Friday, November 30, 2012

SQL Server 2005 Try and Catch Exception Handling


Introduction

Handling errors in SQL Server became easy with the number of different ways. SQL Server 2005 has introduced the new option that helps to handle the errors effectively. Sometimes we cannot capture the errors which occurred in the end user. Even if we want to know the errors which occurred in the end user, we need to write the code to send it to us. It creates an additional overhead for the server.
SQL Server 2005 introduced TRY...CATCH statement which helps us to handle the errors effectively in the back end. This handling of the exception can provide additional information about the errors.

TRY...CATCH

The TRY...CATCH statement works the same as in the programming languages. First it gets executed in the SQL statement which we have written in the TRY block and if any error occurs, then it will get executed the CATCHblock.
BEGIN TRY
// SQL Statements
END TRY
BEGIN CATCH
//Handle the exception details
END CATCH
There are a number of error handling property statements like the following:
 ERROR_NUMBER()  
 ERROR_STATE()  
 ERROR_SEVERITY()  
 ERROR_LINE()  
 ERROR_PROCEDURE()  
 ERROR_MESSAGE()   
Normally, SQL Server stores the default error messages which occurred in the execution in the following system table:
select * from sys.messages
But we can create our own error message details with the help of this exception handling.



Problem
Error handling in previous versions of SQL Server was not the easiest thing to do.  You could test the value of @@ERROR or check @@ROWCOUNT, but if the error was a fatal error you did not have a lot of options.
Solution
With SQL Server 2005, new error handling has been introduced with the TRY...CATCH processing.  Basically what happens is when an error occurs the processing in the TRY block stops and processing is then picked up in the CATCH block.  The following illustrates a simple example of how this is done:
StepCodeOutput
1CREATE PROCEDURE usp_ExampleProc
AS
     SELECT * FROM NonexistentTable;
GO
Command(s) completed successfully.
2EXECUTE usp_ExampleProcMsg 208, Level 16, State 1, Procedure usp_ExampleProc, Line 3
Invalid object name 'NonexistentTable'.

(Note: Processing Stops)
3BEGIN TRY
     EXECUTE usp_ExampleProc
END TRY

BEGIN CATCH
     SELECT
          ERROR_NUMBER() as ErrorNumber,
          ERROR_MESSAGE() as ErrorMessage;
END CATCH;
208 Invalid object name 'NonexistentTable'.
(Note: Processing Continues)
4BEGIN TRY
     EXECUTE usp_ExampleProc
END TRY

BEGIN CATCH

END CATCH;
Command(s) completed successfully.
(Note: Processing Continues)
  • As you can see from the above code and output that when we create the stored procedure for a non-existent table in Step 1 the procedure creates without a problem. 
  • If we run the stored procedure using the code in Step 2, we get an error message that the object does not exist.
  • If we run the stored procedure using the code in Step 3, the error is sent to the CATCH block and an error message is returned. At this point processing can continue without a problem.
  • To further illustrate this in Step 4 the stored procedure is run, the error is caught in the CATCH block, but we are not doing anything to process the error.  Normally you would have something happen, but this shows that you don't have to have any code in the CATCH block.
The values that can be retrieved from the error are also much more detailed, then what you could get with previous versions of SQL Server.  Below is a list of the data that can be retrieved when an error occurs.
  • ERROR_NUMBER() - returns the number of the error.
  • ERROR_SEVERITY() - returns the severity.
  • ERROR_STATE() - returns the error state number.
  • ERROR_PROCEDURE() - returns the name of the stored procedure or trigger where the error occurred.
  • ERROR_LINE() - returns the line number inside the routine that caused the error.
  • ERROR_MESSAGE() - returns the complete text of the error message.
Running the same query above, but returning all of the error information is displayed below.
ERROR_NUMBERERROR_SEVERITYERROR_STATEERROR_PROCEDUREERROR_LINEERROR_MESSAGE
208161usp_ExampleProc3Invalid object name 'NonexistentTable'.
Another nice thing about the TRY...CATCH processing is that you can nest or have multiple TRY...CATCH blocks in your code.  The following although not very practical illustrates how the error is caught and then processing continues and the error is caught again and processing continues again.
StepCodeOutput
1BEGIN TRY
     BEGIN TRY
          EXECUTE usp_ExampleProc
     END TRY

     BEGIN CATCH
          SELECT
               ERROR_NUMBER() AS ErrorNumber,
               ERROR_SEVERITY() AS ErrorSeverity;
     END CATCH;

     EXECUTE usp_ExampleProc
