RSS

Monthly Archives: August 2011

Special character not Allowed in textbox with javascript


I want to check whether the user has entered any special characters in a text box.

First Method (Function) if you insert special char with string then automatically remove special char.

Second Function which no allow to special char .if you insert then auto remove.

 

 

javascript Function

<script type=”text/javascript”>
<!–
function textBoxOnBlur(elementRef)
{
var checkValue = new String(elementRef.value);
var newValue = ”;

// 1<2,3>4&56789
for (var i=0; i<checkValue.length; i++)
{
var currentChar = checkValue.charAt(i);

if ( (currentChar != ‘<‘) && (currentChar != ‘,’) && (currentChar != ‘>’) && (currentChar != ‘&’) )
newValue += currentChar;
}

elementRef.value = newValue;
}

function valid(f) {
!(/^[A-zÑñ0-9]*$/i).test(f.value)?f.value = f.value.replace(/[^A-zÑñ0-9]/ig,”):null;
}
// –>
</script>

html Code

<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”  onblur=”textBoxOnBlur(this);”></asp:TextBox>
<input name=”mytext” type=”text” onkeyup=”valid(this)” onblur=”valid(this)”>

</div>
</form>

Advertisements
 
1 Comment

Posted by on August 19, 2011 in Java Script

 

Tags:

Error Handling in .Net with Example


What is Exception?
An exception is unexpected error or problem.

What is Exception Handling?
Method to handle error and solution to recover from it, so that program works smoothly.

What is try Block?

  • try Block consist of code that might generate error.
  • try Block must be associated with one or more catch block or by finally block.
  • try Block need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it.

Example of try Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
}

Format2
try
{
//Code that might generate error
}
catch(ExceptionA errror)
{
}
catch(ExceptionB error)
{
}

Format3
try
{
//Code that might generate error
}
finally
{
}

What is catch Block?

  • catch Block is used to recover from error generated in try Block.
  • In case of multiple catch Block, only the first matching catch Block is executed.
  • when you write multiple catch block you need to arrange them from specific exception type to more generic type.
  • When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page.

Example of catch Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handle errors occurred in try block
}

Format2
try
{
//Code that might generate error
}
catch(DivideByZeroException errror)
{
//Code that handle errors occurred in try block
//Note: It is most specific error we are trying to catch
}
catch(Exception errror)
{
//Code that handle errors occurred in try block
//Note: It is not specific error in hierarchy
}
catch
{
//Code that handle errors occurred in try block
//Note: It is least specific error in hierarchy
}

Explain finally Block?

  • finally Block contains the code that always executes, whether or not any exception occurs.
  • When to use finally Block? – You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.
  • Only One finally block is associated with try block.
  • finally block must appear after all the catch block.
  • If there is a transfer control statement such as goto, break or continue in either try or catch block the transfer happens only after the code in the finally block is executed.
  • If you use transfer control statement in finally block, you will receive compile time error.

Example of finally Block

Format1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.
}
finally
{
//Code to dispose all allocated resources.
}

Format2
try
{
//Code that might generate error
}
finally
{
//Code to dispose all allocated resources.
}

Explain throw statement?

  • A throw statement is used to generate exception explicitly.
  • Avoid using throw statement as it degrades the speed.
  • throw statement is generally used in recording error in event log or sending an email notification about the error.

Example of throw statement
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.

throw; //Rethrow of exception to Add exception details in event log or sending email.
}

Explain using statement?

  • using statement is used similar to finally block i.e. to dispose the object.
  • using statement declares that you are using a disposable object for a short period of time. As soon as the using block ends, the CLR release the corresponding object immediately by calling its dispose() method.

Example of using statement in C#

//Write code to allocate some resource
//List the allocated resource in a comma-seperated list inside
//the parantheses of the using block

using(…)
{
//use the allocated resource.
}

//here dispose method is called for all the object referenced without writing any additional code.
Is it a best practice to handle every error?
No, it is not best practice to handle every error. It degrades the performance.
You should use Error Handling in any of following situation otherwise try to avoid it.

  • If you can able to recover error in the catch block
  • To write clean-up code that must execute even if an exception occur
  • To record the exception in event log or sending email.

 

Difference between catch(Exception ex) and catch
try
{
}
catch(Exception ex)
{
//Catches all cls-compliant exceptions
}
catch
{
//Catches all other exception including the non-cls compliant exceptions.
}

 

Managing Unhandled Exception You can manage unhandled exception with custom error pages in asp.net. You should configure the <customErrors> element in web.config file. It has two attributes:

  • Mode Attribute: It specifies how custom error page should be displayed. It contains 3 values.
    • On – Displays custom error pages at both the local and remote client.
    • Off – Disables custom error pages at both the local and remote client.
    • RemoteOnly – Displays custom error pages only at the remote client, for local machine it displays default asp.net error page. This is default setting in web.config file.
  • defaultRedirect: It is an optional attribute to specify the custom error page to be displayed when an error occurs.
  • You can display custom error page based on http error statusCode using error element inside the customeError element, in case the no specific statusCode match it will redirect to defaultRedirect page.
  • <customErrors mode=”RemoteOnly” defaultRedirect=”~/DefaultErrorPage.htm”>
    <error statusCode=”403″ redirect=”NoAccess.htm” />
    <error statusCode=”404″ redirect=”FileNotFound.htm” />
    </customErrors>

Example of Unhandled Exception
I have created a sample website which can generate unhandled exception, divide by zero.

 

Client Side

 

<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:TextBox ID=”TextBox2″ runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” Text=”Button” onclick=”Button1_Click” />
<asp:label ID=”Label1″ runat=”server” text=”Label”></asp:label>
</div>
<asp:HyperLink ID=”HyperLink1″ runat=”server” NavigateUrl=”~/HttpError1.aspx”>HyperLink</asp:HyperLink>
</form>

 

