Pages

Tuesday, December 8, 2009

Application Level Error Handling in .NET

There were many chances for the occurrence of error in a .NET web application. We can easily fetch those errors and handle the users in a friendly way with the Global.asax file.

The event Application_Error in the Global.asax file deals with this. You can add this Global.asax file in the root of your web application. Inside that place the following code.

void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/CustomErrors/ErrorHandlingPage.aspx?error=" + Server.GetLastError().Message);
}

This code will fetch the last error occurred in the application and redirects to the ErrorHandlingPage.aspx. Here you can get the error message from the query string 'error'. This is how it works.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String ErrorMsg;
ErrorMsg = Request.QueryString["error"].ToString();
LitError.Text = "Sorry for the inconvenience caused. We regret the situation. Please try after some time. The following exception occured - " + ErrorMsg;
//The below line is for publishing the error to the Exception Log - Specific to the application
ExceptionManager.Publish(ErrorMsg);
}
}

Its upto you to decide, whether to show the message to the user or make in entry in the exception log and notify user with custom error message. Thats it.
Happy coding. Have a good day.

Monday, October 19, 2009

AJAX implementation using POST method in .NET

Here is where the real Ajax is implementation happens. In fact the .Net framework itself supports the partial page posting using Update Panel and etc. But what actually happens here is, the whole contents of the page goes to the server and comes back. Which is again a similar to a page postback. The only difference is the page events doesn't gets loaded again since its not a post back, but all the contents of the page goes to the server and then returns back.

The real implementation of the AJAX happens only with the JavaScript functions. Here you can really send the partial contents to the server and get back the desired results. There were two ways for the AJAX form posting.
1. GET method and
2. POST method.

Most people tend to go for the GET method since its easier to implement.(Particularly beginners). As you grow you have to be able to identify the instance where you are going to use(GET or POST method). In a simple way,

GET - should be used when a minimum amount of data is going to be passed to the server and collect all the information in a single AJAX call.

POST - when the request is going to be updated frequently and also the server data is going to be changed with the AJAX call then you have to go for POST. Also POST is secured compared to GET method since it doesn't expose the parameters(Query String values).

Here is the example where the POST implementation for simple Login.
EG:

Java script Function


function ajaxPOSTFunction(email,password)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if (xmlhttp.status == 200)
{
if(xmlhttp.responseText.match("success"))
{
window.location = '<%= ResolveClientUrl("../profile.aspx") %>';
}
else
{
document.getElementById("validateTips").innerHTML = xmlhttp.responseText;
}
}
}
}

//GET METHOD IMPLEMENTATION - Same implementation using GET - commented
//xmlhttp.open("GET","login.aspx?email=" + email + "&password=" + password,true);
//xmlhttp.send(null);


//POST METHOD IMPLEMENTATION
var params = "email="+email+"&password="+password;
xmlhttp.open("POST",'<%= ResolveClientUrl("../login.aspx") %>',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}

And here is the code for the login.aspx page - PageLoad() and Private method

Login.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim email As String = Request.Form("email")
Dim password As String = Request.Form("password")
AuthenticateUser(email, password)
Catch ex As Exception
Response.Write(ex.ToString())
End Try

End Sub

Public Sub AuthenticateUser(ByVal userName As String, ByVal password As String)
Dim ErrorBuilder As New StringBuilder
Dim responseStatus As Integer
Dim responseText As String = String.Empty

responseStatus = Me.Controller.AuthenticateUser(userName, password)
If responseStatus = Constants.ServiceResponseStatus.Success Then
responseText = "success"
End If

Select Case responseStatus

Case Constants.ServiceResponseStatus.Success

Response.Write(responseText)
Response.End()

Case Constants.ServiceResponseStatus.Failure
Response.Write("failure")
Response.End()

Case Constants.ServiceResponseStatus.Exception
Response.Write("There has been an internal error. Please try to login again!")
Response.End()

Case Else
Response.Write("The username or the password you provided was not a valid. Please login with valid username and password.")
Response.End()

End Select

End Sub

Wednesday, October 14, 2009

Printer Friendly Button in JS

I was so pleased with Javascript. In an printer friendly version page if you wanna a Print button which will direct you for printing, then this is the simplest way.

Here we go.

EG: In the anchor tag just call the javascript function window.print().

javascript:window.print();

Click on the Print this page link to check out.

Print this Page

Really small piece of code right..

Friday, September 25, 2009

Text Formatting made Easy in ASP.NET

In one of my project there was an requirement to display the Phone Numbers formatted according to US Standards(eg: 123-456-7890).

I initially thought I have to insert the '-' symbol at the index values. But my goodness, this was made so easy in .Net String Formatting.