END TRY

BEGIN CATCH
     SELECT
          ERROR_NUMBER() AS ErrorNumber,
          ERROR_SEVERITY() AS ErrorSeverity;
END CATCH;
208 Invalid object name 'NonexistentTable'.

208 Invalid object name 'NonexistentTable'.
Next Steps

Tuesday, November 27, 2012

GET and POST methods in HTML/ASP.NET forms – difference between GET and POST


GET and POST methods in HTML/ASP.NET forms – difference between GET and POST


In this article we will discuss the form submission methods GET and POST with examples and differences of them.

The Get/Post methods are used to send client information to web server. The methods are specified in inside form element using method attribute.

Syntax:
<form method="get|post">
The method attribute uses either get or post. Default is GET method.

GET method:
This method appends form data to page request URL with key value pairs called as query string.
E.g.: http://www.dotnetmirror.com/home.htm?key1=value1&key2=value2
  • Page request URL and the form data information (query string) are separated by the ? Character.
  • Get method is restricted to send up to 1024 characters only.
  • Never use Get method to send sensitive information like password, login information to web server.
  • Form data support only ASCII characters.Cannot used to send binary information like word document, text file and image data to server.
  • We can access query string in ASP.NET using Request.QueryString["key1"]
 Example: Usage of Get method In ASP.NET:

In the below example we will see how GET method passed data from login.html (client) to login.aspx page (server).

Login.html
<html>
<body>
<form method="get" action="Login.aspx">
   User Name: <input id="txtuserName" type="text" name="username" />       
    <input id="btnSubmit" type="submit" value="Submit data using GET" />
    </form>
</body>
</html>
Login.aspx
<html>
<body>
    <form id="form1" runat="server">
    <div>
    Welcome <b><% Response.Write(Request.QueryString["username"].ToString()); %></b>
    </div>
    </form>
</body>
</html>
Output:
Login.html
Fig1 - Login.html with GET








Login.aspx
Fig2 - Login.aspx with GET



Explanation: Login.html has username data which is sent using get method to login.aspx (server). In the output of second screen shot we can see there is key (username) value(DotNetMirror) data as query stirng in the URL which is submitted to login.aspx page and the output(Welcome DotNetMirror) is show in login.aspx page.

Post Method:
  • POST method transfers information over HTTP headers.
  • Data transfer through HTTP headers so using secure HTTP protocol we can make sure that data is secured.
  • No restriction on sending data size via Post and also we can send binary data or ASCII information using POST method.
  • We can access form data in ASP.NET using Request.Form["key1"]
 Example: Usage of Post method In ASP.NET:

Login.html
<html>
<body>
<form method="post" action="Login.aspx">
   User Name: <input id="txtuserName" type="text" name="username" />       
    <input id="btnSubmit" type="submit" value="Submit data using POST" />
    </form>
</body>
</html>
Login.aspx
<html>
<body>
    <form id="form1" runat="server">
    <div>
    Welcome <b><% Response.Write(Request.Form["username"].ToString()); %></b>
    </div>
    </form>
</body>
</html>
Output:
Login.html
Fig3 - Login.html with POST








Login.aspx
Fig4 - Login.aspx with POST


Explanation: Login.html has username data which is sent using post method to login.aspx (server).The output (Welcome DotNetMirror) is show in login.aspx page.

Note: we can observe the post method did not send any query string like what we have seen in get method. Fig2 has query string where Fig4 does not have data in URL.

Usage of Post method:
  • If the form data is large then use POST method because GET method cannot handle long URL’s
  • Form data contains Non-ASCII characters use POST because GET doesn’t support it.

Difference between GET and Post:

GET
POST
Data will be arranged in HTTP header by appending to the URL as query string
Data will be arranged in HTTP message body.
Data is in query string so user can view the data
Not visible to user
Less secured compared to POST method because data is in query string so it will be saved in browser history and web server logs
Bit safer than GET method because data is not saved in history or web server logs
As data is saved in URL so its saves only 2048 bytes data
Can be used for any amount of data
Can be bookmarked
Can’t bookmarked
Hacking will be easy
Hacking is difficult
Only ASCII character data type allowed
No restrictions. Allows binary data also
Caching is possible
No caching


Wednesday, November 21, 2012

Error Handling in ASP.Net Ajax Applications

Error Handling in ASP.Net Ajax Applications

