Powered By Blogger

Tuesday, December 29, 2009

SQL interview Questions and Answers


MS-SQL Server

Microsoft SQL server is a relational database management system. SQL Server offers a high level of security, reliability and scalability depending on the business needs. The server offers a wide data storage, full text query search, buffer management, logging and transaction, fast data retrieval etc. it offers a variety of replication (making copies) services to avoid losing data. It offers SQL Server Reporting Services for data gathered from the database.

Database:
A database is similar to a data file in that it is a storage place for data. Like a data file, a database does not present information directly to a user; the user runs an application that accesses data from the database and presents it to the user in an understandable format. Database systems are more powerful than data files in that data is more highly organized. In a well-designed database, there are no duplicate pieces of data that the user or application must update at the same time.

Related pieces of data are grouped together in a single structure or record, and relationships can be defined between these structures and records. When working with data files, an application must be coded to work with the specific structure of each data file. In contrast, a database contains a catalog that applications use to determine how data is organized. Generic database applications can use the catalog to present users with data from different databases dynamically, without being tied to a specific data format.

A database typically has two main parts: first, the files holding the physical database and second, the database management system (DBMS) software that applications use to access data. The DBMS is responsible for enforcing the database structure, including: - maintaining relationships between data in the database. Ensuring that data is stored correctly and that the rules defining data relationships are not violated. - recovering all data to a point of known consistency in case of system failures.

Relational Database:
Although there are different ways to organize data in a database, relational databases are one of the most effective. Relational database systems are an application of mathematical set theory to the problem of effectively organizing data. In a relational database, data is collected into tables (called relations in relational theory).

A table represents some class of objects that are important to an organization. For example, a company may have a database with a table for employees, another table for customers, and another for stores. Each table is built of columns and rows (called attributes and tuples in relational theory). Each column represents some attribute of the object represented by the table. For example, an Employee table would typically have columns for attributes such as first name, last name, employee ID, department, pay grade, and job title.

Each row represents an instance of the object represented by the table. For example, one row in the Employee table represents the employee who has employee ID 12345. When organizing data into tables, you can usually find many different ways to define tables. Relational database theory defines a process called normalization, which ensures that the set of tables you define will organize your data effectively.

To Create DB: CREATE DATABASE DatabaseName

What is SQL what its uses and its component

Structured Query Language (SQL) is foundation for all relational database systems. Most of the large-scale databases use the SQL to define all user and administrator interactions. QL is Non-Procedural language. It allow the user to concentrate on specifying what data is required rather than concentrating on the how to get it.
The DML component of SQL comprises four basic statements:
* SELECT to get rows from tables
* UPDATE to update the rows of tables
* DELETE to remove rows from tables
* INSERT to add new rows to tables

What is the difference between SQL and T-SQL? Why would a company use one over the other?
ANSI SQL is the standard Structured Query Language. Most database vendors support SQL. T-SQL is Microsoft's "flavor" of SQL; it is ANSI SQL with Microsoft's extensions. A company could choose to use T-SQL over SQL if they have a database application that communicates with a MS SQL Server database only. Therefore a developer could use the "extras" for improved performance, ease of SQL coding, etc. A company could chose SQL because a front-end may have to communicate with several relational database management systems (RDBMs) therefore a programmer could rely on the fact that most database understand ANSI SQL.

Provide all the built in string function of SQL SERVER:

ASCII, NCHAR, SOUNDEX, CHAR, PATINDEX, SPACE, CHARINDEX, REPLACE, STR, DIFFERENCE, QUOTENAME, STUFF, LEFT, REPLICATE, SUBSTRING, LEN, REVERSE, UNICODE, LOWER, RIGHT, UPPER, LTRIM, RTRIM.

How to get number of Maximum connection can be establish to SQL
Select @@MAX_Connections.

Different index configurations table in SQL:

In SQL table can have following index configurations just like: - No indexes, A clustered index, A clustered index and many non-clustered indexes, A non-clustered index, Many non-clustered indexes.

How many objects SQL Server contains: Here is the list of some of the more important database objects database, The transaction log, Assemblies, Tables, Reports, Filegroups, Full-text catalogs, Diagrams, User-defined data types, Views, Roles, Stored procedures, Users, User Defined Functions.

Difference between Extents and Page: Extents: Multiple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

Why we use SET ROWCOUNT in SQL: This syntax is used in SQL Server to stop processing the query after the specified number of rows is returned.

Why we use Unicode in SQL server: Unicode data is stored using the nchar, nvarchar, and ntext data types in SQL Server. Use these data types for columns that store characters from more than one character set. The SQL Server Unicode data types are based on the National Character data types in the SQL-92 standard.

What is a join and List different types of joins: Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins:

• INNER JOIN,
• OUTER JOIN,
• CROSS JOIN.
OUTER JOIN is further classified as
• LEFT OUTER JOINS,
• RIGHT OUTER JOINS and
• FULL OUTER JOINS.

How does .NET and SQL SERVER thread is work