Server side(CodeBehind)

 

protected void Button1_Click(object sender, EventArgs e)
{
try
{
Int32 a = Convert.ToInt32(TextBox1.Text);
Int32 b = Convert.ToInt32(TextBox2.Text);
Label1.Text = Convert.ToString(a / b);
}
catch (Exception ex) {
throw ex;

}

}

 

To suppress error with CustomError Page you need to define customError element in Web.Config file.

Example:
<customErrors mode=”On” defaultRedirect=”~/DefaultErrorPage.htm”>
</customErrors>

This setting web.config will display default error page whenever web application generates unhandled exception

Now, after adding the above code in web.config file and creating a sample DefaultErrorPage.htm in root directory it will redirect to DefaultErrorPage.htm whenever unhandled exception occurs.

Result

 

Give Error message Divided By Zero

Similarly you can display error message for different http status code

<customErrors mode=”On” defaultRedirect=”~/DefaultErrorPage.htm”>
<error statusCode=”403″ redirect=”~/HttpError.aspx?ErrorCode=403″ />
<error statusCode=”404″ redirect=”~/HttpError.aspx?ErrorCode=404″ />
</customErrors>

Here we are using HttpError.aspx page to display all http errors by passing the error code as querystring.

You need to place following code into HttpError.aspx page to make this work

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string sErrorCode = Request.QueryString[“ErrorCode”].ToString();
switch (sErrorCode)
{
case “403”: Label1.Text = “Error: Request Forbidden”;
break;
case “404”: Label1.Text = “Error: Page Not Found”;
break;
}
}
}

So lets click on page which is not present in web application and can generate page not found error.

 

click on HyperLink button and Give Page Not Found Error

Page.Error() Event
Let display error message in above divide by error instead of display custom error page.

Add the Page_Error() Event

protected void Page_Error(object sender, EventArgs e)
{
Response.Write(“Error: ” + Server.GetLastError().Message + ““);
Server.ClearError();
}

Server.GetLastError() method is used to display last error, while Server.ClearError() will clear the last exception and does not fire the subsequent error events. For this reason, you will notice that custom error page is not displayed even though there is unhandled error, and a default error message is displayed.Application.Error() Event
Application.Error

Event is used to handle unhandled exception of entire application. This event lies in Global.asax file. You can use this event to send email for error or generate a text file or recording error information in database, etc.

 void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception err = (Exception)Server.GetLastError().InnerException;

//Create a text file containing error details
string strFileName = “Err_dt_” + DateTime.Now.Month + “_” + DateTime.Now.Day
+ “_” + DateTime.Now.Year + “_Time_” + DateTime.Now.Hour + “_” +
DateTime.Now.Minute + “_” + DateTime.Now.Second + “_”
+ DateTime.Now.Millisecond + “.txt”;

strFileName = Server.MapPath(“~”) + “\\MyError\\” + strFileName;
System.IO.FileStream fsOut = System.IO.File.Create(strFileName);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fsOut);

//Log the error details
string errorText = “Error Message: ” + err.Message + sw.NewLine;
errorText = errorText + “Stack Trace: ” + err.StackTrace + sw.NewLine;
sw.WriteLine(errorText);
sw.Flush();
sw.Close();
fsOut.Close();

}

On running the program and generating exception will create error file in MyError directory and will send email stating error to web master, And it will display custom error page to user.

 
1 Comment

Posted by on August 12, 2011 in ASP Dot Net C#

 

Tags: , ,

Generate Random Password


Enhancing the same password generation logic so that it would be useful for generating random password using C# code.

Client Side (RandPwd.aspx)

<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”rndpwd” runat=”server” Text=”Generate Pwd” onclick=”rndpwd_Click” />
<br />
<asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>
</div>
</form>

Server Side

public static string GetRandomPassword(int length)
    {
        char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
        string password = string.Empty;
        Random random = new Random();

        for (int i = 0; i < length; i++)
        {
            int x = random.Next(1,chars.Length);
            //Don't Allow Repetation of Characters
            if (!password.Contains(chars.GetValue(x).ToString()))
                password += chars.GetValue(x);
            else
                i--;
        }
        return password;
    }

Display Result of Pwd

protected void rndpwd_Click(object sender, EventArgs e)
    {
        Label1.Text=GetRandomPassword(Convert.ToInt32(TextBox1.Text));
    }

Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.
 
Leave a comment

Posted by on August 12, 2011 in ASP Dot Net C#

 

Tags:

Disable Button before Page PostBack in ASP.Net


In this article I will explain how to disable ASP.Net button control before Page PostBack is done or the form is submitted so that user can’t click the button again.

And Also change the text of  button

To start with I have created a simple ASP.Net Web Page with  ASP.Net Buttons on it.

 

<form id=”form1″ runat=”server”>

  <asp:Button ID=”Button1″ runat=”server” Text=”Submit” OnClick=”Button1_Clicked” />

<asp:Label id=”lblmessage” Text=”Page PostBack after Processing….” runat=”server” Visible=”false” />
    </form>

 

Now here’s the short JavaScript snippet that will disable the button as soon as it is clicked so that when PostBack occurs the button cannot be clicked again.

 

<script type = “text/javascript”>
function DisableButton() {
    document.getElementById(“<%=Button1.ClientID %>”).disabled = true;
     document.getElementById(“<%=Button1.ClientID %>”).value=”Processing….”;
}
window.onbeforeunload = DisableButton;
</script>

 

Write this code on Code-Behind

 

 protected void Button1_Clicked(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);

        lblmessage.Visible = true;
    }

 

OutPut

 

 
2 Comments

Posted by on August 8, 2011 in Java Script

 

Tags: , ,