My previous articles, Implementing AJAX Enabled Applications in ASP.Net and Building AJAX Applications using ASP.Net AJAXprovided a good understanding on AJAX and implementing AJAX enabled application using ASP.Net AJAX. Moving forward, we will concentrate on implementing AJAX applications with more advanced features. This article will discuss on various error handling techniques and the ways of notifying errors to the users available in ASP.Net AJAX applications.
By default, whenever there are any error occurred in the server side processing when using ASP.Net Ajax, the error message is notified to the user using a message box (alert). The error message that is displayed on the message box will be the actual error message contained in the original exception’s Message property. In web applications, we normally show an error page with a generic message to the user and log the technical error information to a log file or database or email the error message. This article will help us to customize the errors and notify the users in a better way that gives a better user experience. Moving forward, we will see,
Ø       Show a Generic Error Message.
Ø       Display Generic Error with Technical information.
Ø       Displaying error message on the page instead of MessageBox.
Ø       Using ASP.Net Error Handling Techniques.

Show a Generic Error Message
It will be better, if we suppress the technical error message and instead show a generic error message to the user when there is an error occurred in the server side processing. To do this, ScriptManager object has a property called AsyncPostBackErrorMessagewhich can be used to specify a generic error message.
For example,
ScriptManager1. AsyncPostBackErrorMessage = “Error Occurred”;

This will always give “Error Occurred!!” message for all the exceptions happened in server side processing. Refer the below figure.
Display Generic Error with Technical Information
There is an event called AsyncPostBackError which will be called on the server when there is an error occurred. We can set AsyncPostBackErrorMessage property of ScriptManager object either declaratively or can be customized in this event. e.Exception.Message property will give the actual technical error information which can be logged or displayed to the user.

ASPX
Codebehind
 protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
    {
        ScriptManager1.AsyncPostBackErrorMessage = "Error Occured!!\n" + e.Exception.Message;
    }

Refer the below figure for better understanding.


Displaying the error message on the page instead of MessageBox
Every time when there is an error, it is then notified to the users through a Message box in ASP.Net AJAX application. It will be better if we suppress this message box and display the error information in the page instead of the message box.
To do this, we can utilize the endRequest() event of PageRequestManager object which manages the AJAX in the client side. We can suppress the message box and display the actual error in the page through this event. To get an instance of PageRequestManager, we can call the method Sys.WebForms.PageRequestManager.getInstance().
To display the error message in the page instead of a message box we can use the following script.

 


ASP.Net Hosting

Recent Articles
There is one PageRequestManager object per page which manages partial-page rendering in the browser. PageRequestManager class have series of events which gets executed for an Asynchronous postback.
The order of the events are,
initializeRequest
beginRequest
pageLoading
pageLoaded
endRequest

In the above code, we are displaying the error message in a DIV tag by suppressing the message box in endRequest() event. The EndRequestEventArgs(args, 2nd argument of endRequest event) object have 2 properties called Error and ErrorHandled. Calling args.set_errorHandled(true) sets the ErrorHandled property to true and thus, it suppresses the message box. Refer the below figure where the error message is displayed in the page.

Using ASP.Net Error Handling Techniques

section in the web.config
The custom error section in Web.Config setting will still work with ASP.Net AJAX applications. For example,
   
   

The above setting in web.config will redirect the user to the error page whenever any error occurs in the server processing. There is a property calledAllowCustomErrorsRedirect in ScriptManager object which is set to true by default. Whenever we have this property enabled and endRequest() event is also implemented in Javascipt for error handling, the custom error page will precede and the user will be redirected to Error page. So, we have to make the AllowCustomErrorsRedirectproperty to false to display the error in the same page. The same holds true when we use error handling through Application_Error event in Global.asax and Page_Error Event in page level. Refer my article about Custom Error Handling on ASP.Net in reference section.

Tuesday, November 20, 2012

Normal Forms with examples