There are two types of threading pre-emptive and Non-preemptive but SQL Server support Non-preemptive and .NET thread model is different. Because SQL have to handle thread in different way for SQLCLR this different thread are known as Tasking of Threads. In this thread there is a switch between SQLCLR and SQL SERVER threads .SQL SERVER uses blocking points for transition to happen between SQLCLR and SQL SERVER threads.

Difference between temp table and table variable
• Temp Tables are created in the SQL Server TEMPDB database and therefore require more IO resources and locking. Table Variables and Derived Tables are created in memory.
• Temp Tables will generally perform better for large amounts of data that can be worked on using parallelism whereas Table Variables are best used for small amounts of data (I use a rule of thumb of 100 or less rows) where parallelism would not provide a significant performance improvement.
• You cannot use a stored procedure to insert data into a Table Variable or Derived Table. For example, the following will work: INSERT INTO #MyTempTable EXEC dbo.GetPolicies_sp whereas the following will generate an error: INSERT INTO @MyTableVariable EXEC dbo.GetPolicies_sp.
• Derived Tables can only be created from a SELECT statement but can be used within an Insert, Update, or Delete statement.
• In order of scope endurance, Temp Tables extend the furthest in scope, followed by Table Variables, and finally Derived Tables.

How many types of local table in SQL define with syntax

