Professional Documents
Culture Documents
Do you have fun with SQL Server?. Let's start fun with SQL Server. Suppose you want to swap the values of two columns of a table in SQL Server, how could you achieve this tricky task?. Actually, it is simple and so funny. Suppose you have a Customer table in the database with the following data and you want to interchange the values of columns Name and Address then how do you do?
SELECT * FROM CUSTOMER
Don't worry, to do this task, you need to just write a simple update query for Customer table like as :
UPDATE Customer SET Name=Address , Address=Name
Now After query execution you will find the the values of columns Name and Address have been interchanged, that's so cool.
SELECT * FROM CUSTOMER
By default, SQL Server 2000, 2005, 2008 and 2008R2 doesn't provide intellisense like Visual Studio. While writing T-SQL statements, we need to recall the database table structure (including columns, their data types, size) and other database objects structure like stored procedure, view and functions again and again. Sometimes it becomes tedious task. Don't worry, we have some tools for enabling intellisense in SQL Server like as SQL Complete, SQL Developer Bundle that are free to use and also have their standard versions for advanced features.
SQL Complete
This is a very use ful tools and provide good intellisense help in SQL Server. First download its free or standard version and installed it. After installing you will see a new menu option "SQL Complete" in SQL Server menu as shown in fig.
Now, whenever you will wrie your T-SQL query, it will provides the intellisense help like Visual Studio like as :
Now, whenever you will wrie your T-SQL query, it will provides the intellisense help like Visual Studio like as :
Fetch Next From cur Into @trgName End Close cur Deallocate cur
difference between primary key and foreign key. For more help about keys in SQL Server refer the article Different Types of SQL Keys.
Difference between Primary Key & Foreign Key Primary Key Foreign Key Primary key uniquely identify a record in the table. Foreign key is a field in the table that is primary key in another table. Primary Key can't accept null values. Foreign key can accept multiple null value. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. While Foreign key is non-clustered index. We can have only one Primary key in a table. We can have more than one foreign key in a table.
1. To test data manipulation errors and take suitable actions based on the errors. 2. To find the difference between the state of a table before and after the data modification and take actions based on that difference.
1. 2. 3. 4. 5. 6. 7. 8.
CREATE TRIGGER trg_Emp_Ins ON Employee FOR INSERT AS begin SELECT * FROM INSERTED -- show data in Inserted virtual table SELECT * FROM DELETED -- show data in Deleted virtual table end
In the bwlow
1. --Now insert a new record in Employee table to see data with in Inserted virtual tables 2. INSERT INTO Employee(EmpID, Name, Salary) VALUES(3,'Avin',23000) 3. SELECT * FROM Employee
1.
--Now update the record in Employee table to see data with in Inserted and Deleted Virtual tables 2. Update Employee set Salary=43000 where EmpID=3 3. SELECT * FROM Employee
We could not create the virtual tables or modify the data with in the virtual tables. When we use the OUTPUT clause in SQL Server 2005, 2008 & 2012, then virtual tables are automatically created and managed by SQL Server.
and executed every time it is called. For more about stored procedure and function refer the articles Different types of Stored Procedure and Different types of Function.
Basic Difference
1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values). 2. Functions can have only input parameters for it whereas Procedures can have input/output parameters . 3. Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters.. 4. Functions can be called from Procedure whereas Procedures cannot be called from Function.
Advance Difference
1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it. 2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement. 3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be. 4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables. 5. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations. 6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function. 7. We can go for Transaction Management in Procedure whereas we can't go in Function.
Does practice to avoid the insertion of NULL values in the fixed-length (char) field. Since, NULL takes the same space as desired input value for that field. In case of requirement of NULL, use variable-length (varchar) field that takes less space for NULL.
Does practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.
5. -- Avoid 6. SELECT Name,Price FROM tblProduct 7. where ProductID IN (Select distinct ProductID from tblOrder) 8. --Best practice 9. SELECT Name,Price FROM tblProduct 10. where ProductID EXISTS (Select distinct ProductID from tblOrder)
Does practice to avoid Having Clause since it acts as filter over selected rows. Having clause is required if you further wish to filter the result of an aggregations. Don't use HAVING clause for any other purpose.
Avoid Cursors
Does practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server cursor alternative. Please refer the article Cursor Alternative.
Does practice to keep transaction as small as possible since transaction lock the processing tables data during its life. Some times long transaction may results into deadlocks. Please refer the article SQL Server Transactions Management
SET NOCOUNT ON
Does practice to set NOCOUNT ON since SQL Server returns number of rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
15. 16. 17. 18. 19. 20. 21. CREATE PROCEDURE dbo.MyTestProc AS SET NOCOUNT ON BEGIN . . END
Use TRY-Catch
Does practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running transaction may cause deadlock if you have no handle error by using TRY-CATCH. Please refer the article Exception Handling by TRYCATCH
Use Stored Procedure for frequently used data and more complex queries
Does practice to create stored procedure for quaery that is required to access data frequently. We also created stored procedure for resolving more complex task.
2. AS 3. ( 4. SELECT Name,ROW_NUMBER() OVER(PARTITION by Name, Salary ORDER BY Name) 5. AS duplicateRecCount 6. FROM dbo.Employee 7. ) 8. --Now Delete Duplicate Records 9. DELETE FROM TempEmp 10. WHERE duplicateRecCount > 1 1. --See affected table 2. Select * from Employee
For more help about ROW_NUMBER(), please follow the MSDN link.
Here I am creating a semicolon(;) separated list. You can use comma(,) in place of semicolon to make comma separated list.
For SQL Server database mail setup and configuration and more over how to send mail from SQL Server database you can refer this article.
Normal Forms
We organize the data into database tables by using normal forms rules or conditions. Normal forms help us to make a good database design. Generally we organize the data up to third normal form. We rarely use the fourth and fifth normal form. To understand normal forms consider the folowing unnormalized database table. Now we will normalize the data of below table using normal forms.
3. Remove the partial dependencies(A type of functional dependency where a field is only functionally dependent on the part of primary key) of any non-key field. 4. If field B depends on field A and vice versa. Also for a given value of B, we have only one possible value of A and vice versa, Then we put the field B in to new database table where B will be primary key and also marked as foreign key in parent table. 2NF of above 1NF tables is as follows:
6. Make separate table for transitive dependent Field. 3NF of above 2NF tables is as follows:
ID int IDENTITY(1,1) NOT NULL, ProductID int NOT NULL, ProductName varchar(50) NOT NULL, Qty int NOT NULL, Amount decimal(10, 2) NOT NULL ) GO SELECT * FROM ProductsSales --We have the table with below data
22. SELECT @TotalQty = SUM(Qty),@Total = SUM(Amount) FROM ProductsSales WHERE ProductID = @ProductID 23. INSERT INTO @TProductSales(ProductID,ProductName,TotalQty,GrandTotal) VALUES(@ProductID,@ProductName,@TotalQty,@Total) 24. FETCH NEXT FROM Cur_Product INTO @ProductID END 25. --Close and Deallocate Cursor 26. CLOSE Cur_Product 27. DEALLOCATE Cur_Product 28. --See Calculated data SELECT * FROM @TProductSales
) 76. --Insert data to temporary table #Product 77. INSERT INTO #TProduct(ProductID) SELECT DISTINCT ProductID FROM ProductsSales ORDER BY ProductID ASC 78. SELECT @count = COUNT(SNo) FROM #TProduct 79. WHILE (@i <= @count) 80. BEGIN 81. SELECT @ProductID = ProductID FROM #TProduct WHERE SNo = @i 82. SELECT @ProductName = ProductName FROM ProductsSales WHERE ProductID = @ProductID 83. SELECT @TotalQty = SUM(Qty),@Total = SUM(Amount) FROM ProductsSales WHERE ProductID = @ProductID 84. INSERT INTO #TProductSales(ProductID,ProductName,TotalQty,GrandTotal) VALUES(@ProductID,@ProductName,@TotalQty,@Total) 85. SELECT @i = @i + 1 86. END 87. --See Calculated data 88. SELECT * FROM #TProductSales 89. --Now Drop Temporary Tables 90. DROP TABLE #TProduct DROP TABLE #TProductSales
Dynamic Cursors
A dynamic cursor allows you to see the data updation, deletion and insertion in the data source while the cursor is open. Hence a dynamic cursor is sensitive to any changes to the data source and supports update, delete operations. By default dynamic cursors are scrollable.
) GO INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida') 10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi') 11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun') 12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon') 14. GO 15. SELECT * FROM Employee
6. DYNAMIC 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Dynamic_cur_empupdate 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Mohan' 16. Update Employee SET Salary=15000 WHERE CURRENT OF Dynamic_cur_empupdate 17. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name 18. END 19. END 20. CLOSE Dynamic_cur_empupdate 21. DEALLOCATE Dynamic_cur_empupdate 22. SET NOCOUNT OFF 23. Go 24. Select * from Employee
1. -- Dynamic Cursor for DELETE 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Dynamic_cur_empdelete CURSOR 6. DYNAMIC 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Dynamic_cur_empdelete 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Deepak' 16. DELETE Employee WHERE CURRENT OF Dynamic_cur_empdelete 17. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name 18. END 19. END 20. CLOSE Dynamic_cur_empdelete 21. DEALLOCATE Dynamic_cur_empdelete 22. SET NOCOUNT OFF 23. Go 24. Select * from Employee
1. 2. 3. 4. 5. 6. 7. 8. 9.
-- Forward Only Cursor for Delete SET NOCOUNT ON DECLARE @Id int DECLARE @name varchar(50) DECLARE Forward_cur_empdelete CURSOR FORWARD_ONLY FOR SELECT EmpID,EmpName from Employee ORDER BY EmpName OPEN Forward_cur_empdelete
10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24.
IF @@CURSOR_ROWS > 0 BEGIN FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name WHILE @@Fetch_status = 0 BEGIN IF @name='Sonu' DELETE Employee WHERE CURRENT OF Forward_cur_empdelete FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name END END CLOSE Forward_cur_empdelete DEALLOCATE Forward_cur_empdelete SET NOCOUNT OFF Go Select * from Employee
1. -- Keyse Driven Cursor for Delete 2. SET NOCOUNT ON 3. DECLARE @Id int 4. DECLARE @name varchar(50) 5. DECLARE Keyset_cur_empdelete CURSOR 6. KEYSET 7. FOR 8. SELECT EmpID,EmpName from Employee ORDER BY EmpName 9. OPEN Keyset_cur_empdelete 10. IF @@CURSOR_ROWS > 0 11. BEGIN 12. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name 13. WHILE @@Fetch_status = 0 14. BEGIN 15. IF @name='Amit' 16. DELETE Employee WHERE CURRENT OF Keyset_cur_empdelete 17. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name 18. END 19. END 20. CLOSE Keyset_cur_empdelete 21. DEALLOCATE Keyset_cur_empdelete 22. SET NOCOUNT OFF 23. Go Select * from Employee
Open
A Cursor is opened and populated by executing the SQL statement defined by the cursor.
Fetch
When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.
Close
After data manipulation, we should close the cursor explicitly.
Deallocate
Finally, we need to delete the cursor definition and released all the system resources associated with the cursor.
Syntax to Declare Cursor
Declare Cursor SQL Comaand is used to define the cursor with many options that impact the scalablity and loading behaviour of the cursor. The basic syntax is given below
1. 2. 3. 4. 5. 6. 7. DECLARE cursor_name CURSOR [LOCAL | GLOBAL] --define cursor scope [FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward) [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks FOR select_statement --define SQL Select statement FOR UPDATE [col1,col2,...coln] --define columns that need to be updated
A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open cursor is given below:
1. OPEN [GLOBAL] cursor_name --by default it is local
Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:
1. FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n] 2. FROM [GLOBAL] cursor_name 3. INTO @Variable_name[1,2,..n]
Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
1. CLOSE cursor_name --after closing it can be reopen
Deallocate statement delete the cursor definition and free all the system resources associated with the cursor. The basic syntax to close cursor is given below:
1. DEALLOCATE cursor_name --after deallocation it can't be reopen
) GO INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida') 10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi') 11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun') 12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida') 13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon') 14. GO 15. SELECT * FROM Employee
1. 2. 3. 4. 5. 6.
SET NOCOUNT ON DECLARE @Id int DECLARE @name varchar(50) DECLARE @salary int DECLARE cur_emp CURSOR STATIC FOR
7. SELECT EmpID,EmpName,Salary from Employee 8. OPEN cur_emp 9. IF @@CURSOR_ROWS > 0 10. BEGIN 11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary 12. WHILE @@Fetch_status = 0 13. BEGIN 14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary) 15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary 16. END 17. END 18. CLOSE cur_emp 19. DEALLOCATE cur_emp 20. SET NOCOUNT OFF
1. CREATE PROCEDURE usp_InsertEmployee 2. WITH RECOMPILE 3. @flag bit output,-- return 0 for fail,1 for success 4. @EmpID int, 5. @Name varchar(50), 6. @Salary int, 7. @Address varchar(100) 8. AS 9. BEGIN 10. BEGIN TRANSACTION 11. BEGIN TRY 12. Insert into Employee(EmpID,Name,Salary,Address) Values(@EmpID,@Name,@Salary,@Address); 13. set @flag=1; 14. commit TRANSACTION; 15. END TRY 16. BEGIN CATCH 17. rollback TRANSACTION; 18. set @flag=0; 19. END CATCH 20. END
21. 22.
Declare @flag bit --Now Execute this procedure. Every time this procedure will be recompiled 23. EXEC usp_InsertEmployee @flag output,1,'Deepak',14000,'Noida' 24. if @flag=1 25. print 'Successfully inserted' 26. else 27. print 'There is some error'
AS BEGIN BEGIN TRANSACTION BEGIN TRY Insert into Employee(EmpID,Name,Salary,Address) Values(@EmpID,@Name,@Salary,@Address); 39. set @flag=1; 40. commit TRANSACTION; 41. END TRY 42. BEGIN CATCH 43. rollback TRANSACTION; 44. set @flag=0; 45. END CATCH 46. END
47. 48.
Declare @flag bit --Now Execute this procedure with RECOMPILE option, if you want to recompile its execution plan 49. EXEC usp_InsertEmployee @flag output,2,'Jitendra',15000,'Noida' WITH RECOMPILE 50. if @flag=1 51. print 'Successfully inserted' 52. else 53. print 'There is some error'
Note
1. Creating the stored procedure by using "WITH RECOMPILE" option force the SQL Server to recompile the stored procedure every time when it is called. 2. Call the stored procedure by using "WITH RECOMPILE" option in the EXEC command. 3. Altering the procedure will cause the SQL Server to create a new execution plan 4. If SQL Server is restarted or stopped then all the execution plans will be flush from server cache and recreated when the stored procedure is executed after restarting the server. 5. The "Sp_recompile" system defined stored procedure can be called to refresh the query execution plan for a particular stored procedure
Function is a database object in Sql Server. Basically it is a set of sql statements that accepts only input parameters, perform actions and return the result. Function can return only single value or a table. We cant use function to Insert, Update, Delete records in the database table(s). For more about stored procedure and function refer the article Difference between Stored Procedure and Function
Scalar Function
Scalar functions operates on a single value and returns a single value. Below is the list of some useful Sql Server Scalar functions.
System Scalar Function Scalar Function Description abs(-10.67) This returns absolute number of the given number means 10.67. rand(10) This will generate random number of 10 characters. round(17.56719,3) This will round off the given number to 3 places of decimal means 17.567 upper('dotnet') This will returns upper case of given string means 'DOTNET' lower('DOTNET') This will returns lower case of given string means 'dotnet'
ltrim(' dotnet') This will remove the spaces from left hand side of 'dotnet' string. convert(int, 15.56) This will convert the given float value to integer means 15.
Aggregate Function
Aggregate functions operates on a collection of values and returns a single value. Below is the list of some useful Sql Server Aggregate functions.
System Aggregate Function Aggregate Function Description max() This returns maximum value from a collection of values. min() This returns minimum value from a collection of values. avg() This returns average of all values in a collection. count() This returns no of counts from a collection of values.
Scalar Function
User defined scalar function also returns single value as a result of actions perform by function. We return any datatype value from function.
1. --Create a table CREATE TABLE Employee 2. ( 3. EmpID int PRIMARY KEY, 4. FirstName varchar(50) NULL, 5. LastName varchar(50) NULL, 6. Salary int NULL, 7. Address varchar(100) NULL, 8. ) 9. --Insert Data 10. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(1,'Mohan','Chauahn',22000,'Delhi'); 11. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(2,'Asif','Khan',15000,'Delhi'); 12. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(3,'Bhuvnesh','Shakya',19000,'Noida'); 13. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(4,'Deepak','Kumar',19000,'Noida'); 14. --See created table 15. Select * from Employee
16.
--Create function to get emp full name Create function fnGetEmpFullName 17. ( 18. @FirstName varchar(50), @LastName varchar(50) 19. ) 20. returns varchar(101) 21. As 22. Begin return (Select @FirstName + ' '+ @LastName); 23. end
24. 25.
--Now call the above created function Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary from Employee
31. 32.
42.
Insert @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e; 43. --Now update salary of first employee 44. update @Emp set Salary=25000 where EmpID=1; 45. --It will update only in @Emp table not in Original Employee table 46. return 47. end
48. 49.
50.
--Now see the original table. This is not affected by above function update command 51. Select * from Employee
Note
1. Unlike Stored Procedure, Function returns only single value. 2. Unlike Stored Procedure, Function accepts only input parameters. 3. Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in database table(s). 4. Like Stored Procedure, Function can be nested up to 32 level. 5. User Defined Function can have upto 1023 input parameters while a Stored Procedure can have upto 21000 input parameters. 6. User Defined Function can't returns XML Data Type. 7. User Defined Function doesn't support Exception handling. 8. User Defined Function can call only Extended Stored Procedure. 9. User Defined Function doesn't support set options like set ROWCOUNT etc.
We can define xml data type field to NOT NULL or we can provide a default value to it.
We can retrieve data table records as xml data using FORXML clause in SELECT statement. In FORXML Clause we can define three xml mode.
AUTO
It generates output with both element and attribute features in combination with a sub query.
SELECT DeptName, EmpID FROM Employee AS Emp JOIN Department AS Dept ON Emp.DeptID= Dept.DeptID FOR XML AUTO;
Output:
<Dept DeptName="IT"> <Emp EmpID="1" /> <Emp EmpID="2" /> </Dept> <Dept DeptName="HR"> <Emp EmpID="3" /> </Dept> <Dept DeptName="Technical"> <Emp EmpID="4" /> <Emp EmpID="5" /> </Dept>
EXPLICIT
It converts the rowset that is result of the query execution, into an XML document. This mode provides more control over the format of the XML means in which format you want xml you need to define that format in select query.
SELECT 1 tag, NULL parent, EmpID [employee!1!ID], EmpName [employee!1!name], NULL [order!2!date], NULL [department!3!name] FROM Employee UNION ALL SELECT 3, 1, EmpID, NULL, NULL, DeptName FROM Employee e JOIN Department d ON e.DeptID=d.DeptID ORDER BY 3, 1 FOR XML EXPLICIT;
Output
<employee ID="1" name="Shailendra"> <department name="IT" /> </employee> <employee ID="2" name="Mohan"> <department name="IT" /> </employee> <employee ID="3" name="Vipul"> <department name="HR" /> </employee> <employee ID="4" name="Mrinal"> <department name="Technical" /> </employee> <employee ID="5" name="Jitendra"> <department name="Technical" /> </employee>
RAW
It produce a single element or the optionally provided element name for each row in the query result set that is returned by select statement.
SELECT Emp.EmpID, Dept.DeptName Employee as Emp JOIN Department as Dept ON Emp.DeptID= Dept.DeptID FOR XML RAW;
Output
<row EmpID="1" DeptName="IT" /> <row EmpID="2" DeptName="IT" /> <row EmpID="3" DeptName="HR" /> <row EmpID="4" DeptName="Technical" /> <row EmpID="5" DeptName="Technical" />
XQuery Methods
we have following xml data to implement all the XQuery methods given below.
xml.exist()
This method returns a boolean value depends upon the condition in this method like as
1. SELECT @xml.exist('/Suppliers/User[@Email = "bipul.tiwari@ymail.com"]') as Result1 2. SELECT @xml.exist('/Suppliers/User[@Email = "bipul.tiwari@yahoo.com"]') as Result2
xml.query()
This method takes an XQuery statement and returns an instance of the XML data type like as
3. SELECT @xml.query('/Suppliers/User') as Users
4.
xml.value()
This method takes an XQuery statement and returns a single value after type casting like as
5. SELECT @xml.value('/Suppliers[1]/User[1]/@Email', 'VARCHAR(20)') as ResultEmail1 6. SELECT @xml.value('/Suppliers[1]/User[2]/@Email', 'VARCHAR(20)') as ResultEmail2
xml.nodes()
This method takes an XQuery statement and returns a single value after type casting like as
7. SELECT x.value('@UserNo', 'int') AS UserNo, x.value('@Email', 'varchar(50)') AS Email
8. FROM @xml.nodes('/Suppliers/User') TempXML (x) 9. SELECT x.value('../@UserNo', 'int') AS UserNo, x.value('../@Email', 'varchar(50)') AS Email, x.value('@Name', 'varchar(50)') AS ItemName 10. FROM @xml.nodes('/Suppliers/User/Item') TempXML (x)
xml.modify()
This method takes an XQuery statement and modify the xml data like as
11. 12. 13. --Insert node in the end of XML SET @xml.modify ('insert as last into (/Suppliers)[1]') SELECT @xml;
--Update node in xml DECLARE @UserNo int =120 SET @xml.modify ('replace value of (/Suppliers/User/@UserNo) [1] with sql:variable("@UserNo")') 17. SELECT @xml;
18. 19.
--Update node in xml conditionally SET @xml.modify(' replace value of (/Suppliers/User/@UserNo) [1] with ( if (count(/Suppliers/User[1]/Item) > 2) then "3.0" else "1.0" ) ')
20.
SELECT @xml;
21.
--Delete node in xml SET @xml.modify(' delete Suppliers/User/Item[@No=1]') 22. SELECT @xml;
--Delete node in xml depends on condition DECLARE @ItemNo int=1 SET @xml.modify(' delete Suppliers/User/Item[@No=sql:variable("@ItemNo")]') 26. SELECT @xml;
userName varchar(50) primary key, userpwd varchar(50), address varchar(100) ) insert into tbluser(userName,userpwd,address)values('mohan@gmail.com','123456','Delhi'); insert into tbluser(userName,userpwd,address)values('shailendra@gmail.com','123456','Noid a'); insert into tbluser(userName,userpwd,address)values('jitendra@gmail.com','123456','Gurgao n'); insert into tbluser(userName,userpwd,address)values('bipul@gmail.com','123456','Delhi'); select * from tbluser
Now lets look at the following query string in Asp.net. In this we are passing username from TextBox "txtUserID" and userpwd from TextBox "txtpwd" to check user credential.
"SELECT * FROM tbluser WHERE userName = '"+ txtUserID.text +"' and userpwd = '"+ txtPwd.text +"'";
Now hacker will pass the following input to TextBoxes to inject sql attack. What will happen when the below data goes as input?
"SELECT * FROM tbluser WHERE userName = ';Drop table tblusers --' and userpwd = '123'";
Semicolon ; in above statement will terminate the current sql. So, "SELECT * FROM tbluser WHERE UserID = ''" will become a separate statement and after Semi Colon ; it will starts a new sql statement "Drop table tblusers" that will drop our table tbluser. Hence your user details table has been dropped and your database will be unmanaged.
Master Database
1. Master database contains all of the System level information for Sql Server. 2. It contains all system configuration settings details for Sql Server. We can see the system configuration information by using the system defined "SYSCONFIGURES" table.
Select * from SYSCONFIGURES
3. It contains all existing databases details for Sql Server. We can see the database information and where the actual file persists by using the system defined "SYSDATABASES" table
4. It contains all login accounts details for Sql Server. We can see the login account information by using the system defined "SYSXLOGINS" table.
Select * from SYSXLOGINS
5. It contains all users details for Sql Server. We can see the user information by using the system defined "SYSUSERS" table
Select * from SYSUSERS
6. Primary data of Master database is stored in master.mdf file which default size is 11 MB and Master database log is stored in Masterlog.ldf file which default size is 1.25 MB.
TempDB Database
1. TempDB databse contains all temporary objects like temporary tables and temporary stored procedures for Sql Server.The temporary objects are created by preceding # to the temporary object name. Example#tEmp table gets created in school database.
Use School CREATE TABLE #tEmp ( EmpID int EmpName Varchar(50) )
When the above TSQL statement gets executed, if we see at the tempDB, this temporary table will exist there. Note that we create this table in School Database. But it exists in tempDB. We can access #tEmp table from any other database. 2. TempDB database is recreated every time when we re-start the SQL Server. Hence, when the database server gets restarted, the temporary objects will be removed from TempDB database. 3. Primary data of TempDB database is stored in tempDB.mdf file which default size is 8 MB and TempDB database log is stored in templog.ldf file which default size is 0.5MB.
Model Database
1. Model database work as a template for all the databases created on Sql Server. 2. If we want to keep some generic database objects like as tables, function stored procedures into the newly created database then we put these objects into Model database. Hence when we create a new database then available databse objects in Model database, would be copied into newly created database.
Note : At the creation of a new database,if any database connection is opened for Model database then We can not able to create new database. 3. Primary data of Model database is stored in model.mdf file which default size is 0.75 MB and Model database log is stored in modellog.ldf which default size is 0.75MB.
MSDB Database
1. MSDB database is used by SQL Server Agent to schedule alerts, jobs, and to record operators. Example If we create a Database Maintenance Plan to take backup of a particular database on daily basis, then each and every entry will be stored in system defined SYSJOBS table in MSDB Database. 2. Primary data of Msdb database is stored in msdbdata.mdf file which default size is 12 MB and Msdb database log is stored in msdblog.ldf which default size is 2.25MB.
Resource Database
1. Resource database is also a system defined database that is hidden from user view like as another system defined database. It contains the system defined objects. 2. We can see the Resource database file by navigating to C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn. 3. Using the OBJECT_DEFINITION system function, we can view the contents of the resource database.
SELECT OBJECT_DEFINITION(OBJECT_ID('sys.objects'))
rules, and constraints. If the record/row insertion fails, SQL Server will not fire the After Trigger.
Example
1. -- First create table Employee_Demo 2. CREATE TABLE Employee_Demo 3. ( 4. Emp_ID int identity, 5. Emp_Name varchar(55), 6. Emp_Sal decimal (10,2) 7. ) 8. -- Now Insert records 9. Insert into Employee_Demo values ('Amit',1000); 10. Insert into Employee_Demo values ('Mohan',1200); 11. Insert into Employee_Demo values ('Avin',1100); 12. Insert into Employee_Demo values ('Manoj',1300); 13. Insert into Employee_Demo values ('Riyaz',1400); 14. --Now create table Employee_Demo_Audit for logging/backup purpose of table Employee_Demo create table Employee_Demo_Audit 15. ( 16. Emp_ID int, 17. Emp_Name varchar(55), 18. Emp_Sal decimal(10,2), 19. Audit_Action varchar(100), 20. Audit_Timestamp datetime 21. )
Now I am going to explain the use of After Trigger using Insert, Update, Delete statement with example
7. select @empsal=i.Emp_Sal from inserted i; 8. set @audit_action='Inserted Record -- After Insert Trigger.'; insert into Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Ti mestamp) 9. values (@empid,@empname,@empsal,@audit_action,getdate()); 10. PRINT 'AFTER INSERT trigger fired.' 11. --Output will be
12. 13.
--Now try to insert data in Employee_Demo table insert into Employee_Demo(Emp_Name,Emp_Sal)values ('Shailu',1000); 14. --Output will be
data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be
Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this way we can trace a insert activity on a table using trigger.
CREATE TRIGGER trgAfterUpdate ON dbo.Employee_Demo FOR UPDATE AS declare @empid int, @empname varchar(55), @empsal decimal(10,2), @audit_action varchar(100); 24. select @empid=i.Emp_ID from inserted i; 25. select @empname=i.Emp_Name from inserted i; 26. select @empsal=i.Emp_Sal from inserted i; if update(Emp_Name) 27. set @audit_action='Update Record --- After Update Trigger.'; 28. if update (Emp_Sal) 29. set @audit_action='Update Record --- After Update Trigger.'; 30. insert intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audi t_Timestamp) 31. values (@empid,@empname,@empsal,@audit_action,getdate()); 32. PRINT 'AFTER UPDATE trigger fired.' 33. --Output will be
--Now try to upadte data in Employee_Demo table update Employee_Demo set Emp_Name='Pawan' Where Emp_ID =6; --Output will be
data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be
Trigger have inserted the new record to Employee_Demo_Audit table for update statement. In this way we can trace a update activity on a table using trigger.
--Now try to delete data in Employee_Demo table DELETE FROM Employee_Demo where emp_id = 5 --Output will be
data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be
Trigger have inserted the new record to Employee_Demo_Audit table for delete statement. In this way we can trace a delete activity on a table using trigger. Now I am going to explain the use of Instead of Trigger using Insert, Update, Delete statement with example
COMMIT; PRINT 'Record Inserted -- Instead Of Insert Trigger.' END --Output will be
--Now try to insert data in Employee_Demo table insert into Employee_Demo values ('Shailu',1300) insert into Employee_Demo values ('Shailu',900) -- It will raise error since we are checking salary >=1000 24. --Outputs will be
data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be
Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this way we can apply business validation on the data to be inserted using Instead of trigger and can also trace a insert activity on a table.
47. 48.
--Now try to upadte data in Employee_Demo table update Employee_Demo set Emp_Sal = '1400' where emp_id = 6
49. 50.
data from both the tables to see trigger action Employee_Demo Employee_Demo_Audit be
Trigger have inserted the updated record to Employee_Demo_Audit table for update statement. In this way we can apply business validation on the data to be updated using Instead of trigger and can also trace a update activity on a table.
--Now try to delete data in Employee_Demo table DELETE FROM Employee_Demo where emp_id = 1 DELETE FROM Employee_Demo where emp_id = 3 --Output will be
--now select data from both the tables to see trigger action select * from Employee_Demo select * from Employee_Demo_Audit
80.
--Output will be
Trigger have inserted the deleted record to Employee_Demo_Audit table for delete statement. In this way we can apply business validation on the data to be deleted using Instead of trigger and can also trace a delete activity on a table.
Types of Triggers
In Sql Server we can create four types of triggers Data Definition Language (DDL) triggers, Data Manipulation Language (DML) triggers, CLR triggers and Logon triggers.
DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system defined stored procedures that perform DDL-like operations. Example : If you are going to execute the CREATE LOGIN statement or the sp_addlogin stored procedure to create login user, then both these can execute/fire a DDL trigger that you can create on CREATE_LOGIN event of Sql Server. We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF clause means we can make only After Trigger on DDL statements.
DDL trigger can be used to observe and control actions performed on the server, and to audit these operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating database operations.
DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and stored procedures that perform DML-like operations. DML Triggers are of two types
CLR Triggers
CLR triggers are special type of triggers that based on the CLR (Common Language Runtime) in .net framework. CLR integration of triggers has been introduced with SQL Server 2008 and allows for triggers to be coded in one of .NET languages like C#, Visual Basic and F#. We coded the objects(like trigger) in the CLR that have heavy computations or need references to objects outside the SQL Server. We can write code for both DDL and DML triggers, using a supported CLR language like C#, Visual basic and F#. I will discuss CLR trigger later.
Logon Triggers
Logon triggers are special type of trigger that fire when LOGON event of Sql Server is raised. This event is raised when a user session is being established with Sql Server that is made after the authentication phase finishes, but before the user session is actually established. Hence, all messages that we define in the trigger such as error messages, will be redirected to the SQL Server error log. Logon triggers do not fire if authentication fails. We can use these triggers to audit and control server sessions, such as to track login activity or limit the number of sessions for a specific login. Synatx for Logon Trigger
1. 2. 3. 4. 5. 6. CREATE TRIGGER trigger_name ON ALL SERVER [WITH ENCRYPTION] {FOR|AFTER} LOGON AS sql_statement [1...n ]
trigger_name
This is the name of the trigger. It should conform to the rules for identifiers in Sql Server.
table|view
This is the table/view on which the trigger is to be created.
ENCRYPTION
This option is optional. If this option is specified, original text of the CREATE TRIGGER statement will be encrypted.
EXECUTE AS
This option is optional. This option specifies, the security context under which the trigger is executed.
FOR/AFTER
FOR/AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR is the only keyword specified.AFTER triggers cannot be defined on views.
INSTEAD OF
INSTEAD OF specifies that the trigger is Instead Of Trigger.
CREATE|ALTER|DROP|INSERT|UPDATE|DELETE
These keywords specify on which action the trigger should be fired. One of these keywords or any combination of these keywords in any order can be used.
AS
After this we specifies the actions and condition that the trigger perform.
sql_statement
These are the trigger conditions and actions. The trigger actions specified in the T-SQL statements.
Note
1. The name of a trigger should follow the rules for identifiers. 2. DML trigger can be composed by any T-SQL statements, except CREATE DATABASE, ALTER DATABASE, DROP DATABASE, LOAD DATABASE, LOAD LOG, RECONFIGURE, RESTORE DATABASE, and RESTORE LOG statements. 3. You cannot create triggers against system tables or dynamic management views. Moreover, the TRUNCATE TABLE statement does not fire a trigger because this operation does not log individual row deletions. 4. If you use the DATABASE option, the scope of your DDL trigger will be the current database. If you use the ALL SERVER option, the scope of your DDL triggers to the current server. 5. AFTER triggers cannot be defined on views. 6. AFTER is the default, if FOR is the only keyword specified.
committed and the changes made by T-SQL statements permanently saved to database. If any of these T-SQL statements within a transaction fail, then the complete transaction is cancelled/ rolled back. We use transaction in that case, when we try to modify more than one tables/views that are related to one another. Transactions affect SQL Server performance greatly. Since When a transaction is initiated then it locks all the tables data that are used in the transaction. Hence during transaction life cycle no one can modify these tables data that are used by the transaction. The reason behind the locking of the data is to maintain Data Integrity.
Explicit Transaction
Explicit transactions are defined by programmers. In Explicit transaction we include the DML statements that need to be execute as a unit. Since SELECT statements doesnt modify data. Hence generally we dont include Select statement in a transaction.
Transactions Example
1. CREATE TABLE Department 2. ( 3. DeptID int PRIMARY KEY, 4. DeptName varchar(50) NULL, 5. Location varchar(100) NULL, 6. ) 7. GO 8. CREATE TABLE Employee 9. ( 10. EmpID int PRIMARY KEY, 11. Name varchar(50) NULL, 12. Salary int NULL, 13. Address varchar(100) NULL, 14. DeptID int foreign Key references Department(DeptID) 15. )
3. GO 4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',15000,'Delhi' ,1) 5. SELECT * FROM Department 6. SELECT * FROM Employee
1. BEGIN TRANSACTION trans 2. BEGIN TRY 3. INSERT INTO Department(DeptID,DeptName,Location)VALUES(2,'HR','Delhi') 4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',18000,'Delhi' ,1) 5. IF @@TRANCOUNT > 0 6. BEGIN COMMIT TRANSACTION trans 7. END 8. END TRY 9. BEGIN CATCH 10. print 'Error Occured' 11. IF @@TRANCOUNT > 0 12. BEGIN ROLLBACK TRANSACTION trans 13. END 14. END CATCH
1. --Now Select data to see transaction affects 2. SELECT * FROM Employee 3. SELECT * FROM Department
1. --Transaction with Save Point BEGIN TRANSACTION trans 2. BEGIN TRY 3. INSERT INTO Department(DeptID,DeptName,Location)VALUES(2,'HR','Delhi') 4. IF @@TRANCOUNT > 0
5. BEGIN SAVE TRANSACTION trans; 6. END 7. INSERT INTO Department(DeptID,DeptName,Location)VALUES(3,'Admin','Delhi') 8. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',18000,'Delhi' ,1) 9. IF @@TRANCOUNT > 0 10. BEGIN COMMIT TRANSACTION trans 11. END 12. END TRY 13. BEGIN CATCH 14. print 'Error Occured' 15. IF @@TRANCOUNT > 0 16. BEGIN ROLLBACK TRANSACTION trans 17. END 18. END CATCH
1. --Now Select data to see transaction affects 2. SELECT * FROM Employee 3. SELECT * FROM Department
Group By Clause
Group By clause is used for grouping the records of the database table(s).This clause creates a single row for each group and this process is called aggregation. To use group by clause we have to use at least one aggregate function in Select statement. We can use group by clause without where clause. Syntax for Group By Clause
1. SELECT Col1, Col2, Aggreate_function 2. FROM Table_Name 3. WHERE Condition 4. GROUP BY Col1, Col2
Let's see how the Group By clause works. Suppose we have a table StudentMarks that contains marks in each subject of the student.
1. Create table StudentMarks 2. ( 3. st_RollNo int , 4. st_Name varchar(50), 5. st_Subject varchar(50), 6. st_Marks int 7. ) 8. --Insert data in StudentMarks table 9. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 10. values(1,'Mohan','Physics',75); 11. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 12. values(1,'Mohan','Chemistry',65); 13. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 14. values(1,'Mohan','Math',70); 15. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) values(2,'Vipul','Physics',70); 16. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 17. values(2,'Vipul','Chemistry',75); 18. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) values(2,'Vipul','Math',60); 19. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 20. values(3,'Jitendra','Physics',85); 21. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 22. values(3,'Jitendra','Chemistry',75); 23. insert into StudentMarks(st_RollNo,st_Name,st_Subject,st_Marks) 24. values(3,'Jitendra','Math',60); 25. --Now see data in table 26. select * from StudentMarks
1. -- Group By clause without where condition 2. SELECT st_Name, SUM(st_Marks) AS 'Total Marks' 3. FROM StudentMarks 4. GROUP BY st_Name;
1. 2. 3. 4. 5.
-- Group By clause with where condition SELECT st_Name, SUM(st_Marks) AS 'Total Marks' FROM StudentMarks where st_Name='Mohan' GROUP BY st_Name;
1. -- Group By clause to find max marks in subject 2. SELECT st_Subject,max(st_Marks) AS 'Max Marks in Subject' 3. FROM StudentMarks 4. GROUP BY st_Subject;
Having Clause
This clause operates only on group rows of table(s) and act as a filter like as where clause. We use having clause to filter data that we get from group by clause. To use having clause we need to use group by clause first.
1. 2. 3. 4. 5. -- Having clause without where condition SELECT st_Name, SUM(st_Marks) AS 'Students Scored > 205' FROM StudentMarks GROUP BY st_Name HAVING SUM(st_Marks) > 205
1. 2. 3. 4. 5. 6.
-- Having clause with where condition SELECT st_Name, SUM(st_Marks) AS 'Students Scored > 205' FROM StudentMarks where st_RollNo between 1 and 3 GROUP BY st_Name HAVING SUM(st_Marks) > 205
Note
1. To use Group By Clause, we need to use at least one aggregate function 2. We can use Group By Clause with or without Where Clause. 3. To use Having Clause, we have to use Group By Clause since it filters data that we get from Group By Clause
Create Operation
We can create temporary table(s) using stored procedure for intermediate data manipulation. Below code is used to remove duplicate records from tables using procedure.
1. 2. 3. 4. 5. 6. 7. 8. ( CREATE TABLE Employee_Test Emp_ID int identity, Emp_Name varchar (55) NULL, Emp_Sal decimal (10, 2) NULL, Emp_Designation varchar (20) NULL
) Go INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Amit',12000,'SE') 9. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Amit',12000,'SE') 10. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Mohan',15000,'SE' ) 11. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Mohan',15000,'SE' ) 12. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Riyaz',16000,'SE' ) 13. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Monu',27000,'SSE' ) 14. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation)VALUES('Amit',12000,'SE') 15. GO 16. --Now see table 17. SELECT * FROM dbo.Employee_Test
1. create procedure usp_Removedup 2. as 3. begin 4. CREATE TABLE #tempEmpdata 5. ( 6. Emp_Name varchar (55) NULL, 7. Emp_Sal decimal (10, 2) NULL, 8. Emp_Designation varchar (20) NULL 9. ) 10. --Identify and save distinct data into temporary table
11. INSERT INTO #tempEmpdata SELECT DISTINCT Emp_Name,Emp_Sal, Emp_Designation FROM Employee_Test 12. --Delete original table data by using Truncate command, since it has Emp_ID as identiy col 13. TRUNCATE table Employee_Test 14. --Now insert data from temp table to original table 15. INSERT INTO Employee_Test(Emp_Name,Emp_Sal,Emp_Designation) SELECT Emp_Name,Emp_Sal,Emp_Designation FROM #tempEmpdata 16. --Now drop temp table 17. drop TABLE #tempEmpdata 18. end
Insert Operation
We can insert records into the table(s) using stored procedure by passing data in input parameters. Below code is used to insert record in the table "Employee" using stored procedure
1. CREATE TABLE Employee 2. ( 3. EmpID int primary key, Name varchar(50), 4. Salary int, 5. Address varchar(100) 6. )
1. 2. 3. 4. 5.
Insert into Employee(EmpID,Name,Salary,Address) Values(1,'Mohan',16000,'Delhi') Insert into Employee(EmpID,Name,Salary,Address) Values(2,'Asif',15000,'Delhi') Insert into Employee(EmpID,Name,Salary,Address) Values(3,'Bhuvnesh',19000,'Noida') --See table SELECT * FROM Employee
1. CREATE PROCEDURE usp_InsertEmployee 2. @flag bit output,-- return 0 for fail,1 for success 3. @EmpID int, 4. @Name varchar(50), 5. @Salary int, 6. @Address varchar(100) 7. AS 8. BEGIN 9. BEGIN TRANSACTION 10. BEGIN TRY 11. Insert into Employee(EmpID,Name,Salary,Address) Values(@EmpID,@Name,@Salary,@Address) 12. set @flag=1; 13. IF @@TRANCOUNT > 0 14. BEGIN commit TRANSACTION; 15. END 16. END TRY 17. BEGIN CATCH 18. IF @@TRANCOUNT > 0 19. BEGIN rollback TRANSACTION; 20. END 21. set @flag=0; 22. END CATCH 23. END
1. 2. 3. 4. 5. 6. 7.
--Execute above created procedure to insert rows into table Declare @flag bit EXEC usp_InsertEmployee @flag output,1,'Deepak',14000,'Noida' if @flag=1 print 'Successfully inserted' else print 'There is some error'
1. 2. 3. 4. 5. 6. 7.
--Execute above created procedure to insert rows into table Declare @flag bit EXEC usp_InsertEmployee @flag output,4,'Deepak',14000,'Noida' if @flag=1 print 'Successfully inserted' else print 'There is some error'
Retrieve Operation
We can retrieve data from one or more tables/views with the help of join, using stored procedure. We can put multiple sql statements with in a single stored procedure. Below code is used to fetch data from a table "Employee" using stored procedure
1. -- first we Insert data in the table 2. Insert into Employee(EmpID,Name,Salary,Address) Values(1,'Mohan',16000,'Delhi') 3. Insert into Employee(EmpID,Name,Salary,Address) Values(2,'Asif',15000,'Delhi') 4. Insert into Employee(EmpID,Name,Salary,Address) Values(3,'Bhuvnesh',19000,'Noida') 5. go 6. --Now we create a procedure to fetch data 7. CREATE PROCEDURE usp_SelectEmployee 8. As 9. Select * from Employee ORDER By EmpID
Update Operation
We can update records of the table(s) using stored procedure by passing data in input parameters. Below code is used to update a table "Employee" using stored procedure
1. CREATE PROCEDURE usp_UpdateEmployee 2. @flag bit output,-- return 0 for fail,1 for success 3. @EmpID int, 4. @Salary int, 5. @Address varchar(100) 6. AS 7. BEGIN 8. BEGIN TRANSACTION 9. BEGIN TRY 10. Update Employee set Salary=@Salary, Address=@Address 11. Where EmpID=@EmpID 12. set @flag=1; 13. IF @@TRANCOUNT > 0 14. BEGIN commit TRANSACTION; 15. END 16. END TRY 17. BEGIN CATCH 18. IF @@TRANCOUNT > 0 19. BEGIN rollback TRANSACTION; 20. END 21. set @flag=0; 22. END CATCH 23. END
1. 2. 3. 4. 5. 6.
--Execute above created procedure to update table Declare @flag bit EXEC usp_UpdateEmployee @flag output,1,22000,'Noida' if @flag=1 print 'Successfully updated' else print 'There is some error'
Delete Operation
We can delete records of the table(s) using stored procedure by passing data in input parameters. Below code is used to update a table "Employee" using stored procedure
1. CREATE PROCEDURE usp_DeleteEmployee 2. @flag bit output,-- return 0 for fail,1 for success 3. @EmpID int 4. AS 5. BEGIN 6. BEGIN TRANSACTION 7. BEGIN TRY 8. Delete from Employee Where EmpID=@EmpID set @flag=1; 9. IF @@TRANCOUNT > 0 10. BEGIN commit TRANSACTION; 11. END 12. END TRY 13. BEGIN CATCH 14. IF @@TRANCOUNT > 0 15. BEGIN rollback TRANSACTION; 16. END 17. set @flag=0; 18. END CATCH 19. END
1. 2. 3. 4. 5. 6. 7.
--Execute above created procedure to delete rows from table Declare @flag bit EXEC usp_DeleteEmployee @flag output, 4 if @flag=1 print 'Successfully deleted' else print 'There is some error'
Note
1. In stored procedure we use output parameter to return multiple values. 2. Generally we use output parameter in stored procedure to get status of the operation as I used above "@flag" output parameter to get operations status whether these are successfully executed or not.
Description sp_rename It is used to rename an database object like stored procedure,views,table etc. sp_changeowner It is used to change the owner of an database object. sp_help It provides details on any database object. sp_helpdb It provide the details of the databases defined in the Sql Server. sp_helptext It provides the text of a stored procedure reside in Sql Server sp_depends It provide the details of all database objects that depends on the specific database object.
Extended Procedure
Extended procedures provide an interface to external programs for various maintenance activities. These extended procedures starts with the xp_ prefix and stored in Master database. Basically these are used to call programs that reside on the server automatically from a stored procedure or a trigger run by the server. Example Below statements are used to log an event in the NT event log of the server without raising any error on the client application.
declare @logmsg varchar(100) set @logmsg = suser_sname() + ': Tried to access the dotnet system.' exec xp_logevent 50005, @logmsg print @logmsg
Example The below procedure will display details about the BUILTIN\Administrators Windows group.
EXEC xp_logininfo 'BUILTIN\Administrators'
1. We can nest stored procedures and managed code references in Sql Server up to 32 levels only. This is also applicable for function, trigger and view. 2. The current nesting level of a stored procedures execution is stored in the @@NESTLEVEL function. 3. In Sql Server stored procedure nesting limit is up to 32 levels, but there is no limit on the number of stored procedures that can be invoked with in a stored procedure
Batch-Level Exception
This type of exception aborts only the batch in which exception occurs. The rest of the batches will execute successfully if they have no exceptions. The statement in which exception occurs will be aborted and the remaining T-SQL statements within the batch will also stopped.
--First Batch DECLARE @var DECIMAL; set @var= CONVERT(DECIMAL, PRINT @var PRINT 'This statement will GO --Second Batch DECLARE @var DECIMAL; set @var= CONVERT(DECIMAL, PRINT @var PRINT 'This statement will GO
'12.35') execute'
--For Successfully execution we need to executed select statement as dynamic SQL using the EXEC function
--Now execute above created procedure in batch EXEC usp_print PRINT 'This statement will execute' GO --Since the stored procedure creates a new scope. Hence rest statement will be executed
1. 2. 3. 4. 5. 6. 7. 8.
BEGIN TRY --T-SQL statements --or T-SQL statement blocks END TRY BEGIN CATCH --T-SQL statements --or T-SQL statement blocks END CATCH
ERROR_LINE()
This returns the line number of T-SQL statement that caused error.
ERROR_SEVERITY()
This returns the severity level of the error.
ERROR_STATE()
This returns the state number of the error.
ERROR_PROCEDURE()
This returns the name of the stored procedure or trigger where the error occurred.
ERROR_MESSAGE()
This returns the full text of error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.
12. GO
1. 2. 3. 4. 5. 6. 7. 8.
BEGIN TRY DECLARE @num INT ---- Divide by zero to generate Error SET @num = 5/0 PRINT 'This will not execute' END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; 9. END CATCH; 10. GO
Note
1. A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19. 2. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the CATCH block is ignored. 3. Each TRY block is associated with only one CATCH block and vice versa 4. TRY and CATCH blocks cant be separated with the GO statement. We need to put both TRY and CATCH blocks within the same batch. 5. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using @@TRANCOUNT function in Sql Server. 6. XACT_STATE function within the TRY..CATCH block can be used to check whether a open transaction is committed or not. It will return -1 if transaction is not committed else returns 1.
which is used to make view.One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database table. Syntax for View
1. CREATE VIEW view_name 2. AS 3. select_statement[]
Types of Views
In Sql Server we have two types of views.
10.
--To view detailed information of the columns of table Employee_Test 11. SELECT * FROM INFORMATION_SCHEMA.COLUMNS 12. where TABLE_NAME='Employee_Test'
Catalog View
Catalog Views were introduced with SQL Server 2005. These are used to show database self describing information.
13. select * from sys.tables
Simple View
When we create a view on a single table, it is called simple view.
17. 18. --Now Insert data to table Employee_Test Insert into Employee_Test values ('Amit','PHP',12000,'SE'); 19. Insert into Employee_Test values ('Mohan','ASP.NET',15000,'TL'); 20. Insert into Employee_Test values ('Avin','C#',14000,'SE'); 21. Insert into Employee_Test values ('Manoj','JAVA',22000,'SSE'); 22. Insert into Employee_Test values ('Riyaz','VB',18000,'TH'); 23. -- Now create view on single table Employee_Test 24. create VIEW vw_Employee_Test 25. AS 26. Select Emp_ID ,Emp_Name ,Emp_Designation 27. From Employee_Test
28. 29.
In simple view we can insert, update, delete data. We can only insert data in simple view if we have primary key and all not null fields in the view.
30. 31. -- Insert data to view vw_Employee_Test insert into vw_Employee_Test(Emp_Name, Emp_Designation) values ('Shailu','SSE') 32. -- Now see the affected view 33. Select * from vw_Employee_Test
34. 35.
-- Update data to view vw_Employee_Test Update vw_Employee_Test set Emp_Name = 'Pawan' where Emp_ID = 6 36. -- Now see the affected view 37. Select * from vw_Employee_Test
-- Delete data from view vw_Employee_Test delete from vw_Employee_Test where Emp_ID = 6 -- Now see the affected view Select * from vw_Employee_Test
Complex View
When we create a view on more than one table, it is called complex view.
42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. --Create another table create table Personal_Info ( Emp_Name varchar(55), FName varchar(55), DOB varchar(55), Address varchar(55), Mobile int, State varchar(55) ) -- Now Insert data Insert into Personal_Info values ('G.Chaudary','22-101985','Ghaziabad',96548922,'UP'); 54. Insert into Personal_Info values ('B.S.Chauhan','02-071986','Haridwar',96548200,'UK'); 55. Insert into Personal_Info values ('A.Panwar','30-041987','Noida',97437821,'UP'); 56. Insert into Personal_Info values ('H.C.Patak','20-071986','Rampur',80109747,'UP'); 57. Insert into Personal_Info values ('M.Shekh','21-101985','Delhi',96547954,'Delhi'); 58. -- Now create view on two tables Employee_Test and Personal_Info 59. Create VIEW vw_Employee_Personal_Info 60. As 61. Select e.Emp_ID, e.Emp_Name,e.Emp_Designation,p.DOB,p.Mobile 62. From Employee_Test e INNER JOIN Personal_Info p 63. On e.Emp_Name = p. Emp_Name
64. 65.
We can only update data in complex view.We can't insert,update data in complex view.
66. 67.
--Update view update vw_Employee_Personal_Info set Emp_Designation = 'SSE' where Emp_ID = 3 68. -- See affected view 69. Select * from vw_Employee_Personal_Info
Note
1. We make views for security purpose since it restricts the user to view some columns/fields of the table(s). 2. One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database table
Types of Joins
In Sql Server we have only three types of joins. Using these joins we fetch the data from multiple tables based on condition.
Inner Join
Inner join returns only those records/rows that match/exists in both the tables. Syntax for Inner Join is as
1. Select * from table_1 as t1 2. inner join table_2 as t2 3. on t1.IDcol=t2.IDcol
Outer Join
We have three types of Outer Join.
Cross Join
Cross join is a cartesian join means cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records/rows that are multiplication of record number from both the tables means each row on left table will related to each row of right table. Syntax for right outer Join is as :
4. Select * from table_1 5. cross join table_2
Self Join
Self join is used to join a database table to itself, particularly when the table has a Foreign key that references its own Primary Key. Basically we have only three types of joins : Inner join, Outer join and Cross join. We use any of these three JOINS to join a table to itself. Hence Self join is not a type of Sql join.
Join Examples
Suppose we following three tables and data in these three tables is shown in figure. You can download the SQL script used in this article by using link.
Inner Join
1. SELECT t1.OrderID, t0.ProductID, t0.Name, t0.UnitPrice, t1.Quantity, t1.Price 2. FROM tblProduct AS t0 3. INNER JOIN tblOrder AS t1 ON t0.ProductID = t1.ProductID 4. ORDER BY t1.OrderID
Cross Join
1. SELECT t1.OrderID, t0.ProductID, t0.Name, t0.UnitPrice, t1.Quantity, t1.Price 2. FROM tblProduct AS t0, tblOrder AS t1 3. ORDER BY t0.ProductID
Self Join
To understand Self Join, suppose we following two tables and data in these two tables is shown in figure.
1. 2. 3. 4. 5. 6. CREATE TABLE emp ( id int NOT NULL primary key, name varchar(100) NULL, designation varchar(50) NULL, supid int foreign key references emp(id) ) -- In this table we have a Foreign key supid that references its own Primary Key id. We use it for Self Join 7. INSERT INTO emp(id,name,designation) VALUES(1,'mohan','Manger') 8. INSERT INTO emp(id,name,designation,supid) VALUES(2,'raj kumar','SE',1) 9. INSERT INTO emp(id,name,designation) VALUES(3,'bipul kumar','Manager') 10. INSERT INTO emp(id,name,designation,supid) VALUES(4,'mrinal kumar','SE',2) 11. INSERT INTO emp(id,name,designation,supid) VALUES(5,'jitendra kumar','SE',2)
1. CREATE TABLE empinfo 2. ( 3. id int primary key, 4. address varchar(50) NULL 5. ) 6. INSERT INTO empinfo(id,address) VALUES(1,'Delhi') 7. INSERT INTO empinfo(id,address) VALUES(2,'Noida') 8. INSERT INTO empinfo(id,address) VALUES(4,'Gurgaon') 9. INSERT INTO empinfo(id,address) VALUES(6,'Delhi') 10. INSERT INTO empinfo(id,address) VALUES(7,'Noida')
1.
select e.id,e.name,e.supid as managerid, ei.name as managername from emp e left join emp ei on e.supid=ei.id; 2. -- outer keyword is optional
Column Level
The constraints can be specified immediately after the column definition with the CREATE TABLE statement. This is called column-level constraints.
Table Level
The constraints can be specified after all the columns are defined with the ALTER TABLE statement. This is called table-level constraints.
Check Constraints
This constraint defines a business rule on a column in the database table that each row of the table must follow this rule. Check constraint at column level
CREATE TABLE table_name ( col1 datatype [CONSTRAINT constraint_name] CHECK (condition), col2 datatype );
Super Key
Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.Example : Primary key, Unique key, Alternate key are subset of Super Keys.
Candidate Key
A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key. Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields can be work as Primary Key.
Primary Key
Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.
Alternate key
A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key. Example: In below diagram RollNo and EnrollNo becomes Alternate Keys when we define ID as Primary Key.
Composite/Compound Key
Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key.
Unique Key
Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in database table. It is like Primary key but it can accept only one null value and it can not have duplicate values. For more help refer the article Difference between primary key and unique key.
Foreign Key
Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values. For more help refer the article Difference between primary key and foreign key. Example : We can have a DeptID column in the Employee table which is pointing to DeptID column in a department table where it a primary key. Defined Keys -
1. CREATE TABLE Department 2. ( 3. ID int PRIMARY KEY, 4. Name varchar (50) NOT NULL, 5. Address varchar (200) NOT NULL, ) 6. CREATE TABLE Student 7. ( 8. ID int PRIMARY KEY, 9. RollNo varchar(10) NOT NULL, 10. Name varchar(50) NOT NULL, 11. EnrollNo varchar(50) UNIQUE, 12. Address varchar(200) NOT NULL, 13. DeptID int FOREIGN KEY REFERENCES Department(DeptID) 14. )
Note
1. Practically in database, we have only three types of keys Primary Key, Unique Key and Foreign Key. Other types of keys are only concepts of RDBMS that we need to know.
These SQL commands are used to create, modify, and drop the structure of database objects like table, view, procedure, indexes etc. In this category we have CREATE, ALTER, DROP and TRUNCATE commands.
Note
1. Only with DDL commands we need to write keyword (like table, procedure, view, index, function) with the syntax of command. 2. These commands are used to create/modify the structure of the database object.
Example
3. 4. 5. 6. 7. 8. CREATE TABLE TABLE_NAME ( COL1 VARCHAR(10), COL2 VARCHAR(20), ); --Here "TABLE" is a keyword that is used to create table "TABLE_NAME" 9. CREATE VIEW VIEW_NAME 10. AS 11. BEGIN 12. SELECT * FROM EMP_TABLE 13. END 14. --Here "VIEW" is a keyword that is used to create VIEW "VIEW_NAME"
Note
15. Grant Command : This command is used to give permission to specific users on specific database objects like table, view etc. 16. Revoke Command : This command is used to take out permission from specific users on specific database objects like table, view etc.
SQL Server 2005 10.0 2008 SQL Server 2008 10.5 2010 SQL Server 2008 R2
Data Storage
The main unit of data storage is a database, which is a collection of data. The data in the SQL Server database is stored in primary data files with an extension .mdf and Secondary data files, with an extension .ndf extension are used to store optional metadata. Log files in SQL Server are recognized with the .ldf extension.
Buffer Management
SQL Server buffers pages in RAM to minimize disc Input/Output. A 8 KB page could be buffered in-memory and the set of all pages currently buffered is called the buffer cache. On the basis of available memory, SQL Server decides how many pages will be cached in memory. The buffer cache is managed by the Buffer Manager.
In Optimistic concurrency control, a new version of a row is created whenever the row is updated. Both the versions of the row are stored and maintained into a system defined database Tempdb.
Data Retrieval
Data retrieval from SQL Server is done using T-SQL. SQL Server also allows us to write stored procedures to query the data.
Using ODBC
// ODBC without DSN using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={IBM DB2 ODBC DRIVER};DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP;Port=PortNumber;Uid=UserName;Pwd=Secret"; conn.Open();
Using OLEDB
// OleDb -- Microsoft Driver using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Driver=DB2OLEDB; Network Transport Library=TCPIP; Network Address=xxx.xxx.xxx.xxx; Package Collection=CollectionName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;"; conn.Open(); // OleDb -- IBM Driver
using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Driver=IBMDADB2; DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP; Port=PortNumber; Uid=UserName; Pwd=Secret;"; conn.Open();
Using ODBC
// ODBC -- MyODBC Driver -- remote database using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={MySql}; Server=db.domain.com; Option=131072; Port=3306; Stmt=; DataBase=DataBaseName; Uid=UserName; Pwd=Secret;" ; conn.Open();
Using OLEDB
// OleDb using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Provider=MySqlProv; Data Source=ServerName; User id=UserName; Password=Secret"; conn.Open();
Oracle is most used database in the world. In Ado.net to make connection to Oracle we have multiple options. For this purpose we have different connection string to connect to the Oracle. Basically it is not easy to remember different database connection strings in Ado.Net. So I am sharing some connection strings to connect to the Oracle database using different drivers.
Using ODBC
1. // ODBC -- New Microsoft Driver 2. using System.Data.Odbc; 3. OdbcConnection conn = new OdbcConnection(); 4. conn.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=UserName;Pwd=Secret;"; 5. conn.Open(); 6. // ODBC -- Oracle Driver 7. using System.Data.Odbc; 8. OdbcConnection conn = new OdbcConnection(); 9. conn.ConnectionString = "Driver={Oracle ODBC Driver};Dbq=myDataBase;Uid=UserName;Pwd=Secret;"; 10. conn.Open();
Using OLEDB
1. // OleDb -- Oracle Driver -- Standard Connection 2. using System.Data.OleDb; 3. OleDbConnection conn = new OleDbConnection(); 4. conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=UserName;Password=Secret;"; 5. conn.Open(); 6. // OleDb -- Oracle Driver -- Trusted Connection 7. using System.Data.OleDb; 8. OleDbConnection conn = new OleDbConnection(); 9. conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;OSAuthent=1;"; 10. conn.Open(); 11. // or 12. using System.Data.OleDb; 13. OleDbConnection conn = new OleDbConnection(); 14. conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=admin;Password=pwd"; 15. conn.Open();
Using ODBC
// ODBC -- Standard Security using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; Uid=Admin; Pwd=;password"; conn.Open(); // ODBC -- Workgroup (System Database) using System.Data.Odbc; OdbcConnection conn = new OdbcConnection(); conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; SystemDb=c:\myPath\myDb.mdw;"; conn.Open();
Using OLEDB
// OleDb with MS Jet -- Standard Security using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; User id=admin;Password=password"; conn.Open(); // OleDb with MS Jet -- Workgroup (System Database) using System.Data.OleDb; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; System Database=c:\mypath\myDb.mdw"; conn.Open();
Using ODBC
1. // ODBC -- Standard Connection 2. using System.Data.Odbc; 3. OdbcConnection conn = new OdbcConnection(); 4. conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=UserName; Pwd=Secret"; 5. conn.Open(); 6. // ODBC -- Trusted Connection 7. using System.Data.Odbc; 8. OdbcConnection conn = new OdbcConnection(); 9. conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=admin; Pwd=password"; 10. conn.Open(); 11. // or 12. OdbcConnection conn = new OdbcConnection();
Using OLEDB
1. // OleDb -- Standard Connection 2. using System.Data.OleDb; 3. OleDbConnection conn = new OleDbConnection(); 4. conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;"; 5. conn.Open(); 6. // OleDb -- Trusted Connection 7. using System.Data.OleDb; 8. OleDbConnection conn = new OleDbConnection(); 9. conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;"; 10. conn.Open();
Introduction to Ado.net
Before Ado.net we use Ado (Active Database Object) to access data from databae. Basically Ado has automatic driver detection technique and tt has only one drawback that it only provide a connected environment so efficiency of system may decrease. ADO.NET is a new database technology used by .Net platform (introduced in 2002).Infact it is a set of classes used to communicate between an application front end and a database.It supports both connected & disconnection mode of data access.
System.Data
It contains the common classes for connecting, fetching data from database. Classes are like as DataTable, DataSet, DataView etc.
System.Data.SqlClient
It contains classes for connecting, fetching data from Sql Server database. Classes are like as SqlDataAdapter,SqlDataReader etc.
System.Data.OracleClient
It contains classes for connecting, fetching data from Oracle database. Classes are like as OracleDataAdapter,OracleDataReader etc.
System.Data.OleDb
It contains classes for connecting, fetching data from any database(like msaccess, db2, oracle, sqlserver, mysql). Classes are like as OleDbDataAdapter,OleDbDataReader etc.
System.Data.Odbc
It contains classes for connecting, fetching data from any database(like msaccess, db2, oracle, sqlserver, mysql). Classes are like as OdbcDataAdapter,OdbcDataReader etc.
4. Odbc Data Provider :-It is used to access data from any database (msaccess, mysql, db2).
Data Set
Basically it is a small Data structure that may contain multiple datatables from multiple sources.The information in dataset is created inform of XML and is stored with .xsd extention.It support disconnected mode of data access.It has both scrolling mode means forward and backward scrolling mode (fetching of data).DataSet can have multiple Datatable from multiple sources but DataReader is able toread only single Datatable.
An object is created using the new operator. This operator first makes sure that the bytes required by the new object fit in the reserved region (committing storage if necessary). If the object fits, NextObjPtr points to the object in the heap and object's constructor is called and the new operator returns the address of the object.
8. Only some of the free memory is committed when required and more memory is acquired from the OS in the reserved address range.
Generation 0
This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1. Example : A temporary object.
Generation 1
This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generationen 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.
Generation 2
This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently. Example : An object at application level that contains static data which is available for the duration of the process.
Relocating Phase
In this phase garbage collector updates the references to the objects that will be compacted.
Compacting Phase
In this phase garbage collector reclaims the memory occupied by the dead objects and compacts the surviving objects. The compacting phase moves the surviving objects toward the older end of the memory segment.
Note
1. The large object heap is not compacted, because copying large objects imposes a performance penalty.
More over any CPU registers containing pointers to objects in the managed heap are also considered a part of the application's roots. The list of active roots is maintained by the JIT compiler and CLR, and is made accessible to the garbage collector's algorithm.
Memory Reclaim Process
Now the garbage collecor starts go through the roots and make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6 refers to the objects 8 & 10. Hence all these objects will bacome the part of the live objects graph.
The objects which are not reachable from application's roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.
The garbage collector then remove the dead objects from the heap and live objects will move toward the older end of the memory segment as shown in below fig. Garbage collector also updates all the references(including root references) to the moving objects in the heap.
Reference : http://msdn.microsoft.com/en-us/magazine/bb985010.aspx
Fundamental of Finalization
When a new object is created, the memory is allocated in the managed heap. If newly created object have a Finalize() method or a destructor then a pointer pointing to that object is put into the finalization queue. Basically, finalization queue is an internal data structure that is controlled and managed by the GC. Hence each pointer in finalization queue points to an object that have its Finalize method call before the memory is reclaimed. In the below fig. the managed heap contains 10 objects and objects 2,3,5,6,and 10 also contains the Finalize method. Hence pointers to these objects were added to the finalization queue.
When the garbage collecor starts go through the roots, it make a graph of all the objects reachable from the roots. The below fig. shows a heap with allocated objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6 refers to the objects 8 & 10. Hence all these objects will bacome the part of the live objects graph.
The objects which are not reachable from application's roots, are considered as garbage since these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as dead objects.
Before the collections for dead objects, the garbage collector looks into the finalization queue for pointers identifies these objects. If the pointer found, then the pointer is flushed from the finalization queue and append to the freachable queue .The freachable queue is also an internal data structure and controlled by the garbage collector. Now each and every pointer with in the freachable queue will identify an object that is ready to have its Finalize method called. After the collection, the managed heap looks like below Fig. Here, you see that the memory occupied by objects 7 and 9 has been reclaimed because these objects did not have a Finalize method. However, the memory occupied by objects 2 and 5 could not be reclaimed because their Finalize method has not been called yet.
When an object's pointer entry move from the finalization queue to the freachable queue, the object is not considered garbage and its memory is not reclaimed. There is a special run-time thread that is dedicated for calling Finalize methods. When there is no entry in the freachable queue then this thread sleeps. But when there is entry in the freachable queue, this thread wakes and removes each entry from the queue by calling each object's Finalize method.
The next time the garbage collector is invoked, it sees that the finalized objects are truly garbage, since the application's roots don't point to it and the freachable queue no longer points to it. Now the memory for the object is simply reclaimed.
Note
1. The two GCs are required to reclaim memory used by objects that have FInalize method. Reference : http://msdn.microsoft.com/en-us/magazine/bb985010.aspx
Introduction to Ajax
AJAX is not a technology but it is a group of technologies (as Javascript, CSS, XHTML, DOM etc). We can also say it is a combination of client side technologies that provides asynchronous communication b\w user interface and web server so that partial page rendering occurs instead of complete page post back. It is platform independent means AJAX is a cross platform technology that can be used an any Operating system since it is based an XML & Javascript. It also supports open source implementation of other technology. It partially render the page to the server instead of complete page postback.We use AJAX for developing faster better and more interactive web applications.AJAX use HTTP request b\w web server & browser.
Ajax Features
1. 2. 3. 4. 5. Ajax minimize round trips to the server. It is language independent means we can use ajax in every language Ajax is platform independent. Rendering of webpage is faster. Reduce consumption of server resources.
Ajax Drawback
Response Time in AJAX based development we should care of response time b\w client & server because it gets normally delayed. AJAX is based on Java Script and different browser implement Javascript different way. Hence here may be a problems on different browser. Example :Uploading of file in gmail & do working in message body box.
Script Manager
It manages all ASP.Net AJAX controls on the web page. It renders the AJAX library to the browser and supports partial page rendering. It also manage partial page uploades and provide access to web service method. Without script manager we can't use AJAX controls on the web page.
Introduction to Asp.net
According to Microsoft, "ASP.NET is a technology for building powerful, dynamic Web applications and is part of the .NET Framework". Infact Asp.Net is a programming framework used to develop web applications and web services. Basically it is next version of asp. It provides the easy way to build, deploy & run web application on any browser.
Benefits of Asp.Net
1. Asp.Net makes development simple and easy to maintain with event-driven and server side programming model. 2. Asp.Net source code is executed on the server. The source code is complied first time the page is requested. The server serves the complied version of the page for use next time the page is requested. 3. Asp.Net provides validations controls. 4. The html produced by Asp.Net is sent back to the browser. The application code that we write is not sent back to the browser and is not stolen easily. 5. In Asp.Net business logic(in .cs class file) and presentation logic(in .aspx file) are in separate files.
PreInit
It is is entry point of page life cycle. It checks IsPostBack property to check or recreate dynamic controls. In this we can set master pages dynamically & set and get profile property values.
Init
It is is raised after all controls of page are initilised and skin properties are set. It is used to read or initialise control properties.
InitComplete
This indicates that page is completely initialised.
Preload
This event is called before loading the page in the RAM(memory). If any processing on a control or on page is required we use it.
Load
This invokes the onload event of the page. In this we create connection to the database, get/set controls values and get/set view state values.
loadComplete
This indicates that page is completely loaded into memory.
Prender
we use this event to make final changes to the controls or page before rendering it to the browser.
SaveStateComplete
View state of each control is saved before this event occurs. If we want to change the view state of any control then we use this event. This event can not be used to change the other properties of the controls.
Render/PrenderComplete
This indicates that page is completely rendered to the browser.Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.
Unload
The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.We can use this event for closing files & database connection. This event occurs for each control.
Asp.Net Web Form Asp.Net Web Form is a traditional event driven development model
Asp.Net Web Form has drag and drop server controls, server events and state management techniques.
Asp.Net Web Form has built-in data controls and best for rapid development with powerful data access.
Visual studio and Visual web developer(free) are tools for developing Asp.Net Web Forms.
Asp.Net MVC Asp.Net MVC is a lightweight and MVC (Model, View, Controller) pattern based development model. Asp.Net MVC divide the web application into three components : Model,View and Controller. It has no drag and drop server controls, server events and state management techniques. Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Henec it is best for developing interactive web application with latest web standards. Visual studio and Visual web developer(free) are tools for developing Asp.Net MVC application.
Asp.Net Web Page Asp.Net Web Page is also a lightweight and Razor syntax based development model. Asp.Net Web Page is a single page model like classic Asp and Php.It also has no drag and drop server controls, server events and state management techniques. Asp.Net Web Page has built-in template and helpers also provide full control over markup. Hence it is best for developing beautiful web application with latest web standards.
What is O/RM?
O/RM is an acronym that stands for object/relational mapping. Basically, an O/RM framework is used to persist model objects in a relational database and retrieve them. It uses metadata information to interface with the database. This way, your data-layer code knows nothing about the database structure. The O/RM tool becomes middleware that completely hides the complexity. The heart of O/RM is the mappingthe mapping technique is what binds the object and relational worlds. By mapping, you express how a class and its properties are related to one or more tables in the database. This information is used by the O/RM tools engine to dynamically build SQL code that retrieves data and transforms it into objects. Similarly, by tracking changes to objects properties, it can use mapping data to send updates back to the database. The mapping information is generally expressed as an XML file. As an alternative, some O/RM tools use attributes on the classes and their properties to maintain mapping data.
Maintainability
Since you have the fewer lines of code to fetch data from database,the fewer lines of code you have to maintain. This is particularly true in the big projects.
Performance
The complexity of O/RM introduces an obvious slowdown in performance. In entity framework first request to fetch data is little bit slow but after that is fast to fetch data from database.
conceptual model
The conceptual model is where you describe the model classes. This file is split into two main sections: the first is a container that lists all the entities and the relationships that are managed by Entity Framework, and the second contains a detailed description of their structure.
STORAGE MODEL
The storage model is the equivalent of the conceptual model, but it describes the database organization. Not only is this file conceptually similar to the previous one, but it also uses the same XML nodes. Unlike the conceptual model, it isnt possible to split this model into several physical files. The first section of this file lists all the tables, views, stored procedures, and foreign keys that are affected. The second section describes the items listed in the first node. Regarding tables and views, the columns and primary keys are described. When it comes to stored procedures, input and output parameters are described. The description of a foreign key contains information about the table involved, the cardinality, and the delete and update rules.
MAPPING MODEL
The mapping file is completely different. Its job isnt to describe something but to compensate for the differences that exist between the two previous models. This is where the real magic of mapping happens: you map a class to one or multiple tables, map one table to one or multiple classes, define inheritance mapping, and map stored procedures for both updates and object retrieval. There is only one important node in this file: it associates the class to a table and can be repeated more than once to ensure that a class can be mapped against multiple tables, and vice versa. Like the storage description file and unlike the conceptual file, the mapping file cant be split into multiple files.
Entity Model specifies a single unit of work, not all our database. If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects.
Disable change tracking for entity if not needed
Whenever you retrieve the data only for reading purpose, not for modification then there is no need of object tracking. So disable object tracking by using MergeOption as below:
NorthwindDataContext context = new NorthwindDataContext() context.tblCities.MergeOption = MergeOption.NoTracking;
This option allow us to turn off the object cache and unnecessary identity management of the objects.
Use Pre-Generating Views to reduce response time for first request
When the object of ObjectContext is created first time in the application, the entity framework creates a set of classes that is required to access the database. This set of classes is called view and if your data model is large then creating the view may delay the web application response to the first request for a page. We can reduce this response time by creating view at compile time by using T4 template or EdmGen.exe command-line tool.
Avoid fetching all the fields if not required
Avoid fetching not required fields from the database. Suppose I have table of Customer with 20 fields and I am interested only in three fields - CustomerID, Name, Address then fetch only these three fields instead of fetching all the fields of the Customer table.
//Bad Practice var customer = (from cust in dataContext.Customers select cust).ToList(); //Good Practice var customerLite = (from cust in dataContext.Customers select new { customer. CustomerID, customer.Name, customer.Address }). ToList ();
In linq we have Var, IEnumerable, IQueryable, IList type collection for data manipulation. Each collection has its importance and performance impact on the query,
so beware of using all these collection for data manipulation. For learning difference among all these collection refer my articles IEnumerable VS IQueryable, IEnumerable VS IList and Var VS IEnumerable.
Use Compiled Query wherever needed
Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow in first time but after that it boost the performance significantly. We use Compile method of CompiledQuery class for making compiled query. Suppose you required to retrieve customers details again and again based on city then make this query to compiled query like as
// create the entity object NorthwindEntities mobjentity = new NorthwindEntities(); //Simple Query IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi" select customer; //Compiled Query Func> compiledQuery = CompiledQuery.Compile>( (ctx, city) =>from customer in ctx.Customers where customer.City == city select customer);
In above query we are passing the string parameter city for filtering the records. For more about anonymous method.
Retrieve only required number of records
When we are binding data to grid or doing paging, retrieve only required no of records to improve performance. This can achieved by using Take,While and Skip methods.
// create the entity object NorthwindEntities mobjentity = new NorthwindEntities(); int pageSize=10,startingPageIndex=2; List lstCus = mobjentity.tblCustomers.Take(pageSize) .Skip(startingPageIndex * pageSize) .ToList();
In LINQ, we use contains method for checking existence. It is converted to "WHERE IN" in SQL which cause performance degrades.
Avoid using Views
Views degrade the LINQ query performance costly. These are slow in performance and impact the performance greatly. So avoid using views in LINQ to Entities.
Debug and Optimize LINQ Query
If you want to debug and optimize your query then LINQ Pad is a great tool for this purpose. I am a big fan of LINQ Pad. It is very useful for query construction, debugging and optimization.
IQueryable lstCus = from customer in mobjentity.tblCustomers where customer.City == "Delhi" select customer; lstCus.Dump();
Dump method of LINQ Pad give the result of above query in the result window.
Introduction to CSS
CSS stands for Cascading Style Sheets.CSS is a language that you can use to define styles against any HTML element. These styles are set using CSS properties.For example, you can set font properties (size, colors, style etc), background images, border styles, and much more.Using CSS, We can define all our common styles in an external Style Sheet. This way, if we want to change every occurence of a style throughout our site, we only need to update one place. Till now, there are css1, css2, css3 versions are used.
Benefits of CSS
There are following benefits :
Easy maintenance
To change the style of an element, we only have to make a change in one place.
Limitations of CSS
The known issue is Browser compatibility issue. Browsers have varying levels of compliance with Style Sheets. This means that some Style Sheet features are supported and some aren't. To confuse things more, some browser manufacturers decide to come up with their own proprietary tags. Fortunately, browser compatibility is becoming less of an issue as the latest browser versions are much more standards-compliant than their earlier counterparts.
CSS IDs
The id selector is used to specify a style for a single, unique element. It is defined with a "#". Example : #para{ text-align:left; color:blue;}
CSS Classes
The class selector is used to specify a style for a group of elements. class selector is most often used on several elements. It is defined with a "." Example :.para {text-align:left;color:blue;}
During creation of an HTML page using CSS, it is essential to know the HTML elements display behavior. HTML elements have three display style options inline, block and none. Each option has its significant in the designing of HTML page. The basic difference among these display options is very important to know in order to use CSS efficiently. In this article, I will expose the basic difference among these display options.
Block
1. 2. 3. 4. 5. Block display elements makes a separate block with a new line before and after. It takes the full available width based on its parent element or container. Using CSS we can fix height and width of block elements. It can have other inline or block elements. <div>, <h1><h6>, <p>, <ul>, <ol>, <dl>, <li>, <dt>, <dd>,<table>, <blockquote>, <pre>,<form> are displayed as block naturally.
Inline
6. Inline display elements stay with the flow of the document and dont force the new line. 7. It takes the width as it needs. 8. Using CSS we cant fix height and width of inline elements. 9. It can have only inline elements. 10. <span>, <a>, <strong>, <em>, <img />, <abbr>, <acronym>, <br>,<input> are displayed as inline naturally.
None
11. Some tags, like <meta />,<script> and <style> are not visible naturally. We can change the display style of block elements to inline and vice-versa.
Examples of block and inline elements A paragraph (html block element <p>)
Paragraph width will be equal to the container width Paragraph height will be equal to its content.
An anchor tag with fixed height and width(to show that it does not work)
We cant set a fixed width and/or height to an inline element.
} </script>
Introduction to JQuery
JQuery is a cross-browser JavaScript library that is developed to simplify the client-side scripting of HTML.It was released in january 2006 at BarCamp NYC by John Resig. JQuery is free, easy to use and open source scripting language. JQuery's syntax are easy. Using Jquery we can select DOM elements, create animations, handle different types of events, and develop ajax based applications. JQuery also provides facilities for developers to create own plugins on top of the JavaScript library. Using these capabilities, developers are able to create high level interaction and animation, advanced effects, theme-able widgets. This contributes to the formation of interactive and dynamic web pages.
Features of JQuery
JQuery is awesome scripting library. I am using it from one year and I am very much impressed to Jquery. I like it and find myself much comfortable to work with it.There are following features of JQuery : 1. 2. 3. 4. 5. 6. 7. 8. DOM traversal and modification (including support for CSS 1-3). HTML element selections. HTML element manipulation. CSS manipulation. Effects and animations. Extensibility through plug-ins. Ajax and Events Utilities - such as browser version and the each function.
Note
1. Both Google and Microsoft provides good support for jQuery.If you do not want to store the jQuery library on your website or own computer, you can load the CDN jQuery core file from Google or Microsoft.You can download the latest version of JQuery using following links.
http://ajax.microsoft.com/ajax/jquery/jquery-1.7.min.js http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js 2. You can download JQuery 1.7 version cheat sheet from here JQuery 1.7 Cheat Sheet
Disable cut, copy & paste using Javascript When we don't want to display any message on cut, copy & paste
1. <asp:TextBox ID="TextBox1" runat="server" oncopy="return false" onpaste="return false" oncut="return false"></asp:TextBox>
5. alert('cut,copy & paste options are disabled !!'); 6. }); 7. }); 8. </script> 9. <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
32. <form name="upload" action=""> 33. <input type="file" name="fUpload" id="fUpload" /> 34. <input type="button" value="Get File Size" onclick="GetFileSize('fUpload');" /> 35. </form> 36. </body> 37. </html>
Above example will work on all browsers including IE, FF, Chrome, Safari, Opera etc.
Introduction to LINQ
LINQ stands for Language-Integrated Query. Basically LINQ address the current database development model in the context of Object Oriented Programming Model. If some one wants to develop database application on .Net platform the very simple approach he uses ADO.Net. ADO.Net is serving as middle ware in application and provides complete object oriented wrapper around the database SQL.So developer must have good knowledge of object oriented concept as well as SQL to develop an application. But incase of Linq SQL statements are become part of the C# and VB.Net code so there are less chance of mistake. LINQ enables developers to query data sources using a query like syntax with both C# and VB.NET. Using LINQ we can query any database and collection.
LINQ to Ado.Net
LINQ to ADO.NET includes different flavors of LINQ to query data from different databases like as Microsoft SQL Server, Oracle, and others. It has following flavours
LINQ to SQL
It is specifically designed for working with Sql Server database. It provides runtime infrastructure for managing relational data as objects. It also supports transactions, views and stored procedures. It is an object-relational mapping (ORM) framework that allow 1-1 mapping of Sql Server database to .net classes. In this mapping the classes that match the database table are created automatically from the database itself and we can use these classes immediately.
LINQ to DataSet
It is an easy and faster way to query data cached in a DataSet object. It also allow LINQ to query over any database that can be query with Ado.Net.
LINQ to Entities
In many ways it is very similar to LINQ to SQL. It uses a conceptual Entity Data Model (EDM). The ADO.NET Entity Framework has been improved in .NET framework 4.0 to query any database like Sql Server, Oracle, MySql, DB2 and many more.
LINQ to XML
It provides an improved XML programming interface. Using this we can query, modify xml document and also save document after modification. System.Xml.Linq namespace contains classes for LINQ to XML.
The JOIN query operator compares the specified properties/keys of two collections for equality by using the EQUALS keyword. By default, all joins queries written by the JOIN keyword are treated as equijoins.
INNER JOIN
Inner join returns only those records or rows that match or exists in both the tables.
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, od.Quantity, od.Price, }).ToList();
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID join ct in dataContext.tblCustomers on od.CustomerID equals ct.CustID orderby od.OrderID select new { od.OrderID, pd.ProductID, pd.Name, pd.UnitPrice, od.Quantity, od.Price, Customer=ct.Name //define anonymous type Customer }).ToList();
NOTE
1. Always remember, both the anonymous types should have exact same number of properties with same name and datatype other wise you will get the compile time error "Type inferencce failed in the call to Join". 2. Both the comparing fields should define either NULL or NOT NULL values. 3. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of NOT NULL field to NULL data type like as above fig.
CROSS JOIN
Cross join is a cartesian join means cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records or rows that are multiplication of record number from both the tables means each row on left table will related to each row of right table. In LINQ to achieve CROSS JOIN behavior, there is no need to use Join clause and where clause. We will write the query as shown below.
C# Code
var q = from c in dataContext.Customers from o in dataContext.Orders select new { c.CustomerID, c.ContactName, a.OrderID, a.OrderDate };
GROUP JOIN
Whene a join clause use an INTO expression, then it is called a group join. A group join produces a sequence of object arrays based on properties equivalence of left collection and right collection. If right collection has no matching elements with left collection then an empty array will be produced.
C# Code
var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID into t orderby pd.ProductID select new { pd.ProductID, pd.Name, pd.UnitPrice, Order=t }).ToList();
Basically, GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups.
XML data is often used to transfer data from one application to another. Since XML is language independent, hence it is a good choice to use xml for transferring data between two different platform applications. In C#, it is easy to make xml from database by using LINQ to SQL and LINQ to XML.
* FROM Product
Now, query the data from above table using LINQ. We can also save the output to xml file.
IEnumerable VS IQueryable
In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by Iqueryable, hence it has all the features of it and except this, it has its own features. Both have its own importance to query data and data manipulation. Lets see both the fetures and take the advantage of both the fetures to boost your LINQ Query performance.
IEnumerable
1. IEnumerable exists in System.Collections Namespace.
2. IEnumerable can move forward only over a collection, it cant move backward and between the items. 3. IEnumerable is best to query data from in-memory collections like List, Array etc. 4. While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. 5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries. 6. IEnumerable supports deferred execution. 7. IEnumerable doesnt supports custom query. 8. IEnumerable doesnt support lazy loading. Hence not suitable for paging like scenarios. 9. Extension methods supports by IEnumerable takes functional objects.
IEnumerable Example
MyDataContext dc = new MyDataContext (); IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S")); list = list.Take<Employee>(10);
Notice that in this query "top 10" is missing since IEnumerable filters records on client side
IQueryable
1. IQueryable exists in System.Linq Namespace. 2. IQueryable can move forward only over a collection, it cant move backward and between the items. 3. IQueryable is best to query data from out-memory (like remote database, service) collections. 4. While query data from database, IQueryable execute select query on server side with all filters. 5. IQueryable is suitable for LINQ to SQL queries. 6. IQueryable supports deferred execution. 7. IQueryable supports custom query using CreateQuery and Execute methods. 8. IQueryable support lazy loading. Hence it is suitable for paging like scenarios. 9. Extension methods supports by IEnumerable takes expression objects means expression tree.
IQueryable Example
MyDataContext dc = new MyDataContext (); IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S")); list = list.Take<Employee>(10);
Notice that in this query "top 10" is exist since IQueryable executes query in SQL server with all filters.
IEnumerable VS IList
In LINQ to query data from collections, we use IEnumerable and IList for data manipulation.IEnumerable is inherited by IList, hence it has all the features of it and except this, it has its own features. IList has below advantage over IEnumerable. In previous article, I explain the difference between IEnumerable and IQueryable.
IList
1. IList exists in System.Collections Namespace. 2. IList is used to access an element in a specific position/index in a list. 3. Like IEnumerable, IList is also best to query data from in-memory collections like List, Array etc. 4. IList is useful when you want to Add or remove items from the list. 5. IList can find out the no of elements in the collection without iterating the collection. 6. IList supports deferred execution. 7. IList doesnt support further filtering.
IEnumerable
1. IEnumerable exists in System.Collections Namespace. 2. IEnumerable can move forward only over a collection, it cant move backward and between the items. 3. IEnumerable is best to query data from in-memory collections like List, Array etc. 4. IEnumerable doent support add or remove items from the list. 5. Using Ienumerable we can find out the no of elements in the collection after iterating the collection. 6. IEnumerable supports deferred execution. 7. IEnumerable supports further filtering.
Var VS IEnumerable
In previous article I explain the difference between IEnumerable and IQuerable, IEnumerable and IList. In this article I expose the difference between Var and IEnumerable. IEnumerable is an interface that can move forward only over a collection, it cant move backward and between the items. Var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration. Both have its own importance to query data and data manipulation.
Var Type
Since Var is anonymous types, hence use it whenever you don't know the type of output or it is anonymous. Suppose you are joining two tables and retrieving data from both the tables then the result will be an Anonymous type.
1. 2. 3. 4. 5. 6. 7. 8. var q =(from e in tblEmployee join d in tblDept on e.DeptID equals d.DeptID select new { e.EmpID, e.FirstName, d.DeptName, });
In above query, result is coming from both the tables so use Var type.
1. var q =(from e in tblEmployee where e.City=="Delhi" select new { 2. e.EmpID, 3. FullName=e.FirstName+" "+e.LastName, 4. e.Salary 5. });
In above query, result is coming only from single table but we are combining the employee's FirstName and LastName to new type FullName that is annonymous type so use Var type. Hence use Var type when you want to make a "custom" type on the fly. More over Var acts like as IQueryable since it execute select query on server side with all filters. Refer below examples for explanation.
IEnumerable Example
1. MyDataContext dc = new MyDataContext (); 2. IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S")); 3. list = list.Take<Employee>(10);
Notice that in this query "top 10" is missing since IEnumerable filters records on client side
Var Example
1. MyDataContext dc = new MyDataContext (); 2. var list = dc.Employees.Where(p => p.Name.StartsWith("S")); 3. list = list.Take<Employee>(10);
Notice that in this query "top 10" is exist since var is a IQueryable type that executes query in SQL server with all filters.
IEnumerable Type
IEnumerable is a forward only collection and is useful when we already know the type of query result. In below query the result will be a list of employee that can be mapped (type cast) to employee table.
1. IEnumerable<tblEmployee> lst =(from e in tblEmployee 2. where e.City=="Delhi" 3. select e);
Note
1. 2. 3. 4.
Use Var type when you want to make a "custom" type on the fly. Use IEnumerable when you already know the type of query result. Var is also good for remote collection. IEnumerable is good for in-memory collection.
Object
Object is representative of the class and is responsible for memory allocation of its data members and member functions.An object is a real world entity having attributes (data type) and behaviors (functions). An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object behavior. For example, the hand can grip something or a Student (object) can give the name or address
Class
Class is a data structure that contains data members (constants files, events), member function methods, properties, constructor, destructor, indexers and nested type.Basically 1. It is a user defined data type. 2. It is a reference type. 3. Infact class is a tag or template for object.
Encapsulation
Encapsulation is a mechanism of binding the data member & member function into a single unit known as class.Encapsulation provides a way for abstraction.In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes.
Data abstraction
Data abstraction is a mechanism to provide the essential features without describing the background details. Means provide the functions to access the hidden (private) data. The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.
Data Hiding
Data hiding is a mechanism to hide the internal structure of an object from rest of the program.In a class private members are hidden from the rest of the program, hence it supports data hiding. Data hiding is also a way to implement data abstraction.
Polymorphism
Polymorphism means one thing in many form.Basically polymorphism is capability of one object to behave in multiple ways. Example : A man role changes at home, college, and outside the home. There are following types of polymorphism : 4. Static polymorphism(compile time) :It is achieved using function overloading and operator overloading. 5. Dynamic polymorphism(runtime time) : It is achieved using function overriding means using virtual function.
Functions
1. Functions have independent existence means they can be defined outside of the class. Ex:- main() function in C, C++ Language 2. Functions are defined in structured languages like Pascal,C and object based language like javaScript 3. Functions are called independently. 4. Functions are self describing unit of code.
1. //function main in C 2. void main() 3. { 4. int a,b,c; 5. a=5; 6. b=6; 7. c=a+b;
8. printf("Sum is : %d",c); 9. }
Methods
1. Methods do not have independent existence they are always defined with in class. Ex:main() method in C# Language that is defined with in a class 2. Methods are defined in object oriented languages like C#, Java 3. Methods are called using instance or object. 4. Methods are used to manipuate instance variable of a class.
1. //method sum in C# 2. class demo 3. { 4. int a,b,c; 5. public void sum() 6. { 7. a=5; 8. b=6; 9. c=a+b; 10. Console.WriteLine("Sum is : {0}",c); 11. } 12. }
Conversion Functions
SQL Serve 2012 has support for new conversion functions TRY_CONVERT, and TRY_PARSE for convering numeric, date, and time values to desired format. These functions are very helpful while programming T-SQL.
1. 2. 3. 4. 5. 6.
--Suppose Employee tables has 500 records --Below query skip 200 rows and fetch the next 20 records SELECT EmpID, EmpName, Salary FROM dbo.Employee ORDER BY EmpID OFFSET 200 ROWS FETCH NEXT 20 ROWS ONLY
T-SQL Sequence
SQL Server 2012 also supports sequence like Oracle database. It works like as IDENTITY field without being a field. The main advantage of sequence is that you can use it in the same way as GUIDs and with better performance than GUIDs when used as a clustered index key.
7. --Create Sequence object 8. CREATE SEQUENCE objSequence 9. START WITH 1 10. INCREMENT BY 1; 11. --Create Employee object 12. DECLARE @Employee TABLE 13. ( 14. ID int NOT NULL PRIMARY KEY, 15. FullName nvarchar(100) NOT NULL 16. ) 17. --Insert values 18. INSERT @Employee (ID, FullName) 19. VALUES (NEXT VALUE FOR objSequence, 'Mohan'), 20. (NEXT VALUE FOR objSequence, 'Deepak'), 21. (NEXT VALUE FOR objSequence, 'Pavan'); 22. --Show data 23. SELECT * FROM @Employee
SQL Server 2012 introduces a new function format() for formatting string data like as C#. It is a CLR based function.
24. SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS [ISO Formatted Date], FORMAT(GETDATE(), 'yyyy-MM-dd hh:mm:ss') AS [Full ISO], FORMAT(GETDATE(), 'MMMM dd, yyyy') AS [Long-EN Date], FORMAT(22.7, 'C', 'en-US') AS [US Currency], FORMAT(99 * 2.226, '000.000') AS [Padded Decimal], FORMAT(12345678, '0,0') AS [Commas in Large Numbers]
Introduction to TFS
TFS stands for Team Foundation Server which is developed by Microsoft. Integration of TFS with Visual Studio enables a team to work together and organize their efforts to complete a project. Dot Net developers use TFS for source control, bug tracking, requirement gathering and to manage complete life cycle of software development. It has below listed features:-
Communication Enhancement
TFS enhance the communication among team members by ensuring that no information or work is lost when a team member hand over his task to team. Project of the team is stored on the TFS and every team member has its own credentials to connect to TFS for accessing the project. TFS provides a central location to team project and each team member coordinate his work at this location.
Team Explorer
All members of a team work together on the team project by using Team Explorer in Visual Studio. Team Explorer connects to the TFS and displays team projects from the server. By using Team Explorer, every team member can get updated work items, projects documents and task to do.
Roles
Roles can be defined on team project that is on TFS. Each role represents one or more disciplines that are required to successful completion of the team project.
Alerts
TFS also provides alerts that are sent to team members by e-mail when something has changed on the team project. We can customize alerts on TFS according to our need.
Source Control
TFS allow the team to manage all source files for a project. We can also add non-source files such as important project documents, project plans etc. to TFS.
Builds
TFS Build enables the team to create and manage product builds regularly. TFS Build also provides build reports on the status and quality of each build.
Reports
Reports related to track status and information (like as work item changes, check-ins and status of product builds etc.) about the project are stored in a database on the TFS
Debug Mode
Developer use debug mode for debugging the web application on live/local server. Debug mode allow developers to break the execution of program using interrupt 3 and step through the code. Debug mode has below features: 1. Less optimized code 2. Some additional instructions are added to enable the developer to set a breakpoint on every source code line. 3. More memory is used by the source code at runtime. 4. Scripts & images downloaded by webresource.axd are not cached. 5. It has big size, and runs slower.
Release Mode
Developer use release mode for final deployment of source code on live server. Release mode dlls contain optimized code and it is for customers. Release mode has below features: 1. More optimized code 2. Some additional instructions are removed and developer cant set a breakpoint on every source code line. 3. Less memory is used by the source code at runtime. 4. Scripts & images downloaded by webresource.axd are cached. 5. It has small size, and runs fast.
Note
There is no difference in functionality of a debug dll and a release dll. usually, when we compile code in debug mode, we have a corresponding .pdb (program database) file. This .pdb file contains information that enables the debugger to map the generated IL (intermediate language) to source code line number. It also contains the names of local variables in the source code.
We can set the compile mode in visual studio as shown in below fig.
Ctrl-Del Ctrl-C or Ctrl-Insert Ctrl-V or Shift-Insert Ctrl-Z or Alt-Backspace Ctrl-Space Ctrl-Y or Ctrl-Shift-Z Ctrl-S Ctrl-Shift-S Ctrl-P F7 Shift-F7 Shift-F8 or F8 Alt-Shift-A Ctrl-Shift-A Shift-F9 F12 Shift-F12 Ctrl-} Ctrl-Shift-}
item to the clipboard Delete next "word" Copies the currently selected item to the clipboard Pastes the item from the clipboard at the cursor location Undo the previous editing action To see intelligence dialog Redo the previous undo action Saves the current selected file Saves all files and projects Displays the Print dialog Switches from the design view to the code view in the editor Switches from the code view to the design view in the editor Navigate to compile time errors Add Existing Item(file) to selected project Add New Item(file) to selected project Display the selected item quick output means contains value while debugging Moves the cursor to the selected method, variable, class definition. Finds the reference to the selected method, variable, class or the item under the cursor Match curly braces, brackets or compiler directives Select text between matched braces, brackets or compiler directives
Text manipulation
Description Indents the currently selected line or lines by one tab stop. If there is no selection, this inserts a tab stop Complete the syntax of an item. ExampleWrite for and now press Tab-Tab, then for loop syntax will be automatically completed. Similarly it works for property, index, class syntax. Moves current line or selected lines one tab stop to the left Deletes one character to the left of the cursor Marks the current line or selected lines of code as a comment, using the correct comment
Ctrl-K, Ctrl-U Ctrl-K, Ctrl-D Ctrl-T or Shift-Enter Ctrl-U Ctrl-Shift-U Ctrl-Shift-Right Arrow Ctrl-Right Arrow Shift-End Shift-Home Shift-Alt-Arrows or Alt-Mouse Ctrl-Delete Ctrl-Backspace Ctrl-G
syntax for the programming language Removes the comment syntax from the current line or currently selected lines of code Do proper alignment of all the code of design view and code view Swaps the characters on either side of the cursor. (For example, AC|BD becomes AB| CD.) Available only in text editors Changes the selected text to lowercase characters Changes the selected text to uppercase characters Select the entire word with space from start to end Move the cursor in forward direction word by word Select the entire line from start to end Select the entire line from end to start Column wise text selection for text manipulation Deletes the word to the right of the cursor Deletes the word to the left of the cursor Jump to line number or go to line
Project related
Ctrl-Shift-N Ctrl-O Ctrl-Shift-O Ctrl-M-O Ctrl-M-P or Ctrl-M-L Ctrl-F Ctrl-H Ctrl-Shift-F Ctrl-Tab F9
Description Builds the solution Displays the New File dialog. Note: files created this way are not associated with a project. Use Ctrl-Shift-A to add a new file in a project Displays the New Project dialog Displays the Open File dialog Displays the Open Project dialog Collapse all the methods, classes, regions in the current code behind or class file Expands all the methods, classes, regions in the current code behind or class file Displays the Find dialog Displays the Replace dialog Find the reference of selected item into entire solution. Move from one opened file to another opened file in visual studio. Sets or removes a breakpoint at the current line
Enables or disables the breakpoint on the current line of code. The line must already have a breakpoint for this to work Runs the code with invoking the debugger. Runs the code without invoking the debugger. Displays the Properties window, which lists the design-time properties and events for the currently selected item Displays the Server Explorer window, which allows you to view and manipulate database servers, event logs, message queues, web services, and many other operating system services Displays the Solution Explorer, which lists the projects and files in the current solution Displays the Toolbox, which contains controls and other items that can be dragged into editor and designer windows Displays the Immediate window, where you can find the controls or variables values or can do data manipulation during debugging
You can use Weather Reporting web service to display weather information in your personal website.
Stock Quote
You can display latest update of Share market with Stock Quote on your web site
News Headline
You can display latest news update by using News Headline Web Service in your website.
Introduction to WCF
WCF stands for Windows Communication Foundation. It is Microsoft's latest technology that enables applications in a distributed environment to communicate with each other.WCF is Microsoft's unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing. WCF is an umbrella technology that covers ASMX web services, .NET remoting, WSE, Enterprise Service, and System.Messaging. It is designed to offer a manageable approach to
distributed computing, broad interoperability, and direct support for service orientation. WCF supports many styles of distributed application development by providing a layered architecture.
Address (Where)
It specifies the location of the service means, where the service is hosted. The service hosting URL may be like http://server/wcfService. Clients will use this location to communicate with your service.
Binding (How)
It specifies how the client will communicate to the service. We have different protocols (like http,tcp,named pipe,msmq) for the WCF to communicate to the client.
Contract (What)
It specifies what the service will do. For this purpose we have different contract like as Data Contract, Operation Contract, Message Contract, Fault Contract. I will discuss all these later.
WCF Hosting
A WCF service is a component that can be called by other applications. It must be hosted in an environment in order to be discovered and used by others. The WCF host is an application that controls the lifetime of the service. With .NET 3.0 and beyond, there are several ways to host the service.
Self hosting
A WCF service can be self-hosted, which means that the service runs as a standalone application and controls its own lifetime. This is the most flexible and easiest way of hosting a WCF service, but its availability and features are limited.
IIS hosting
A better way of hosting a WCF service is to use IIS. This is the traditional way of hosting a web service. IIS, by nature, has many useful features, such as process recycling, idle shutdown, process health monitoring, message-based activation, high availability, easy manageability, versioning, and deployment scenarios. All of these features are required for enterprise-level WCF services.
Request Headers
1. OPTIONS http://myserver/MyService.svc/GetStates HTTP/1.1 2. Host: 192.168.4.156 User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0 3. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 4. Accept-Language: en-us,en;q=0.5 5. Accept-Encoding: gzip, deflate
6. Proxy-Connection: keep-alive 7. Origin: http://192.168.4.156:90 8. Access-Control-Request-Method: POST 9. Access-Control-Request-Headers: content-type 10. Pragma: no-cache 11. Cache-Control: no-cache
Response Headers
1. HTTP/1.0 405 Method Not Allowed 2. Cache-Control: private 3. Allow: POST 4. Content-Length: 1565 5. Content-Type: text/html; charset=UTF-8 6. Server: Microsoft-IIS/7.0 7. X-AspNet-Version: 4.0.30319 8. X-Powered-By: ASP.NET 9. Access-Control-Allow-Origin: * 10. Access-Control-Allow-Headers: Content-Type 11. Date: Fri, 04 May 2012 12:05:17 GMT 12. X-Cache: MISS from c1india.noida.in 13. X-Cache-Lookup: MISS from c1india.noida.in:3128 14. Via: 1.0 c1india.noida.in:3128 (squid/2.6.STABLE21) 15. Proxy-Connection: close
In above request headers the method is "OPTION" not "POST" and the response headers has content-type "text/html; charset=UTF-8" instead of "json;charset=UTF-8". To change these options we need to do some changes in web.config of hosted wcf service.
22. Supplier msupp=new Supplier(); 23. msupp.Name=supp.Name; 24. msupp.Email=supp.Email 25. //Make Supplier List to retun 26. lst.Add(msupp); 27. } 28. return lst; 29. } 30. } 31. }
Global.asax Code
You can also define your hosted service web.config setting in Global.asax file. If you have defined setting in web.config then there is no need to do here.
1. protected void Application_BeginRequest(object sender, EventArgs e) 2. { 3. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , *); 4. if (HttpContext.Current.Request.HttpMethod == "OPTIONS" ) 5. { 6. //These headers are handling the "pre-flight" OPTIONS call sent by the browser 7. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" ); 8. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" ); 9. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" ); 10. HttpContext.Current.Response.End(); 11. } 12. }
Note
1. You can define cross domain setting either in web.config or in global.asax file of your wcf service.
In this article, I am going to share my experience with you so that you will be able to resolve this error in ajax enabled wcf service. I have the below service and code for calling wcf.
WCF Service
1. namespace WCFBAL 2. { 3. [DataContract] 4. public class Employee 5. { 6. [DataMember] 7. public int EmpID; 8. [DataMember] 9. public string Name; 10. [DataMember] 11. public int Salary; 12. [DataMember] 13. public DateTime JoiningDate; 14. } 15. [ServiceContract(Namespace = "")] 16. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 17. public class WCFBALService 18. { 19. [WebInvoke(Method = "POST")] 20. public Employee GetEmpInfo(int mEmpID) 21. { 22. try 23. { 24. //suppose you have a list of employee like as in the database 25. List lst = new List() 26. { 27. new Employee { EmpID = 1, Name = "Deepak", Salary = 12000, JoiningDate = Convert.ToDateTime("11/05/2011") }, 28. new Employee { EmpID = 2, Name = "Mohan", Salary = 18000}, 29. new Employee { EmpID = 3, Name = "Mohan", JoiningDate = Convert.ToDateTime("06/10/2011") } 30. }; 31. var q = lst.Where(m => m.EmpID == mEmpID).FirstOrDefault(); 32. Employee mobjEmp = new Employee(); 33. if (q != null) 34. { 35. mobjEmp.EmpID = q.EmpID; 36. mobjEmp.Name = q.Name; 37. mobjEmp.Salary = q.Salary; // comment this line to expect same error 38. //The no error will be raised since "Salary" field is of int type and default value of int variable is "0", so zero value will be assigned to it. 39. mobjEmp.JoiningDate = q.JoiningDate; // comment this line and provide mEmpID=1 to raise error 40. //The error will be raised since "JoiningDate" field is not being serialized because this of DateTime and this has no default value and not assign any value to it. 41. } 42. return mobjEmp;
43. } 44. catch (Exception mex) 45. { 46. return null; 47. } 48. } 49. } 50. }
Routing
Asp.net Routing is the first step in MVC request cycle. Basically it is a pattern matching system that matches the requests URL against the registered URL patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the appropriate handler for that request. Otherwise, the routing engine returns a 404 HTTP status code against that request. When application starts at first time, it registers one or more patterns to the Route Table to tell the routing system what to do with any requests that match these patterns. An application has only one Route Table and this is setup in the Global.asax file of the application.
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); }
MvcHandler
The handler returned from the RouteTable will always be an MvcHandler and represents a particular RouteContext. Actually, MvcHandler creates a controller, and also executes the controller.
Controller
The controller determines which action method of the controller class to call, and then calls that method
View Result
The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult,
View Engine
Now the ViewResult calls into the current view engine to render the view. Controller is responsible only for preparing the data and decides which view to display by returning a ViewResult instance.
View
The data rendered by the current view engine is displayed on the view.
Controller
Basically, the controller Receives input like as form values, query strings values etc. from users via the View and perform required operations on the user's inputs with the help of Model and passing the results back to the View. Actually, controllers are classes that have methods or action results and these actions results are called by the routing system to process a particular request.
Creating a Controller
For creating a controller, do right-click on the Controller folder in your mvc application and select the menu option Add, Controller. After selection the Add Controller dialog is being displayed as shown in fig. Now enter your controller name before Controller word.
In this way you have successfully created your controller as shown in fig.
ViewResult
Returns a ViewResult which renders the specified or default view by using controller View() helper method.
PartialViewResult
Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using controller PartialView() helper method.
RedirectResult
Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.
RedirectToRouteResult
Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an action method or specific route entry by using controller RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.
ContentResult
Returns a ContentResult which renders raw text like as "Hello, DotNet Tricks!" by using controller Content() helper method.
JsonResult
Returns a JsonResult which serializes an object in JSON format ( like as "{ "Message": Hello, World! }") and renders it by using controller Json() helper method.
JavaScriptResult
Returns a JavaScriptResult which renders a snippet of JavaScript code like as "function hello() { alert(Hello, World!); }" by using controller JavaScript() helper method. This is used only in AJAX scenarios.
FileResult
Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using controller File() helper method.
EmptyResult
Returns no result returned by an action. This has no controller helper method.
HttpNotFoundResult
Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.
HttpUnauthorizedResult
Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code(means "not authorized") response. This has no controller helper method. This is used for authentication (forms authentication or Windows authentication) to ask the user to log in.
HttpStatusCodeResult
Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.
Removing the Web Form View Engine for better performance of Razor View Engine
By default MVC is configured to resolve a view by searching the views that match the Web Form view engine's naming conventions first. After that MVC begins search for the views that match the Razor view engine's naming conventions as shown in below fig.
So, If are not using ASPX views in your MVC applications then the checking four unused locations first for every return View() and Html.RenderPartial is quite wasteful and time consuming. After removing Web Form engine, Razor View Engine will be twice as fast with the Web Form engine.
After removing all the view engines and register only Razor view engine, now MVC try to resolve a view by searching the views that match the Razor view engine's naming conventions only as shown in fig.
Note
1. After removing Web Form engine, Razor View Engine will be twice as fast with the Web Form engine.
The above if-statement prevents the rendering of script tag into the html source code and it used only by the Visual Studio for jQuery intellisense support. To check jQuery intellisense type the $ or $( between your $(document).ready(function() function and you can see the intellisense as shown in fig.
Note
1. In MVC Razor, there is no central place to add the reference to the vsdoc.js file. We need to add this code line to each every view separately to enable the IntelliSense support for jQuery.
and then give the name for partial view and also checked the Create a partial view option as shown in fig.
Note
1. It is best practice to create partial view in the shared folder and partial view name is preceded by "_", but it is not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.
The main difference between above two methods is that the Partial helper method renders a partial view into a string while RenderPartial method writes directly into the response stream instead of returning a string.
Note
1. Partial or RenderPartial methods are used when a model for the page is already populated with all the information. For example in a blog to show an article comment we would like to use Partial or RenderPartial methods since an article information are already populated in the model. 2. RenderAction method is used when some information is need to show on multiple pages. Hence partial view should have its own model. For example to category list of articles on each and every page we would like to use RenderAction method since the list of category is populated by different model.
ViewModel Example
Designing the model
public class UserLoginModel { [Required(ErrorMessage = "Please enter your username")]
[Display(Name = "User Name")] [MaxLength(50)] public string UserName { get; set; } [Required(ErrorMessage = "Please enter your password")] [Display(Name = "Password")] [MaxLength(50)] public string Password { get; set; } }
} else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } catch (Exception ex) { } } return View(user); }
DisplayName
specify the display name for a property.
DisplayFormat
specify the display format for a property like different format for Date proerty.
Required
Specify a property as required.
ReqularExpression
validate the value of a property by specified regular expression pattern.
Range
validate the value of a property with in a specified range of values.
StringLength
specify min and max length for a string property.
MaxLength
specify max length for a string property.
Bind
specify fields to include or exclude when adding parameter or form values to model properties.
ScaffoldColumn
specify fields for hiding from editor forms.
15.
[Required(ErrorMessage = "Employee Address is required")] [StringLength(300)] 16. public string Address { get; set; } 17. [Required(ErrorMessage = "Salary is required")] [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")] 18. public int Salary{ get; set; } 19. [Required(ErrorMessage = "Please enter your email address")] [DataType(DataType.EmailAddress)] 20. [Display(Name = "Email address")] 21. [MaxLength(50)] 22. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")] 23. public string Email { get; set; } 24. } 25. }
Once we have define validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view.
1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 2. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
24.
<div class="editor-field"> @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email) 25. </div> 26. <p> <input type="submit" value="Save" /> 27. </p> 28. </div> 29. }