Normalization or data normalization is a process to organize the data into tabular format (database tables). A good database design includes the normalization, without normalization a database system may slow, inefficient and might not produce the expected result. Normalization reduces the data redundancy and inconsistent data dependency.

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.
  1. First Normal Form (1NF)

    A database table is said to be in 1NF if it contains no repeating fields/columns. The process of converting the UNF table into 1NF is as follows:
    1. Separate the repeating fields into new database tables along with the key from unnormalized database table.
    2. The primary key of new database tables may be a composite key
    1NF of above UNF table is as follows:
  2. Second Normal Form (2NF)

    A database table is said to be in 2NF if it is in 1NF and contains only those fields/columns that are functionally dependent(means the value of field is determined by the value of another field(s)) on the primary key. In 2NF we remove the partial dependencies of any non-key field.
    The process of converting the database table into 2NF is as follows:
    1. 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.
    2. 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:
  3. Third Normal Form (3NF)

    A database table is said to be in 3NF if it is in 2NF and all non keys fields should be dependent on primary key or We can also said a table to be in 3NF if it is in 2NF and no fields of the table is transitively functionally dependent on the primary key.The process of converting the table into 3NF is as follows:
    1. Remove the transitive dependecies(A type of functional dependency where a field is functionally dependent on the Field that is not the primary key.Hence its value is determined, indirectly by the primary key )
    2. Make separate table for transitive dependent Field.
    3NF of above 2NF tables is as follows:
  4. Boyce Code Normal Form (BCNF)

    A database table is said to be in BCNF if it is in 3NF and contains each and every determinant as a candidate key.The process of converting the table into BCNF is as follows:
    1. Remove the non trival functional dependency.
    2. Make separate table for the determinants.
    BCNF of below table is as follows:
  5. Fourth Normal Form (4NF)

    A database table is said to be in 4NF if it is in BCNF and primary key has one-to-one relationship to all non keys fields or We can also said a table to be in 4NF if it is in BCNF and contains no multi-valued dependencies.The process of converting the table into 4NF is as follows:
    1. Remove the multivalued dependency.
    2. Make separate table for multivalued Fields.
    4NF of below table is as follows:
  6. Fifth Normal Form (5NF)

    A database table is said to be in 5NF if it is in 4NF and contains no redundant values or We can also said a table to be in 5NF if it is in 4NF and contains no join dependencies.The process of converting the table into 5NF is as follows:
    1. Remove the join dependency.
    2. Break the database table into smaller and smaller tables to remove all data redundancy.
    5NF of below table is as follows:

Thursday, November 15, 2012

How to join two DataTables


How to join two DataTables using C#



I have found out the way to get the join of the tables using the GetParentRow() method in combination with a "Relation" in the DataSet.

Here is the code:

DataTable dt1 = new DataTable("Table1");
DataTable dt2 = new DataTable("Table2");
DataSet ds = new DataSet("DataSet");

dt1.Columns.Add("Eno"typeof(Int32));
dt1.Columns.Add("Ename"typeof(String));
dt1.Columns.Add("Salary"typeof(Double));
dt1.Columns.Add("Deptno"typeof(Int32));
dt1.PrimaryKey = new DataColumn[] { dt1.Columns["Eno"] };

dt2.Columns.Add("Deptno"typeof(Int32));
dt2.Columns.Add("Dname"typeof(String));
dt2.PrimaryKey = new DataColumn[] { dt2.Columns["Deptno"] };

ds.Tables.Add(dt1);
ds.Tables.Add(dt2);

// Loading data into dt1, dt2:
object[] o1 ={ 1, "dvs.kiran kumar", 50000.50, 10 };
object[] o2 ={ 2, "Raj", 4000.50, 20 };
object[] o3 ={ 3, "Gary", 10000.50, 10 };

object[] c1 ={ 10, "MFG" };
object[] c2 ={ 20, "EAS" };
object[] c3 ={ 30, "E&U" };
object[] c4 ={ 40, "PES" };

dt2.Rows.Add(c1);
dt2.Rows.Add(c2);
dt2.Rows.Add(c3);
dt2.Rows.Add(c4);

dt1.Rows.Add(o1);
dt1.Rows.Add(o2);
dt1.Rows.Add(o3);

DataRelation drel = new DataRelation("EquiJoin", dt2.Columns["Deptno"], dt1.Columns["Deptno"]);
ds.Relations.Add(drel);

DataTable jt = new DataTable("Joinedtable");
jt.Columns.Add("Eno"typeof(Int32));
jt.Columns.Add("Ename"typeof(String));
jt.Columns.Add("Salary"typeof(Double));
jt.Columns.Add("Deptno"typeof(Int32));
jt.Columns.Add("Dname"typeof(String));
ds.Tables.Add(jt);
foreach (DataRow dr in ds.Tables["Table1"].Rows)
{
       DataRow parent = dr.GetParentRow("EquiJoin");
       DataRow current = jt.NewRow();
       // Just add all the columns' data in "dr" to the New table.
       for (int i = 0; i < ds.Tables["Table1"].Columns.Count; i++)
       {
             current[ i ] = dr[ i ];
       }
       // Add the column that is not present in the child, which is present in the parent.
       current["Dname"] = parent["Dname"];
       jt.Rows.Add(current);
}
dataGridView1.DataSource = ds.Tables["Joinedtable"];