There are 2 types of temporary tables, local and global. Local temporary tables are created using a single pound (#) sign and are visible to a single connection and automatically dropped when that connection ends. Global temporary tables are created using a double pound (##) sign and are visible across multiple connections and users and are automatically dropped when all SQL sessions stop referencing the global temporary table.

CREATE TABLE #MyTempTable ( PolicyId INT IDENTITY(1,1) PRIMARY KEY NOT NULL,LastName VARCHAR(50) NOT NULL )

What is SQL tuning: SQL tuning is the process of getting that the SQL statements that an application that will issue that's run in the fastest possible time.
What is SQL injection: SQL injection is a security vulnerability that occurs in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.

What is SET operator in SQL SERVER: SET operators mainly used to combine same type of data from two or more tables. And another thing is that columns and their data type should be same as all the queries have. The column names from the first query will appear in the result.
UNION - It produce rows of first query + rows of 2nd query minus duplicate rows
UNION ALL - It produce rows from both the queries including duplicate rows.

select empid from emp union all select empid from emp_att group by empid
MINUS - Rows that are unique for the 1st query will be retrieved
INTERSECT - common rows from both the queries will be retrieved.
Join is used to select columns from two or more tables.

Can you define ROLLUP in SQL SERVER 2005: ROLLUP work with the "Group By" clause its main functioning comes into existence when we use Group by. We can get sub-total of row by using the Rollup function. When result is return by Group By class first row display the grand total or we can say that the main total.

Syntax: - select firstcolumn,secondcolumn,sum(thirdcolumn) from tablename group by firstcolumn,secondcolumn with rollup order by firstcolumn.

How many records can take clustered index in SQL: A clustered index is a special type of index that reorders the way the records in the table are physically stored. Therefore the table can have only one clustered index.

What is Cascade and Restrict when we use DROP table in SQL SERVER
When we are using Drop table in SQL the syntax is simple. Drop table table_name (CASCADE / RESTRICT) we use cascade to drop table although it have some dependencies just like triggers, storedprocedure, primarykey, foreignkey it will delete first. But if we use restrict a error message is shown on using of DROP if the table have relation Trigger, storedprocedure.
Some Tips when Optimizing SQL Server 2005 Query
1. Turn on the execution plan, and statistics
2. Use Clustered Indexes
3. Use Indexed Views
4. Use Covering Indexes
5. Keep your clustered index small.
6. Avoid cursors
7. Archive old data
8. Partition your data correctly
9. Remove user-defined inline scalar functions
10. Use APPLY
11. Use computed columns
12. Use the correct transaction isolation level

What is SQL Cache Dependency in ASP.NET 2.0: SQL cache dependencies are new technique in ASP.NET 2.0 which can automatically invalidate a cached data object just like a Dataset. When the related data is modified in the database. So for instance if you have a dataset which is tied up to a database tables any changes in the database table will invalidate the cached data object which can be a dataset or a data source. To enable this we need a syntax that is as follows: - aspnet_regSQL -ed -E -d Northwind.

How many types of local tables in SQL SERVER: There are 2 types of temporary tables, local and global. Local temporary tables are created using a single pound (#) sign and are visible to a single connection and automatically dropped when that connection ends. Global temporary tables are created using a double pound (##) sign and are visible across multiple connections and users and are automatically dropped when all SQL sessions stop referencing the global temporary table.

Where .NET CLR and SQL SERVER run: All .net application and SQL Server runs in same process or we can say that on same address because there is no issue of speed because if these two process are run in different process then there may be a speed issue created one process goes fast and other slow may create the problem.

What are Checkpoint in SQL Server: When we done operation on SQL SERVER that is not committed directly to the database. All operation must be logged in to Transaction Log files after that they should be done on to the main database. Checkpoint are the point which alert SQL Server to save all the data to main database if no Check point is there then log files get full we can use Checkpoint command to commit all data in the SQL SERVER. When we stop the SQL Server it will take long time because Checkpoint is also fired.

Explain integration between SQL Server 2005 and Visual Studio 2005: This integration provides wider range of development with the help of CLR for database server. Because CLR helps developers to get flexibility for developing database applications and also provides language interoperability just like Visual C++, Visual Basic .Net and Visual C# .Net. The CLR helps developers to get the arrays, classes and exception handling available through programming languages such as Visual C++ or Visual C# which is use in stored procedures, functions and triggers for creating database application dynamically and also provide more efficient reuse of code and faster execution of complex tasks. We particularly liked the error-checking powers of the CLR environment, which reduces run-time errors.

What is the difference between SQL and PL-SQL: We can get modify, Retrieve by single command or statement in SQL but PL/SQL process all SQL statements one at a time. With PL/SQL, an entire block of statements process in a single command line.SQL is structured query language, various queries are used to handle the database in a simplified manner. While PL/SQL is procedural language contains various types of variable, functions and procedures and other major difference is SQL as the name suggest it is just structured query language whereas PLSQL is a combination of Programming language & SQL.

What is the difference between UNION ALL Statement and UNION

The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION, the reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

Write some disadvantage of Cursor: Cursor plays there row quite nicely but although there are some disadvantage of Cursor. Because we know cursor doing roundtrip it will make network line busy and also make time consuming methods. First of all select query grenade output and after that cursor goes one by one so roundtrip happen. Another disadvantage of cursor is there are too costly because they require lot of resources and temporary storage so network is quite busy.

What is Log Shipping and its purpose: In Log Shipping the transactional log file from one server is automatically updated in backup database on the other server and in the case when one server fails the other server will have the same DB and we can use this as the DDR(disaster recovery) plan.

Monday, December 28, 2009

SQL Server Date format





SQL Server Date format


FORMAT

QUERY

SAMPLE

1

select convert(varchar, getdate(), 1)

12/30/06

2

select convert(varchar, getdate(), 2)

06.12.30

3

select convert(varchar, getdate(), 3)

30/12/06

4

select convert(varchar, getdate(), 4)

30.12.06

5

select convert(varchar, getdate(), 5)

30-12-06

6

select convert(varchar, getdate(), 6)

30 Dec 06

7

select convert(varchar, getdate(), 7)

Dec 30, 06

10

select convert(varchar, getdate(), 10)

12-30-06

11

select convert(varchar, getdate(), 11)

06/12/30

101

select convert(varchar, getdate(), 101)

12/30/2006

102

select convert(varchar, getdate(), 102)

2006.12.30

103

select convert(varchar, getdate(), 103)

30/12/2006

104

select convert(varchar, getdate(), 104)

30.12.2006

105

select convert(varchar, getdate(), 105)

30-12-2006

106

select convert(varchar, getdate(), 106)

30 Dec 2006

107

select convert(varchar, getdate(), 107)

Dec 30, 2006

110

select convert(varchar, getdate(), 110)

12-30-2006

111

select convert(varchar, getdate(), 111)

2006/12/30

Time Formats

8 or 108

select convert(varchar, getdate(), 8)

00:38:54

9 or 109

select convert(varchar, getdate(), 9)

Dec 30 2006 12:38:54:840AM

14 or 114

select convert(varchar, getdate(), 14)

00:38:54:840




























You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample statement

Output

select replace(convert(varchar, getdate(),101),'/','')

12302006

select replace(convert(varchar, getdate(),101),'/','') + replace(convert(varchar, getdate(),108),':','')

12302006004426






Stored Procedure vs User Define Function in SQL

Stored Procedures vs. User Defined Functions

Stored Procedure:

A stored procedure is an already written SQL statement that is saved in the database. If you find yourself using the same query over and over again, it would make sense to put it into a stored procedure. When you put this SQL statement in a stored procedure, you can then run the stored procedure from the database's command environment.

Stored procedure can reduced network traffic and latency, boosting application performance. Stored procedure execution plans can be reused, staying cached in SQL Server's memory, reducing server overhead. Stored procedures help promote code reuse. Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients. Stored procedures provide better security to your data.

Create Procedure GetSalesById
(
@Id int,
@Sales money OUTPUT
)
As
SELECT @Sales = sales
FROM sample
WHERE id = @Id

Running the stored procedure:

GetSalesById.
Passing it two parameters:
@Id = 1
@Sales = (an output parameter)
It returned the value: 5000.

CREATE PROCEDURE usp_adduser
@login varchar(20),
@pswd varchar(20),
@f_name varchar(25),
@l_name varchar(35) //datatype and size should match the table definition
AS
INSERT INTO USERLIST (login, pswd, f_name, l_name)
VALUES (@login, @pswd, @f_name, @l_name)

To Execute:

exec usp_adduser 'dnelson', 'dean2003', 'Dean'

User-Defined Functions:

Microsoft has introduced the concept of User-Defined Functions that allow you to define your own T-SQL functions that can accept zero or more parameters and return a single scalar data value or a table data type.
There are three types of User-Defined functions in SQL Server 2000 and they are

1. Scalar,
2. Inline Table-Valued and
3. Multi-statement Table-valued.

Scalar User-Defined Function
A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value. Below is an example that is based in the data found in the NorthWind Customers Table.

Below is an example that is based in the data found in the NorthWind Customers Table.

CREATE FUNCTION whichContinent
(@Country nvarchar(15))
RETURNS varchar(30)
AS
BEGIN
declare @Return varchar(30)
select @return = case @Country
when 'Argentina' then 'South America'
when 'Belgium' then 'Europe'
when 'Brazil' then 'South America'
when 'Canada' then 'North America'
when 'Denmark' then 'Europe'
when 'Finland' then 'Europe'
when 'France' then 'Europe'
else 'Unknown'
end

return @return
end

Execute:

print dbo.WhichContinent('Argentina')


Because this function returns a scalar value of a varchar(30) this function could be used anywhere a varchar(30) expression is allowed such as a computed column in a table, view, a T-SQL select list item. Below are some of the examples that I was able to use after creating the above function definition.

Inline Table-Value User-Defined Function

An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

Multi-statement Table-Value User-Defined Function

A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, I can use it in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

Benefits of User-Defined Functions

The benefits to SQL Server User-Defined functions are numerous. First, we can use these functions in so many different places when compared to the SQL Server stored procedure. The ability for a function to act like a table (for Inline table and Multi-statement table functions) gives developers the ability to break out complex logic into shorter and shorter code blocks. This will generally give the additional benefit of making the code less complex and easier to write and maintain. In the case of a Scalar User-Defined Function, the ability to use this function anywhere you can use a scalar of the same data type is also a very powerful thing. Combining these advantages with the ability to pass parameters into these database objects makes the SQL Server User-Defined function a very powerful tool.

Difference:

SQL Server user-defined functions and stored procedure offer similar functionality. Both allow you to create bundles of SQL statements that are stored on the server for future use. This offers you a tremendous efficiency benefit, as you can save programming time by:

Reusing code from one program to another, cutting down on program development time
Hiding the SQL details, allowing database developers to worry about SQL and application developers to deal only in higher-level languages Centralize maintenance, allowing you to make business logic changes in a single place that automatically affect all dependent applications
At first glance, functions and stored procedures seem identical. However, there are several subtle, yet important differences between the two:

Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL statement.

Procedure can return zero or n values whereas function can return one value which is mandatory.

Procedures can have input, output parameters for it whereas functions can have only input parameters.

Procedure allows select as well as DML statement in it whereas function allow only select statement in it.

Functions can be called from procedure whereas procedures cannot be called from function.

Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.

We can go for transaction management in procedure whereas we can't go in function.

Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

Thursday, December 24, 2009

upload image to database (image format) in MS-Sql server and MY-SQL

MS-SQL server
create table:


create table imgtab(idd int identity(1,1), imgsrc image)


aspx.vb


Dim intImageSize As Int64
Dim strImageType As String
Dim ImageStream As Stream
' intImageSize = PersonImage.PostedFile.ContentLength
intImageSize = fup1.PostedFile.ContentLength
strImageType = fup1.PostedFile.ContentType
ImageStream = fup1.PostedFile.InputStream
Dim ImageContent(intImageSize) As Byte
Dim intStatus As Integer
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
Dim myCommand As New SqlCommand("insert into
imgtab values ( @imgsamgetimage )'", Conn)
myCommand.Parameters.Add("@imgsamgetimage", SqlDbType.Image, ImageContent.Length).Value = ImageContent
myCommand.ExecuteNonQuery()
Conn.Close()


MY-SQL Server:

Create Table:

 CREATE TABLE `cust_file` (              
`id` int(11) NOT NULL auto_increment,
`customer_id` int(11) default NULL,
`filename` varchar(255) default NULL,
`filedata` blob,
`contenttype` varchar(255) default NULL,
`length` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1


C#:

 public void Mysql_File_Save(string sConnString, int nCustId, byte[] bData, string sName, string sContentType, int nContentLength)
{
using (MySql.Data.MySqlClient.MySqlConnection oConn =
new MySql.Data.MySqlClient.MySqlConnection(sConnString))
{
oConn.Open();

MySql.Data.MySqlClient.MySqlCommand oCommand = oConn.CreateCommand();
oCommand.Connection = oConn;


//Add new
oCommand.CommandText = "insert into cust_file(customer_id, filename, filedata, contenttype, length) " +
"values( ?in_customer_id, ?in_filename, ?in_filedata, ?in_contenttype, ?in_length)";
//oCommand.CommandType = CommandType.StoredProcedure;

MySql.Data.MySqlClient.MySqlParameter oParam =
oCommand.Parameters.Add("?in_customer_id",
MySql.Data.MySqlClient.MySqlDbType.Int64);
oParam.Value = nCustId;
oParam = oCommand.Parameters.Add("?in_filename",
MySql.Data.MySqlClient.MySqlDbType.VarChar, 255);
oParam.Value = sName;
oParam = oCommand.Parameters.Add("?in_filedata",
MySql.Data.MySqlClient.MySqlDbType.Blob);
oParam.Value = bData;
oParam = oCommand.Parameters.Add("?in_contenttype",
MySql.Data.MySqlClient.MySqlDbType.VarChar, 255);
oParam.Value = sContentType;
oParam = oCommand.Parameters.Add("?in_length",
MySql.Data.MySqlClient.MySqlDbType.Int64);
oParam.Value = nContentLength;

oCommand.ExecuteNonQuery();
oConn.Close();

}
}

Anyway it allows us to write code such as:
 byte[] bData = FileToArray("f:\\n1jpg.jpg");
Mysql_File_Save("Database=sakila;Data Source=192.168.10.4;User id=stefan;Password=pekka",
1, bData, "N1jpg", MimeType("f:\\n1jpg.jpg"), bData.Length);

Source:

http://www.programmingado.net/c-27/a-141/Insert-blob-into-MySQL.aspx

http://bytes.com/topic/asp-net/answers/342898-how-store-retrieve-array-bytes-mysql

http://www.dotnetspider.com/forum/194010-save-retrive-image-from-to-mysql-database-using-asp-net-c-language.aspx



Thumbnail photos in gridview using handler file

thumnail.aspx


<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" Visible="False" Width="50%">

<Columns>
<asp:TemplateField HeaderText="Absentees">
<ItemTemplate>
<asp:CheckBox ID="chk_absentees2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Photo">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="20px"
ImageUrl='<%# "Handler_Student.ashx?id=" & Eval("stud_id") %>' Width="20px" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="stud_name" HeaderText="Name"
SortExpression="stud_name" />
<asp:BoundField DataField="stud_id" HeaderText="Student ID"
SortExpression="stud_id" />
<asp:BoundField DataField="Course" HeaderText="Course"
SortExpression="Course" />
<asp:BoundField DataField="department" HeaderText="Department"
SortExpression="department" />
<asp:BoundField DataField="stud_year" HeaderText="Year"
SortExpression="stud_year" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
</asp:GridView>


thumnail.aspx.vb


Public Sub bind_year()

str = Convert.ToString(System.DateTime.Now.ToShortDateString())
If List_dept.Visible = False Then
If List_year.SelectedIndex = -1 Then
Else

lbl_status.Visible = True
btn_absent.Visible = True
lbl_status.Text = List_course.SelectedItem.Text & " " & List_year.SelectedItem.Text & " Year Student Details."

passquery = "select stud_id,stud_name,course,department,stud_year from student_details where course='" & List_course.SelectedValue.ToString() & "' and stud_year='" & List_year.SelectedItem.Text & "' and Joined_in='" & branchid & "' and stud_id not in(select studid from student_attendance where att_date = '" + str + "')"
Call DBConnect(Conn)
Obj.Pr_Bind_Grid(Conn, passquery, GridView1, "No Details available")
If GridView1.Rows.Count = 0 Then
btn_absent.Visible = False
lbl_grid.Visible = True
End If
End If
Else
If List_dept.Text = "" Then
lbl_status.Visible = False
GridView1.Visible = False
btn_absent.Visible = False
Response.Write("<script>alert ('Select Department')</script>")
Else
If List_year.Visible = False Then
Else
If List_year.SelectedIndex = -1 Then
Else


'List_year.SelectedIndex = 0
lbl_status.Visible = True
btn_absent.Visible = True
lbl_status.Text = List_course.SelectedItem.Text & " (" & List_dept.SelectedItem.Text & ") " & List_year.SelectedItem.Text & " Year Student Details."
passquery = "select stud_id,stud_name,course,department,stud_year from student_details where course='" & List_course.SelectedValue.ToString() & "' and department='" & List_dept.SelectedValue.ToString() & "' and stud_year='" & List_year.SelectedItem.Text & "' and Joined_in='" & branchid & "' and stud_id not in(select studid from student_attendance where att_date = '" + str + "')"
Call DBConnect(Conn)
Obj.Pr_Bind_Grid(Conn, passquery, GridView1, "No Details available")
If GridView1.Rows.Count = 0 Then
btn_absent.Visible = False
lbl_grid.Visible = True
End If
End If
End If

End If

End If
GridView1.DataBind()
Conn.Close()
End Sub


Handler_Student.ashx


<%@ WebHandler Language="VB" Class="Handler_Student" %>

Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration

Public Class Handler_Student : Implements IHttpHandler
Dim con As New SqlConnection
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Try
Call DBConnect(con)
Dim sql As String = "Select photo from student_details where stud_id=@staff_id"
Dim cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("@staff_id", System.Data.SqlDbType.VarChar, 50).Value = context.Request.QueryString("id")
cmd.Prepare()
Dim dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
context.Response.BinaryWrite(DirectCast(dr("photo"), Byte()))
Catch ex As Exception

End Try
End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property

End Class

Thursday, December 17, 2009

Regular Expression in asp.net


This table lists the regular expressions which were used in this sample code, the data type each is intended to recognize, and some examples of strings that each regular expression accepts (matches) and rejects (does not match).

data type regular expression accepts rejects
whitespace /^\s+$/ spaces, tabs, etc. 0 a
single letter /^[a-zA-Z]$/ a A 0 . -
alphabetic string /^[a-zA-Z]+$/ aAbB a1 23
single digit /^\d/ 0 00 1a
single letter or digit /^([a-zA-Z]|\d)$/ 0 a 00 1a
alphanumeric string /^[a-zA-Z0-9]+$/ a1b2 2.5 1.a
integer /^\d+$/ 0 23 23.5
signed integer /^(+|-)?\d+$/ -1 +12 -1.1
floating point number /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/ 1.1 .9 8. -1.1 .
signed float /^(((+|-)?\d+(\.\d*)?)|((+|-)?(\d*\.)?\d+))$/ -1.1 1.1 .9 8. 1a
email address /^.+\@.+\..+$/ a@b.c a@b




JavaScript

Javascript function to check textbox empty.

function UnamePwdValidation()
{
if (document.getElementById("<%=Txt_UserName.ClientID%>").value=="")
{
alert("Enter Username");
document.getElementById("<%=Txt_UserName.ClientID%>").focus();
return false;
}
if(document.getElementById("<%=Txt_Password.ClientID %>").value=="")
{
alert("Enter Password");
document.getElementById("<%=Txt_UserName.ClientID %>").focus();
return false;
}
}

< asp:ImageButton ID="Submit" OnClientClick="return UnamePwdValidation()" runat="server" ImageUrl="images\Go.jpg" TabIndex="3" /
>


Javascript function to allow only alphabets (lower and upper case).

function AllowCharacterOnly(myevent)
{
var Val = (myevent.which) ? myevent.which : myevent.keyCode
if ((Val > 64 && Val <> 96 && Val < type="text" id="txtChracter" onkeypress="return AllowCharacterOnly(event)" style="color: rgb(255, 102, 0); font-weight: bold;">Javascript to allow user to enter only numeric value.


function AllowNumericValue(myevent)
{
var charVal = (myevent.which) ? myevent.which : myevent.keyCode
if (charVal > 31 && (charVal <> 57))
{
return false;
}
return true;

}


input type="text" id="Text2" onkeypress="return AllowNumericCharacters(event)"

Javascript function to show an alert if user entered a non numeric value.

function ValidationCheckforNumeric(txtVal)
{
var len = txtVal.value.length;
var charVal = 0;
for (var i=0;i
{
charVal = txtVal.value.charCodeAt(i);
if (!((charVal >= 48 && charVal <= 57))) { alert("Only Numeric Values are Allowed"); txtVal.value = ''; txtVal.focus(); return false; } } return true; } input type="text" id="txtNumber" onchange='ValidationCheckforNumeric(this)' Javascript code for checking null value in Textbox.

function CheckForEmptyTextbox()
{
var s;
var txtValue;
txtValue = document.getElementById('TextBox1');
if (txtValue.value == '')
{
s = confirm('TextBox1 is blank, do you want to continue?');
return s;
}
return true;

}

Button1.Attributes.Add("onclick", "javascript: CheckForEmptyTextbox();");

On button click - how to bring up browsers emailing box using javascript.

INPUT TYPE="button" VALUE="Send Email." onClick = "parent.location= 'mailto:mymailid@gmail.com'"

Show Timer on status bar using Javascript

function showtime ()
{

var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = "" + ((hours >12) ? hours -12 :hours)
timeValue += ((minutes <>= 12) ? " P.M." : " A.M."

window.status = timeValue;

}

Call this function on load of the form.

Check the browser type using javascript.

if(navigator.appName=="Netscape")
{
alert("Browser is Netscape Navigator.");
}
else if (navigator.appName == "Microsoft Internet Explorer")
{
alert("Browser is Microsoft Internet Explorer.");
}
else
{
alert("Neither Netscape Navigator nor Internet Explorer.");
}

Set Control Focus using Javascript code.

body onload="document.forms[0]['TextBox1'].focus();"

PopUp Window

window.open('pop_up.html', 'popup', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=200,height=130')

Cookies (JavaScript)

http://www.pages.org/javascript/index.html



Tuesday, December 15, 2009

Set the DateFormat in Indian Format (dd-MM-yyyy)


To View Date in Indian Format (dd-MM-yyyy)

By Fixing the Date format(Our desired) throughout the Application By doing this in .ASAX File

In Global.asax

using System.Globalization;
using System.Threading;

protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo inf = new CultureInfo("en-US");
inf.DateTimeFormat.ShortDatePattern = "dd--MM--yyyy";
inf.DateTimeFormat.DateSeparator = "--";
Thread.CurrentThread.CurrentUICulture = inf;
Thread.CurrentThread.CurrentCulture = inf;
}

In Default.aspx

Label4.Text = DateTime.Now.ToShortDateString();




Monday, December 14, 2009

Constructors and Types of Constructors in C#



Constructor:

* Constructor has same name as class name.
* Constructor is used to initialize an object (instance) of a class.
* Constructor is a like a method without any return type.
* Constructor follows the access scope (Can be private, protected, public, Internal and external).
* Constructor can be overloaded.

Broadly speaking, it is a method in the class which gets executed when its object is created. Usually we put the initialization code in the constructor.

C# supports two types of constructor:

  • a class constructor static constructor and an
  • instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments.
Non-static constructors are inline and are faster.

Constructors generally following types :

* Default Constructor
* Parametrized constructor
* Private Constructor
* Static Constructor
* Copy Constructor


Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.

You need not to define default constructor it is implicitly defined.

class Program
{
class c1
{
int
a, b;

public c1()
{
this.a =
10;
this.b = 20;
}

public
void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}",
b);
}
}

static
void
Main(string[] args)
{
// Here when you create instance
of the class default constructor will be called.
c1
ob1 = new c1();
ob1.display();
Console.ReadLine();
}
}

Note: In the above practical example if you don't create a constructor still there will be a default constructor, which will initialize the data members of the class with some legal values.

Parameterized constructor

Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.

class Program
{
class c1
{
int
a, b;

public
c1(int x, int
y)
{
this.a = x;
this.b =
y;
}

public
void
display()
{
Console.WriteLine("Value of a: {0}",
a);
Console.WriteLine("Value of b: {0}",
b);
}
}

static
void
Main(string[] args)
{
// Here when you create instance
of the class parameterized constructor will be called.
c1
ob1 = new c1(10,
20);
ob1.display();
Console.ReadLine();
}
}

Private Constructor

Private constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.

class Program
{

class
c1
{
int a, b;

// Private constructor declared
here
private c1(int x, int
y)
{
this.a = x;
this.b =
y;
}

public
static c1
create_instance()
{
return new c1(12,
20);
}

public
void
display()
{
int z = a +
b;
Console.WriteLine(z);
}
}

static
void
Main(string[] args)
{
// Here the class is initiated
using a static method of the class than only you can use private
constructor
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
Static constructors:

Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.

class Program
{

public class test
{
static string name;
static int age;

static

test()
{
Console.WriteLine("Using static constructor to initialize static
data members"
);
name = "John Sena";
age
= 23;
}

public
static void
display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}

}

static
void
Main(string[] args)
{
test.display();
Console.ReadLine();
}
}

Copy Constructor

If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied.

class Program
{

class
c1
{
int a, b;

public

c1(int x, int y)
{
this.a = x;
this.b = y;
}

// Copy construtor
public c1(c1 a)
{
this.a =
a.a;
this.b = a.b;
}

public
void display()
{
int z
= a + b;
Console.WriteLine(z);
}
}

static
void
Main(string[] args)
{
c1
ob1 = new c1(10,
20);
ob1.display();
// Here we are using copy constructor. Copy constructor is using the
values already defined with ob1
c1 ob2 =
new c1(ob1);
ob2.display();
Console.ReadLine();
}
}

Note: Copy constructor sets behavior during runtime. It is shallow copying.

The following are the Access Modifiers for constructors,

Public : A constructor that is defined as public will be called whenever a class is instantiated.

Protected : A constructor is defined as protected in such cases where the base class will initialize on its own whenever derived types of it are created.

Private : A constructor is defined as private in such cases whenever a class which contains only static members has to be accessed will avoid the creation of the object for the class.

Internal : An internal constructor can be used to limit concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.

External : When a constructor is declared using an extern modifier, the constructor is said to be an external constructor.


General:

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

FAQs Regd. Constructors :

1. Is the Constructor mandatory for the class ?

Yes, It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say for example we have the private constructor in the class then it is of no use as it cannot be accessed by the object, so practically it is no available for the object. In such conditions it will raise an error.

2. What if I do not write the constructor ?

In such case the compiler will try to supply the no parameter constructor for your class behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor ( with or without parameters), then compiler will not make any such attempt.

3. What if I have the constructor public myDerivedClass() but not the public myBaseClass() ?

It will raise an error. If either the no parameter constructor is absent or it is in-accessible ( say it is private ), it will raise an error. You will have to take the precaution here.

4. Can we access static members from the non-static ( normal ) constructors ?

Yes, We can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.

5. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.




Source:

1: http://www.c-sharpcorner.com/UploadFile/neerajsaluja/ConstructorsInCSharp11152005233222PM/ConstructorsInCSharp.aspx

2: http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx

Reverse String - HTTP to HTTPS - Image Type(without checking extensions)

C#

string str = TextBox1.Text.Trim();
char[] chr = str.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i =0 ; i < chr.Length; i++) { sb.Append(chr[(chr.Length-1)-i].ToString());
}
Label1.Text = sb.ToString();



Change the Current page from HTTP to HTTPS

if (!Request.IsSecureConnection)
{
//to get the current URL
UriBuilder uri = new UriBuilder(Page.Request.Url);
uri.Scheme = Uri.UriSchemeHttps;

// Redirect to https
Response.Redirect(uri.ToString());
}

Find Out the Image Type without Checking its Extension
Image imgUp = Image.FromFile(Server.MapPath("~/images/abc.jpg"));
if (imgUp.RawFormat.Equals(ImageFormat.Jpeg))
Response.Write("JPEG");
else if (imgUp.RawFormat.Equals(ImageFormat.Gif))
Response.Write("GIF");


first Monday of every month in an year

C#:

StringBuilder sb = new StringBuilder();
for (int mth = 1; mth <= 12; mth++)
{
DateTime dt = new DateTime(2010, mth, 1);
while (dt.DayOfWeek != DayOfWeek.Monday)
{
dt = dt.AddDays(1);
}
sb.Append(Convert.ToString(dt.ToLongDateString() + " ::: " )); } Label2.Text = sb.ToString();


VB.Net:

For mth As Integer = 1 To 12
Dim dt As New DateTime(2010, mth, 1)
Do While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(1)
Loop
Console.WriteLine(dt.ToLongDateString())
Next mth
Console.ReadLine()

Saturday, December 12, 2009

How to create a secured and locked folder in Windows XP

Steps

To secure my "topsecret" folder in D directory.






Create a notepad file with this content:

ren topsecret Fonts.{21EC2020-3AEA-1069-A2DD-08002B30309D}

Save the file as "loc.bat" in D directory itself (Where your folder is located. Ex: "topsecret").




Create another one notepad file with this content:

ren Fonts.{21EC2020-3AEA-1069-A2DD-08002B30309D} topsecret

Save the file as "key.bat" in D
directory itself (Where your folder is located. Ex: "topsecret").




click "loc.bat" file to lock our "topsecret" folder.

Now the "topsecret" folder will turn into fonts and clicking on that folder will open the control panel.

To unlock that
"topsecret" folder, click the "key.bat" file.

Now it will work fine......



source: http://www.online-tech-tips.com






Friday, December 11, 2009

write and read a cookie from a client's computer ASP.Net C#

1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores

FirstName
LastName
LastVisit


2. Create the user interface to enter FirstName and LastName. The HTML for the webform is as shown below.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesExample.aspx.cs" Inherits="CookiesExample" % >
<html >
<head runat="server" >
<title >Write a cookie to the client computer </title >
</head >
<body >
<form id="form1" runat="server" >
<table >
<tr >
<td style="width: 100px" >
First Name </td >
<td style="width: 100px" >
<asp:TextBox ID="FirstNameTextBox" runat="server" > </asp:TextBox >
</td >
</tr >
<tr >
<td style="width: 100px" >
Last Name
</td >
<td style="width: 100px" >
<asp:TextBox ID="LastNameTextBox" runat="server" > </asp:TextBox >
</td >
</tr >
<tr >
<td style="width: 100px" >
</td >
<td style="width: 100px" >
<asp:Button ID="WriteCookieButton" runat="server" Text="Write Cookie" OnClick="WriteCookieButton_Click" / >
</td >
</tr >
<tr >
<td style="width: 100px" >
</td >
<td style="width: 100px" >
<asp:Button ID="ReadCookieButton" runat="server" Text="Read Cookie" OnClick="ReadCookieButton_Click" / >
</td >
</tr >
</table >
</form >
</body >
</html >

3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.


protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}

4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.


protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}

5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.


Source:

http://venkataspinterview.blogspot.com/2008/11/write-and-read-cookie-aspnet-interview.html



Bind an XML to DropDownList ASP.Net C#

create an XML file in ur project

Employees.xml

<Employees >
<Employee >
<Name >David </Name >
<ID >101 </ID >
<IsActive >true </IsActive >
</Employee >
<Employee >
<Name >Tom </Name >
<ID >102 </ID >
<IsActive >true </IsActive >
</Employee >
<Employee >
<Name >Rick </Name >
<ID >103 </ID >
<IsActive >false </IsActive >
</Employee >
<Employee >
<Name >Mark </Name >
<ID >104 </ID >
<IsActive >true </IsActive >
</Employee >
</Employees >



--------------------------------------------------------

Code sample:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Employees.xml"));

DataView DV = DS.Tables["Employee"].DefaultView;
DV.RowFilter = "IsActive='true'";
DV.Sort = "Name asc";

DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}

-------------------------------------------------------

Code Explanation:

1.
Read the XML data from Employees.xml file into a DataSet. We make use of the ReadXml() method. ReadXml method loads the XML data into the dataset DS. DS.ReadXml(Server.MapPath("Employees.xml"));

2. Now you have the Data in a relational format in the dataset. Create a DataView on the employees table in the DataSet. The DefaultView property of DataTable returns the DataView.
DataView DV = DS.Tables["Employee"].DefaultView;

3. After you have created the DataView, apply the RowFilter, to select only the active employees. You apply the RowFilter as shown below.
DV.RowFilter = "IsActive='true'";

4. Now sort the data in the DataView in ascending order. We sort the data on the Name column. You can apply the sort expression on a dataview as shown below.
DV.Sort = "Name asc";

5. Finally set the DataSource, DataValueField and DataTextField properties of the dropdownlist and call the DataBind() method as shown in the below code.
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();


Untill now we have seen how to bind an XML file to dropdownlist. We have also seen how to create a DataView on DataTable. DataView is used for sorting and filtering the data. Now we have to get the SelecteValue and SelectedItem Text of a dropdownlist. To achieve this, follow the below steps.

1. Set the autopostback property of the dropdownlist to true. So, when ever a selection in the dropdownlist changes, the webform is posted back to the server automatically.

2. In the DropDownList1_SelectedIndexChanged event handler we can capture the employee name and id using the DropDownList1.SelectedItem.Text and DropDownList1.SelectedItem.Value properties as shown below.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}



Source: http://venkataspinterview.blogspot.com/2008/10/bind-xml-file-to-dropdownlist.html