For Example:

Dim phone as Integer = 123456890

String.Format("{0:###-###-####}", phone)


This will be displayed as 123-456-7890

Be a smart coder. Let me know if its useful. Happy Coding.

Wednesday, September 2, 2009

Reseed Identity Column in a Table

Today in our web application we have to make a major release to production. Everything went fine but we have lot of test entries in the production. Our identity column of the User table increased from 1342 to 1456 because of the test entries. Myself and a friend of mine read an article for resetting the Identity Column. So after deleting the entries this is what you have to do.


Resetting Current Identity Value to New Value

use DBNAME

go
dbcc checkident(TABLENAME, reseed,seed value)

For Eg:

dbcc checkident(dbo.[User],reseed,1342)

which served my purpose.


To Get Current Identity Value

Also this seems to be useful. This gives the current identity value of the table.

use DBNAME

go
dbcc checkident(TABLENAME, noreseed)

For Eg:

dbcc checkident(dbo.[User],noreseed)

Please let me know your thoughts. Have a good day.

Saturday, August 29, 2009

Basic SQL System Stored Procedures to be known by every Developer

There are large number of System Stored Procedures. Here are few stored procedures that should be known by every developer who work with Databases. And these stored procedures will be very handy at times(Particularly for me.My favorites :) ).


sp_Help:

Gives the structure of the table.

Syntax: sp_Help

Eg: sp_Help 'dbo.tblProduct'



sp_Helptext:

Gives the definition of the objects like Stored Procedures(both user defined and system defined), Triggers, Functions and etc.

Syntax: sp_Helptext

Eg: sp_Helptext 'dbo.sp_tblProduct_Insert'



sp_Depends:

Gives all the Stored Procedure and View associated with the Table.

Syntax: sp_Depends

Eg: sp_Depends 'dbo.tblProduct'



sp_Spaceused:

Gives information on the size database objects.

Syntax: sp_Spaceused

Eg: sp_Spaceused 'dbo.tblProduct'


I can assure you these System Stored Procedures will help you in Development.

Please let me know your thoughts. Have a wonderful time.

Thursday, August 27, 2009

Change Focus for TextBoxes using Javascript

In most of the real time project there will be requirement to change focus of the TextBox from one to another dynamically, instead of clicking the TextBoxes. The ideal example in this case would be Phone Number Text Boxes in the US format(000-000-0000). Consider there were three TextBoxes. It wil be irritating for the end user to click each text box and then type numbers.

So here, on every keyboard press event ("onkeypress") we capture the event and check for the length of the TextBox in the changeFocus() Javascript function. Again the browser compatibility issue raises its head and its handled in its own way. This is so simple to implement. Here is the code snippet.

Javascript Function:

//Change Focus for the Phone TextBox

function changeFocus(textbox1,textbox2)
{
var browserName=navigator.appName;
if (browserName=="Netscape")
{
if(textbox1.value.length >= 2)
{
textbox2.focus();
}
}
else if(browserName=="Microsoft Internet Explorer")
{
if(textbox1.value.length == 3)
{
textbox2.focus();
}
}
else
{
if(textbox1.value.length == 3)
{
textbox2.focus();
}
}
return true;
}

//End of Change Focus for the Phone TextBox


The ASP.NET(Vb) File Code:-

You can add this code in the Load Event of the Page.

Me.TxtCellPhone1.Attributes.Add("onkeypress", String.Format("javascript:return changeFocus({0},{1});", Me.TxtCellPhone1.ClientID, Me.TxtCellPhone2.ClientID))
Me.TxtCellPhone2.Attributes.Add("onkeypress", String.Format("javascript:return changeFocus({0},{1});", Me.TxtCellPhone2.ClientID, Me.TxtCellPhone3.ClientID))

Here no need to add an event for TxtCellPhone3 TextBox.

Let me know your Thoughts. Happy Coding.

Tuesday, August 25, 2009

Diable Browser Back Button

I have gone mad for getting my browser back button disabled in one of my projects. And at last arrived at this solution:

function disableBrowserBackBtn() { window.history.go(1) }
disableBrowserBackBtn();
window.onload = disableBrowserBackBtn();
window.onpageshow = function(evt) { if (evt.persisted) disableBrowserBackBtn() }
window.onunload = function() { void (0); disableBrowserBackBtn(); }

You have to just add the Script in the pages you want to disable the browser back button.

But this is just bluffing the user, using the the javascript code window.hsitory.go(-1) ->Redirecting to previous page.

For the perfect solution you have to open a new pop-up window with no navigation toolbar.

Please let me know your comments....Have a good day.