About the author

Vijay Kodali
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2024

Detecting crawlers,bots,spiders in Asp.Net

Here is a way of detecting search engine (Google, live…) crawlers,spiders etc..

[code:c#]
            System.Web.HttpBrowserCapabilities clientBrowserCaps = Request.Browser;
            if (((System.Web.Configuration.HttpCapabilitiesBase)clientBrowserCaps).Crawler)
            {
                Response.Write ( "Browser is a search engine.");
            }
            else
            {
               Response.Write ("Browser is not a search engine.");
            } 

//Here is another approach..

            if (Request.ServerVariables["HTTP_USER_AGENT"].Contains("Googlebot"))
            {
                //log Google bot visit
            }
            else if (Request.ServerVariables["HTTP_USER_AGENT"].Contains("msnbot"))
            {
                //log MSN bot visit
            }
            else if (Request.ServerVariables["HTTP_USER_AGENT"].Contains("Yahoo"))
            {
                //log yahoo bot visit
            }
            else
            {
                //similarly you can check for other search engines
            }

[/code]


Posted by vijay on Tuesday, July 15, 2008 11:51 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Removing empty spaces and HTML tags from TextBox text on client side

Here is a small code to remove spaces from textbox's text in onblur event.

 

<asp:TextBox ID="TextBox2" runat="server" onblur="javascript:value=value.replace(/\s/g,'');"></asp:TextBox>

 

To remove HTML tags..

<asp:textbox id="TextBox2" runat="server" onblur="this.value = this.value.replace(/<\/?[^>]+>/gi, '');">
</asp:textbox>

 

Please let me know, if you have any issues.


Tags:
Posted by vijay on Thursday, June 12, 2008 1:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Change back ground color of Asp.net Textbox on validation failure

Here is a way of changing back ground color for Textbox on validation failure. The key here is using Page_ClientValidate function in javascript.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a value"
    ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="btnClick();"
    OnClick="Button1_Click1" />

<script type="text/javascript"> 

    function btnClick() 
    { 
        if (!Page_ClientValidate()) 
        { 
            document.getElementById("TextBox1").style.backgroundColor="red"; 
        } 
    } 

    function ClearBackGround() 
    { 
        document.getElementById("TextBox1").style.backgroundColor=""; 
    } 

</script>
In Code behind

TextBox1.Attributes.Add("onkeypress", "ClearBackGround()");


Tags:
Categories: ASP.NET | JavaScript
Posted by vijay on Thursday, June 5, 2008 9:08 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Disable Browser Back Button in ASP.NET

The browser back button cannot be disabled as the browser security will not allow this. If you want user to stay on the same page, even if user presses back button, try this java script..

<script language="JavaScript">
javascript:window.history.forward(1);
</script>

What if the JavaScript is disabled by the client, then this code doesn't work. And also it works great in IE, but not in other browsers. So I do not highly recommend using this.

 

Here is another solution for back button problem..

Add this code to Page_load

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now); 

 

The above code will disable page cache. Since the page is not being cached on the browser, the page will be reloaded when the user hits the back button.


Posted by vijay on Thursday, April 24, 2008 9:38 PM
Permalink | Comments (7) | Post RSSRSS comment feed

Detecting Session Timeout and Redirect to Login Page in ASP.NET

HTTP(web page) is stateless, so we cannot know whether the Session has really expired without sending a page request back to the server. If you want to redirect the page immediately(with out any user action) after session expires consider this approach.

 

Response.AppendHeader("Refresh",Convert.ToString((Session.Timeout * 60)+ 10)+";URL=Login.aspx");

 

Add this line of code to page_Load.


Tags:
Categories: ASP.NET | ASP.Net 3.5
Posted by vijay on Friday, April 11, 2008 6:35 PM
Permalink | Comments (2) | Post RSSRSS comment feed

Detecting Asp.Net page close event

Sometimes we have to capture page close event or navigation event to alert users. For example, Alerting user for navigating away from input page without saving it. Check this java script code..

window.onbeforeunload= function(){
if((window.event.clientX<0) || (window.event.clientY<0))
    {
      event.returnValue = "Are you sure you want to navigate away from this page? You haven't saved this form.";
    }
};

This code works only in Ie6/7. And also keep in mind, we can never catch the browser close event for 100%. For example, what if the user kills the browser process or shut down OS.


Tags:
Posted by vijay on Thursday, March 20, 2008 2:49 PM
Permalink | Comments (0) | Post RSSRSS comment feed

cursor position after postback

To maintain cursor position on every page, set following code in web.config file

<system.web>             
        <pages maintainScrollPositionOnPostBack="true"></pages>
</system.web> 

Categories: ASP.NET | ASP.Net 3.5
Posted by vijay on Thursday, January 10, 2008 12:09 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Add, Delete Items in DropDownList, ListBox using Javascript

I have seen lots of questions in Asp.Net forums for adding/deleting items in drop down list or list box using JavaScript. Here is the code...

