Hello All, We are going to start new batch from next week. message/call or mail us for more details.

5 September 2013

Types Of Exception Handling Techniques in ASP.NET

Exceptions or errors are unusual occurrences that happen within the logic of an application. You cannot program for every possibility; hence, they are imminent. If an exception occurs within an application, the user is presented with a yellow page that looks ugly. So, how do you deal with these situations? You use exception handling techniques in ASP.NET.

There are three ways to handle exceptions/errors in ASP.NET:
  1. try-catch block. This is also called Structured Exception Handling (SEH).
  2. Error Events.
  3. Custom Error Page.
You will look at each one of them in detail in the next sections.

Try-Catch Block

Enclose code that accesses files, databases, and so forth inside a try-catch block because access to those resources might be denied due to various reasons causing an exception. The third part of this block is finally. It is executed irrespective of the fact that an exception has been raised. Hence, use the finally block to complete the housekeeping jobs.

As a good programming practice, always catch specific exceptions. To view the exception types supported by the .NET Framework, use the Debug menu and select Exceptions in Visual Studio.NET.

In the following code, you try to access a table that does not exist in the Northwind database; therefore, an exception is raised. By using the try catch and finally block, you handle the exception and display a message.
  1. try
  2. {
  3. con = new SqlConnection("integrated security=SSPI;
  4. data source= (local);persist security info=False;
  5. initial catalog=Northwind");
  6. da = new SqlDataAdapter("Select * from TblNotExisits", con);
  7. ds = new DataSet();
  8. da.Fill(ds);
  9. }
  10. catch(SqlException ex)
  11. {
  12. return "Connection Unsuccessful " + ex.Message;
  13. }
  14. finally
  15. {
  16. con.Dispose();
  17. }
  18. return "Connection Successful";

Using Error Events

There are three different error events in ASP.NET that can be used in conjunction with SEH so that all exceptions are handled and the user is presented with a user-friendly error message.
  1. Page_Error: Occurs when an error occurs within the Web page. This event is in the Web form.
  2. Global_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.
  3. Application_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.
Methods in the Server object are used to handle the exception in the error events.
  1. GetLastError: Gets the last exception that occurred on the server.
  2. ClearError: Use this method to handle the exception and stop the error to trigger the subsequent error event or display the error to the user.
In the following code, you handle the exception in all the above three mentioned events but call the ClearError method only in the Application_Error event so that the error is propogated to the above level.
  1. private void Page_Error(object sender, System.EventArgs e)
  2. {
  3. Exception ex = Server.GetLastError();
  4. Response.Write("Handled error from Page<br>");
  5. //Server.ClearError();
  6. }
  7. protected void Application_Error(Object sender, EventArgs e)
  8. {
  9. Exception ex = Server.GetLastError();
  10. Response.Write("Handled error from Application <br>");
  11. Server.ClearError();
  12. }
  13. protected void Global_Error(Object sender, EventArgs e)
  14. {
  15. Exception ex = Server.GetLastError();
  16. Response.Write("Handled error from Global <br>");
  17. }

Using Custom Error Pages

Use custom error page to handle HTTP exceptions such as page not found, unauthorized access, and so forth. You can specify custom error pages in two places:
  1. customErrors section of the web.config file. This setting specifies the application-wide error page to display for unhandled HTTP errors. HTTP errors are identified by the HTTP status code. Include the <error> tag in the customErrors to display a status code-specific error page. Does not work with .htm or .html files. Set the mode attribute to "On" to view the error page locally.
  2. errorPage attribute of the @Page directive of the Web form to display the error page for the error generated on the particular Web form.
The customsError section in the web.config file specifies the application to redirect to Error404.aspx file if a non-existent file is requested.
  1. <customErrors mode="On" defaultRedirect="Error.aspx">
  2. <error statusCode="404" redirect="Error404.aspx" />
  3. </customErrors>
The @Page directive specifies the error page to be redirected to if an error occurs in the Web page.
  1. <%@ Page language="c#" Codebehind="PageErr.aspx.cs"
  2. AutoEventWireup="false"
  3. Inherits="ExceptionHandling.PageErr"
  4. errorPage="Error.aspx" %>

Sql Server Mirroring Step By Step Using SSMS

In this blog I am going to outline my environment and then walk through the process of setting up Database Mirroring.  This will include the configurations, backups, restores and verification process.  Let's jump in.

My test environment consists of two separate VM’s running VM Workstation with Windows 2008 R2 Datacenter Edition and SQL Server 2008 R2 Enterprise named appropriately Principal and Mirror. The SQL Server and SQL Server Agent Services accounts are running as domain users (DOMAIN\User). Windows Firewall is OFF for the sake of this example.

I created a database on the Principal SQL Server instance and named it TestMirror. The recovery model is set to FULL RECOVERY.

1st step: Issue a full backup of the database.

BACKUP DATABASE TestMirror TO DISK = 'C:\Program Files\Microsoft SQL 
2nd step: Issue a transaction log backup of the database.

BACKUP LOG TestMirror TO DISK = 'C:\Program Files\Microsoft SQL 

Below are the two files in the file system:

3rd step:  Assuming you have the backup folder shared on the Principal Server and you can access it from the Mirror Server, you will need to restore the full backup to the Mirror server with the

RESTORE DATABASE TestMirror FROM DISK = N'\\Principal\Backup\Backup.bak' 
WITH FILE = 1, MOVE N'TestMirror_log' TO 
N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\TestMirror_1.ldf', 
4th step: Restore log backup also with the NORECOVERY option.
RESTORE LOG TestMirror FROM DISK = N'\\Principal\Backup\Backup.trn' 

Now it’s time to dig down and configure Database Mirroring. From the Principal server, right click the database and choose "Tasks" | "Mirror" or choose "Properties" | "Mirroring".

Click the "Configure Security" button and click "Next >" if the Configure Database Mirroring Security Wizard intro screen appears. The next screen should be the Include Witness Server screen:

This is where you would configure a witness server for your mirroring, but since we’re just configuring a basic mirror we will skip this part. However, if you are configuring mirroring in an Enterprise environment it is recommended you configure a witness server because without one you will not have synchronous automatic failover option
Select "No", then click "Next >" to continue the process.
The next screen will give you options to configure the Principal Server Instance:

Here we will be creating our endpoint, which is a SQL Server object that allows SQL Server to communicate over the network. We will name it Mirroring with a Listener Port of 5022.

Click the "Next >" button to continue.
The next screen will give you options to configure the Mirror Server Instance:

 To connect to the Mirror server instance we will need to click the "Connect…" button then select the mirror server and provide the correct credentials:

Once connected, we also notice our endpoint name is Mirroring and we are listening on port 5022.

Click "Next >" and you’ll see the Service Accounts screen.

When using Windows Authentication, if the server instances use different accounts, specify the service accounts for SQL Server. These service accounts must all be domain accounts (in the same or trusted domains).
If all the server instances use the same domain account or use certificate-based authentication, leave the fields blank.

Since my service accounts are using the same domain account, I’ll leave this blank.
Click "Finish" and you’ll see a Complete the Wizard screen that summarizes what we just configured. Click "Finish" one more time.

If you see the big green check mark that means Database Mirroring has been configured correctly. However, just because it is configured correctly doesn’t mean that database mirroring is going to start...

Next screen that pops up should be the Start/Do Not Start Mirroring screen:

We’re going to click Do Not Start Mirroring just so we can look at the Operating Modes we can use:
Since we didn’t specify a witness server we will not get the High Safety with automatic failover option, but we still get the High Performance and High Safety without automatic failover options.

For this example, we’ll stick with synchronous high safety without automatic failover so changes on both servers will be synchronized.

Next, click "Start Mirroring" as shown below.
If everything turned out right, Database Mirroring has been started successfully and we are fully synchronized.

Mirror15 Mirror16
If Database mirroring did not start successfully or you received an error here are a few scripts to troubleshoot the situation:

Both servers should be listening on the same port. To verify this, run the following command:

SELECT type_desc, port 
FROM sys.tcp_endpoints;
We are listening on port 5022. This should be the same on the Principal and Mirror servers:
Database mirroring should be started on both servers. To verify this, run the following command:

SELECT state_desc
FROM sys.database_mirroring_endpoints;
The state_desc column on both the Principal and Mirror server should be started:

To start an Endpoint, run the following:

ALTER ENDPOINT <Endpoint Name>
AS TCP (LISTENER_PORT = <port number>)
FOR database_mirroring (ROLE = ALL);
ROLES should be the same on both the Principal and Mirror Server, to verify this run:

SELECT role 
FROM sys.database_mirroring_endpoints;

To verify the login from the other server has CONNECT permissions run the following:

CONVERT(nvarchar(38), suser_name(SP.grantor_principal_id))
FROM sys.server_permissions  SP , sys.endpoints EP
WHERE SP.major_id  = EP.endpoint_id
ORDER BY  Permission,grantor, grantee;

You can see here from the State and Permissions column that the user has been Granted Connect permissions.