<asp:DropDownList ID="DropDownList1" runat="server" Width="182px"> 
<asp:ListItem value="1" Text ="Approve"></asp:ListItem> 
<asp:ListItem value="2" Text ="Accept"></asp:ListItem> 
<asp:ListItem value="3" Text ="Test1"></asp:ListItem> 
<asp:ListItem value="4" Text ="Test2"></asp:ListItem> 
</asp:DropDownList> 

<input type="button" value="Remove selected item" onclick="JavaScript: DeleteItem();" /> 
<input type="text" id="ddlText" name="ddlText" /> 
<input type="text" id="ddlValue" name="ddlValue" /> 
<input type="button" value="Add item" onclick="JavaScript: AddItem();" /> 
<input type="hidden" id="ddlElements" name="ddlElements" runat="server" /> 
<asp:Button ID="Button1" runat="server" Text="Button" />
    <script type="text/javascript"> 
    function DeleteItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var optionsList = ''; 

        if ( dropDownListRef.value.length > 0 ) 
        { 
            var itemIndex = dropDownListRef.selectedIndex;
       if ( itemIndex >= 0 ) 
            dropDownListRef.remove(itemIndex); 
        } 
        else 
        { 
            alert('Please select an item'); 
            dropDownListRef.focus(); 
            dropDownListRef.select(); 
        } 
          

        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 
        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
     
        if ( optionsList.length > 0 )
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
        document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
    } 


    function AddItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var ddlTextRef = document.getElementById('ddlText'); 
        var ddlValueRef = document.getElementById('ddlValue'); 
        var optionsList = ''; 

        if ( ddlTextRef.value !="" && ddlValueRef.value!="" ) 
        { 
            var option1 = document.createElement("option"); 
            option1.text= ddlValueRef.value; 
            option1.value= ddlTextRef.value ; 
            dropDownListRef.options.add(option1); 
        } 
        else 
            alert('Please enter values'); 
          
        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 

        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
          
        if ( optionsList.length > 0 )
        
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
            document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
       
    } 

</script>

In Code behind Page_Load, add following code..

if (IsPostBack)
{
    DropDownList1.Items.Clear();
    string[] DropDownListArray = ddlElements.Value.Trim().Split(';'); 
    
    for (int i = 0; i < DropDownListArray.Length; i = i + 2)
    {
        string itemText = DropDownListArray[i];
        string itemValue = DropDownListArray[i + 1]; 
        DropDownList1.Items.Add(new ListItem(itemText, itemValue));
    }

}

string optionsList = string.Empty; 
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
   string optionText = DropDownList1.Items[i].Text;
   string optionValue = DropDownList1.Items[i].Value;
          
    if (optionsList.Length > 0) 
      
    optionsList += ";";
    optionsList += optionText;
    optionsList += ';';
    optionsList += optionValue;
}

ddlElements.Value = optionsList; 

Update:  Client-side changes to a DropDownList/ListBox are not persisted server-side, so any changes made will be lost if a PostBack occurs. Added server-side persistence to code. (Thanks to tip form NC01)

 


Tags:
Posted by vijay on Friday, December 14, 2007 9:40 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Session timeout error in Asp.Net

1.) We were facing timeout issue on one of our servers. Web.config settings had no effect on the time out.

2.) I have set the session to last 24 hours with this statement in my web.config:

		
	
		<sessionState mode="InProc" timeout="720"/>	
	

     But the session still ends after 20 min of inactivity. What am I missing here?

I saw similar type of questions frequently in Asp.Net forums. Here is a post to help those

What is Session State?

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. In order to preserve server memory, ASP.NET implements a rolling timeout mechanism which discards the session information for a user if no request is seen within the timeout period (default 20 minutes which is reset with each request).

You would also have to setup session timeout in IIS in addition to webconfig settings.

In IIS6 change the session timeout setting by going to:
'Configuration' Button -> 'Options' Tab -> Tick Enable Session state, increase value from default 20 mins to desired value

In IIS7 change the session timeout setting by going to:

Features View pane –> Application Development – >Sessions state

IIS 7-1 

IIS 7-2

Don’t see Session state icon in IIS 7? Check this blog post

http://blogs.msdn.com/webdevtools/archive/2006/09/18/761206.aspx

Here are some other reasons for Session loss..

1.) IIS worker process restart or Application Pool recycle.(Check the System logs)

2.) Application Domain restart due to Antivirus scans or changes in Config files.

 

Please leave a comment.


Posted by vijay on Sunday, December 2, 2007 8:37 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Multiline Asp.Net textbox maxlength

MaxLength property of a TextBox control does not work when the TextMode property is set to Multiline. Here is small work around using regualr expression validator..

<asp:TextBox ID="txtComment" runat="server" Width="466px" TextMode ="MultiLine" ></asp:TextBox> 
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtComment" 
ErrorMessage="Not more than 50 charcters" Display="Static" ValidationExpression='^[\s\S]{0,50}$'> 
</asp:RegularExpressionValidator> 

Tags:
Categories: ASP.NET
Posted by vijay on Wednesday, November 21, 2007 3:02 PM
Permalink | Comments (1) | Post RSSRSS comment feed