>Cookieless Session State Asp.net


>

Cookieless Session State Asp.net

ASP.NET Session State by default uses a cookie to store session ID. Session ID is a unique string, used to recognize individual visitor between visits. But, if client’s web browser doesn’t support cookies or visitor has disabled cookies in web browser’s settings, ASP.NET can’t store session id on client’s machine. In this case, new session will be created for every request. This behavior is useless because we can’t remember information for certain visitor between two requests. We can say that, by default, sessions can’t work if browser doesn’t support cookies.

ASP.NET sessions without cookies (cookieless session)

ASP.NET supports sessions without cookies, known as cookieless sessions. As an alternative, ASP.NET can embed session id inside of page URL. On this way, all page links will contain session id string. When visitor clicks on some of these links, ASP.NET will read session id from page URL, so we don’t need cookies support to have functional sessions.

To enable cookieless sessions, add cookieless="true", or cookieless="UseUri" (both options have the same meaning) inside sessionState tag in web.config file, like this:

<sessionState cookieless="true" />

SessionState element in web.config file is located inside <configuration>, <system.web> elements. Default behavior for sessions with cookies could be set with cookieless="false". Since it is already specified in machine.config file and inherited to all ASP.NET applications on server, you don’t need any configuration change if you use cookie sessions.

As a result of cookieless="true", session id will be embedded in all page URLs. The drawback is that you’ll end up with ugly URLs, which are not so good for SEO (search engine optimization) and visitor definitely will not remember it. Here is an example URL of website which uses ASP.NET cookieless sessions:

http://mappoint.msn.com/(22b5c4zyybphaw2mt3hjni2n)/Home.aspx

Bolded part represents session id, which is used to recognize a visitor. Possible problem is that URL will be different for every visitor and every visit, because they will have different session identities. If user just copy URL and paste it somewhere while recommending your website, he or she will send its session id too. This could be potential security risk if session is not expired yet. Also, search engines will consider any of these links as separate page. This will divide page ranking and decrease position of your page in search engine results.

Cookieless session and absolute URLs problem

There is a problem with absolute URLs if Cookieless session is used (e.g. URLs which starts with http://, https:// etc.), and with URLs which starts with slash character "/". So, you can’t use links like /products/Product1.aspx anymore. If you place absolute link on your page, ASP.NET will not embed session id in it. If visitor clicks on link without current session id, he or she will get new session with new session id. Previous session and its data will be lost. With every next click on absolute links, visitor will get new session each time. On this way session becomes useless, because it cant remember user’s data between two requests. So, easiest solution is to simply forget links with absolute URLs on cookieless website.

Other option is to embed session id into absolute URLs by using Response.ApplyAppPathModifier method. This could be useful, for example if we read and display a list of absolute URLs from database, or perform redirection from http:// to https:// etc. Here is a simple example of modification of absolute URL. Resulting URL will contain embedded current session id:

<a id="Hyperlink1" runat="server" href='<% =Response.ApplyAppPathModifier("http://mysite.com/Some-Absolute-Link.aspx&quot;); %>’ >Absolute link with cookieless session example</a>

In the other hand, absolute links are pretty useful for static files like images, .js, .css, .zip files etc.

Cookieless session and links to images, JavaScript files, CSS files etc.

When cookieless="true" is used, every relative link will be rewritten to embed session id. That includes links to files like images, JavaScript files, CSS files, PDF files, ZIP files for download etc.

In most cases, you don’t need session id embedded inside of these links. Embedded session id inside of links to images and other similar files could cause cache problems.

For every new visit, visitor will get different session id. Thus, same image will always have different URL. Different URL means different image for web browser. If you check "Temporary Internet Files" in Internet Explorer or some other browser, notice that same image is saved many times. Actually, it is saved again each time you visit cookieless website. This could be a problem, especially on high traffic websites. In this case, cookieless session could increase bandwidth costs and slow down page loading, since same files must be downloaded multiple times and stored separately.

As a simple solution, you can use absolute links for images, JavaScript, CSS, PDF and similar files and avoid session id issue on this way.

ASP.NET cookieless options

ASP.NET offers six different options for cookieless attribute.

UseCookies – This is default option, set in machine.config file. ASP.NET website will use cookies to store session id, even if client doesn’t support them. In case that client refuse to save cookie, session data will be lost and new session is created for each request. Thus, clients without cookie support can’t use web application.

false – has same meaning as UseCookies.

UseUri – Website will embed session id inside of all relative URLs. ASP.NET Session State will never use cookies, even if client browser supports them. Sessions will work on each client, but could be less secure than session with cookie.

true – same as UseUri.

UseDeviceProfile – ASP.NET will check client if it’s capable to support cookies. If client can support cookies, cookie will be used to store session id. Notice that this method just checks browser’s features, but it doesn’t consider an option that user is manually disabled cookies in browser. If web browser application supports cookies but user is disabled them, session will not work.

AutoDetect – ASP.NET will automatically detect if client supports cookies or not. If client supports cookies, website will use a cookie as storage for session id. If client doesn’t support cookies, ASP.NET will embed session id in page URL. This looks as good compromise, although could cause problems with search engines.

Cookieless sessions and RegenerateExpiredSessionId parameter

To enable cookieless session, it is enough to set appropriate value for cookieless parameter. But, sessionState element contains RegenerateExpiredSessionId parameter which is important for security reasons. RegenerateExpiredSessionId could have two values:

True – Expired session ids can’t be used again. If visitor comes to website using old session id, it will be replaced with new session id

False – If visitor uses old session id to visit website (e.g. through a bookmark, search engines, social networks etc.), website will create new session collection but session id will stay same.

For security reasons, especially with cookieless sessions, is better to always use RegenerateExpiredSessionId="True". On this way expired session id will not be used for new session, to avoid that different visitors have same session id.

SEO (Search Engine Optimization) and cookieless sessions

Search engines like Google could provide a lot of visits to website. Everything begins when Googlebot, or some others’ search bot application, make requests to website to load its content and save it to their database for further analyze. Saved data are then provided for search on search engine, and possibly listed in search results.

Important issue when working with cookieless sessions is duplicate content. Let’s suppose that you have one page with unique content. Each time when search bot reads that page, ASP.NET will assign different session id to it. Different session id means different URLs on page. So, instead to see your page as one page with original content, search bot could consider that you have a lot of different pages with same content. That is not good for search engine optimization, because your page will divide its ranking and be shown on the bottom of search results where no one clicks.

The solution for this could be to use cookieless="UseDeviceProfile" and then add new browser profile for each search bot inside <browsers> element in web.config. For example, if user agent string contains word "Googlebot", browser profile will tell ASP.NET that Googlebot supports cookies. On this way, session id will not use cookies when Google bot comes. Of course, we know that Googlebot doesn’t support cookies, so this sounds more like hack than recommended nice looking solution. But, it will work and you can add new browser profile for any problematic search bot. Notice that UseDeviceProfile only looks on browser capabilities, thus on this way you are losing visitors with capable browsers, but who manually disabled cookies.

One more potential SEO problem with cookieless sessions is HTTP 302 redirect. When, search bot makes requests to some domain which uses cookieless sessions, ASP.NET will redirect visitor to other link with session id embedded. During this process, ASP.NET will use HTTP 302 Found message. Code 302 could have two meanings: 303 or 307. "303 See Other" means that correct content is found on different URL. 307 response represents temporary redirect. So, correct status code should be 307, temporary redirect, because in that case main link without session id is considered as the correct one. Unfortunately, bad architecture of ASP.NET cookieless session redirects using vague 302 message which is more often perceived as 303, than as 307. The consequence is that search bots usually save URL with session id embedded and even worse, see different pages each time when crawl through website.

Fortunately, main search engines learned how to deal with session variables, so now the problem is not so big as before. Still, clean URLs with keywords only will always rank better in search results, thus I can say that cookieless sessions generally are not good for SEO.

Security issues and cookieless session

Main security problem when working with sessions is a possibility that malicious user will find out others’ session id. If two users share same session id, they share same session variables too and website is considering them as one visitor. This could be a security risk if session is used for any private or sensitive data, or to allow access to restricted areas of web site. When cookies are used, session id can be protected using SSL and by marking a cookie as secure. But, in case of cookieless session, session id is part of URL and is much more vulnerable.

Attacker could use network monitoring tool to see requested URLs. Because session id is part of URL, if you know requested URL you know session id too. Also, if malicious user get access to recent web server’s logs, it is possible to read recent requested URLs and visit website with still active session.

On more problem is e-mail, social network or instant messenger communication. Pretty innocent question, as "Can you send me link to that page please?" could be huge security risk. Visitor could copy link from address bar and send it to someone through an email, some instant messenger, like AIM, Windows Live Messenger, Skype etc., or through social networks like Facebook. When other person use received link to open website, he or she will share same session as sender, and possibly see private data or have access to restricted area of web site.

Search bots generally don’t accept cookies. That means that bots will get cookieless session and see URLs with embedded session id. If these URLs appear in search results, they will still contain that session id. So, imagine that first visitor comes to your website from Google search. Website will read session id from given URL. Then, after few minutes, second visitor comes using the same link. Now these two, and every next visitor that comes from search engine will share same session id, and same session variables and all of them will be considered as single visitor! This could make sessions useless and also be potential security risk. To solve this problem, always set RegenerateExpiredSessionId="True" when working with cookieless session. When RegenerateExpiredSessionId="True" and some visitor comes through an URL that contains expired session id, ASP.NET will assign new unique session id.

Since session id is so exposed when cookieless sessions are used, to increase security you can check some other information from visitor, like information from Request.Browser properties. Checking of IP address is also an option, but notice that some Internet service providers change IP address during the single visit. In cases like this, often you still can check first two numbers of IP address because they usually stay the same.

Notice that visitors usually disable cookies for security reasons. In case of cookieless sesions, ironically, visitor become much more insecure than if session with cookie is used.

Menu and TreeView control when cookieless session is used

Menu and TreeView controls are standard controls used for site navigation. Keep in mind that these controls will not automatically add session ids. For example, very common scenario is to bind Menu or TreeView control to SiteMapDataSource control. It looks logical that resulting links on page will have session id embedded. But, Menu or TreeView control will display just simple absolute links without ids.

To resolve this, we need to use Response.ApplyAppPathModifier method again. In this case, we’ll use MenuItemDataBound or TreeNodeDataBound events respectively:

[ C# ]

// Cookieless sessions with Menu control
protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
{
// Embeds session id
   e.Item.NavigateUrl = Response.ApplyAppPathModifier(e.Item.NavigateUrl);
}
// Cookieless sessions with TreeView control
protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
// Embeds session id
   e.Node.NavigateUrl = Response.ApplyAppPathModifier(e.Node.NavigateUrl);
}

[ VB.NET ]

‘ Cookieless sessions with Menu control
Protected Sub Menu1_MenuItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemDataBound
‘ Embeds session id
   e.Item.NavigateUrl = Response.ApplyAppPathModifier(e.Item.NavigateUrl)
End Sub
‘ Cookieless sessions with TreeView control
Protected Sub TreeView1_TreeNodeDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeView1.TreeNodeDataBound
‘ Embeds session id
   e.Node.NavigateUrl = Response.ApplyAppPathModifier(e.Node.NavigateUrl)
End Sub

Now, all links in Menu or TreeView controls will have session ids embedded.

Session.IsCookieless property

You can check in run time if session is cookieless sessions or not. This is useful if you are creating an application that could be included as module on others’ websites (e.g. forum, user support application etc.). In this case, you can’t change settings in main web.config file, but you can check in code if session requires cookies but visitor is disabled them, and if needed redirect and inform visitor so he or she knows why application doesn’t work. Example of using Session.IsCookieless property could look like this:

[ C# ]

if (Session.IsCookieless)
{
// Web application uses cookieless session
}
else
{
// Web application uses cookies to work with sessions
// If needed, inform visitor that cookies are required
}

[ VB.NET ]

If (Session.IsCookieless) Then
‘ Web application uses cookieless session
Else
‘ Web application uses cookies to work with sessions
‘ If needed, inform visitor that cookies are required
End If

Conclusion

HTTP is stateless protocol, which means that it doesn’t provide a way to save information of same visitor between two requests. ASP.NET offers Session State as a method to resolve this problem. To find out more about other possible methods, check ASP.NET Session State Alternatives tutorial. In general, to save visitor’s state when using stateless protocol, you can place id inside of page’s HTML or as part of URL. In HTML, there are two options: <head> or <body> tags. Cookies are part of <head> tag, but this is automatically managed by web browser.

ASP.NET ViewState stores information inside of <body> tag, as hidden field. This works nice, but the problem is that this method can only work with POST, and can’t work if GET method is used.

Third, and last option is to store information inside of page URL, and that is how cookieless session work. Be aware that some mobile devices can’t read format of cookieless URLs with parentheses, and cookieless sessions could cause problems with some URL rewriting modules.

If you have pure HTML pages, there is a problem to share POST data between HTML form and ASP.NET web form. When cookieless ASP.NET form is posted, it contains information about session id too. But, if you make POST on HTML form, it will not contain session id and new session will be created. In that case, data of previous session will be lost. The solution could be to embed session id to link in form’s action attribute. You can do that using Response.ApplyAppPathModifier method like in previous examples.

Limitations

The principal limitation of this feature is the limited amount of data that can be stored in the URL. This feature is not targeted at common browsers such as IE, since these do support cookies and do not require this feature. The browsers that do not support cookies are the ones found on mobile devices (such as phones), and these browsers typically severely limit the size of the URL they support. So, be careful when you use this feature—try to make sure that the cookieless string generated by your application is small.

A second limitation on the size comes on the Windows 2003 platform. A (configurable) setting on the Windows Networking layer requires that each segment of the URL be less than 256 chars in length. Since the entire cookieless string goes into 1 segment, it must be less than 256 chars. (A segment of the URL is the portion of the URL between two forward slashes (‘/’)).

Advertisements
Posted in Uncategorized | 9 Comments

Filtering or Searching in Listbox Item Using JavaScript


Normally you have a requirement that user want to search or filtering record in a list box according to what he write in textbox.So in my pervious posted Search ListBox items using JavaScript.I explained how to search in listbox but there is one restriction when user want to search, it will select only one record and user can not see the other records related to searching criteria.So in this post I explain how to implement this thing if you have that kind or requirement.

First you write JavaScript code on html page.

 
<script type="text/javascript" language="javascript">
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {

ddlText = new Array();ddlValue = new Array();ddl = document.getElementById("<%=ListBox1.ClientID %>");lblMesg = document.getElementById("<%=lblMessage.ClientID%>");for (var i = 0; i < ddl.options.length; i++) {ddlText[ddlText.length] = ddl.options[i].text;ddlValue[ddlValue.length] = ddl.options[i].value;}}window.onload = CacheItems;

function FilterItems(value) {        ddl.options.length = 0;

        for (var i = 0; i < ddlText.length; i++) {

            if (ddlText[i].toLowerCase().indexOf(value) != -1) {

                AddItem(ddlText[i], ddlValue[i]);

            }

        }

        lblMesg.innerHTML = ddl.options.length + " items found.";

        if (ddl.options.length == 0) {

            AddItem("No items found.", "");

        }

    }

    function AddItem(text, value) {

        var opt = document.createElement("option");

        opt.text = text;

        opt.value = value;

        ddl.options.add(opt);

    }</script>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The above three JavaScript methods take care of the Filtering and Searching process. The significance of the these methods is described below
1. CacheItems
This method is called on the window onload event. The job of this method is to populate text and value arrays that will be used to cache the List box items.
2. FilterItems
This method is called when keyup event fires in the Search TextBox. This method searches for the string segment and filters the Listbox items.
3. AddItem
This method as the name suggests adds a new item to the Listbox

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

<body> 

<form id="form1" runat="server"> 

<asp:TextBox ID="TextBox1" runat="server" onkeyup="FilterItems(this.value)"><br /> 

<asp:ListBox ID="ListBox1" runat="server" Height="150px" Width="250px"> 

<asp:ListItem>Vincent</asp:ListItem> 

<asp:ListItem>Jennifer</asp:ListItem> 

<asp:ListItem>Shynne</asp:ListItem> 

<asp:ListItem>Christian</asp:ListItem> 

<asp:ListItem>Helen</asp:ListItem> 

<asp:ListItem>Vladi</asp:ListItem> 

<asp:ListItem>Bee</asp:ListItem> 

<asp:ListItem>Jerome</asp:ListItem> 

<asp:ListItem>Vinz</asp:ListItem> 

<asp:ListItem>Churchill</asp:ListItem> 

<asp:ListItem>Rod</asp:ListItem> 

<asp:ListItem>Mark</asp:ListItem> 

</asp:ListBox> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></form> 

</body> 

</html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The JavaScript function basically searches the ListBox items and find the items based from the value of the TextBox that was entered. If a keyword exist from the list then it will 
automatically select the ListItems in the ListBox, but if the keyword does not exist then it will clear the ListBox selection.While the label will display the status message to the user
Posted in Asp.Net, JavaScript | Tagged , , | 3 Comments

Avoid Multiple Form Submits


>

 
Multiple form submits is a serious issue in web applications because it’ll result in unexpected behavior like multiple entries in database .I have spent some time for the same in Google and I got some solutions for that.
If you are submitting the page only once then you can use,
<form onsubmit="return Submit();">

And the method is like,

 

<script type="text/javascript">
var flag = false;
function Submit() {
if (flag) {
return false;
}
else {
flag = true;
return true;
}
}
</script>
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

For a single button you can use,

 
btnSubmit.Attributes["onclick"] = "this.disabled=true;" + GetPostBackEventReference(btnSubmit);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

For pages with update panels multiple submit is a serious issue as page is posting asynchronously or partially.In that scenario you can use Sys.WebForms.PageRequestManager for fixing the issue,

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
function BeginRequest(sender, e) {
e.get_postBackElement().disabled = true;
}
</script>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Posted in Tips | Tagged | 1 Comment

Auto-Refreshing ASP.NET Web Pages


>

 

Today I am writing about how you can auto-refresh the page without user click .If you want to refresh the page at specific time of interval like after each 10 seconds you can used any of the following methods.

HTML header refresh tag

 

    The most common and best known way to tag of the following format is placed in the HTML section of the page:

    <meta http-equiv=”refresh” content=” 5; url=http://dotnetfarrukhabbas.blogspot.com/“>

    • where ‘5‘ refers to the number of seconds that will elapse before the page is refreshed;

    • ‘url’ is the new url redirect to. It can be excluded which means the current page will be reloaded.

      This construct is useful if you have one or two pages which have to auto-refresh, and works for any HTML content type forms.

      You can used this meta tag in master page as well as any specific page.

       

      Using JavaScript

      You can also used the JavaScript for auto refreshing the page instead of meta tag.

      <script language="javascript" type="text/javascript"> 

      setTimeout("StratRefresh()", 30000);
      function StratRefresh() {
      window.location.reload();
      }
      </script>

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

       

      Refresh Page from Server Side

      ASP.NET provides the AppendHeader method to the Response object. Typically the page refresh can be set as follows in an ASP.NET webform (in C#):

      protected void Page_Load(object sender, EventArgs e)
      {
      if (!Page.IsPostBack)
      {
      //page will be refereshed at a interval of 10 sec
      Response.AddHeader("Refresh", "10");
      }
      }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      This construct is useful as it can be placed in a base webform OnLoad() or Page_Load() response method. All derived webforms will then have the same page refresh setting when they are loaded.

      Note 

      when the page gets refresh then it will not persist the view-state of the page.

      Posted in Tips | Tagged | 3 Comments

      call server side method from client side using script manager


      >

       

       

       

      Hello friends.

      I am going to share with you a concept to call server side method from client side using script manager.

      Step 1 : Put ScriptManager on .ASPX page.

      Step 2 : Set EnablePageMethods=”True” in ScriptManager.

      Step 3 : Create one static method in server side that return some value.

      Step 4 : Set WebMethod attribute to above the method.

      Step 5 : Create one javascript  function and call server side method using PageMethods object and set callback method as argument.

      Step 6 : Create callback method where you will be able to retrieve return parameter from server side method.

      See following example code

      ScriptManager on the page.

      <asp:ScriptManager ID="ScriptManager1"  EnablePageMethods="true" runat="server">
      </asp:ScriptManager>

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      My server side static method

      [System.Web.Services.WebMethod]
      public static int Sum(int value1, int value2)
      {
      return value1 + value2;
      }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      My javascript function to call server side method and retrieve result from server side

      <script language="javascript" type="text/javascript">
      pageMethodConcept={
      callServerSideMethod:function(){
      PageMethods.Sum(3,4,pageMethodConcept.callback);

      // I am passing 3 and 4 to get sum and set callback method
      },
      callback:function(result){
      alert(result);
      }
      }
      window.onload=pageMethodConcept.callServerSideMethod;
      </script>

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      Posted in Asp.Net | Tagged , , | 1 Comment

      Edit code when your ASP.NET Development Server is running


      >

       

      Lot of people trying to edit the code when ASP.NET Development Server is running but they can’t. In order to edit code you have to stop debugger/ ASP.NET  Development server then you can edit it.

      If you want to continue code edit while your are running ASP.NET Development Server try this:

      http://localhost:3499/Default.aspx

      You do have the option to control which port is used when using the built-in development server.  The steps to specify the port to be used are slightly different depending on whether you are using a website project or a web application project.

      ASP.NET Development Server – Web Application project

      1. Right click the Project in the Solution Explorer, and then select “Properties”

      2. Click “Web” tab.

      3. Go to Server section (Make sure Visual Studio Development server is selected)

      4. Check Enable Edit and Continue is turned on
      Posted in Tips | Tagged | 2 Comments

      Clear Session On Browser Close


      How to capture logoff time when user closes browser?

      Or

      How to end user session when browser closed?

      Or

      How to end user session when user redirect to another sites.

      These are some of the frequently asked questions normally this is the requirement of any application.There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP.I am explain one of them which is very effective and tested.

      1. First create a page LogOut.aspx and in Page_Load event write this code:-

      protected void Page_Load(object sender, EventArgs e){    Session.Abandon();}

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

       

      2. Then add following JavaScript code in your page or Master Page:-

      <script type="text/javascript">

       

          var clicked = false;   function CheckBrowser()     {        if (clicked == false)        {            //Browser closed        }        else        {            //redirected             clicked = false;        }    }
      
          function bodyUnload()    {        if (clicked == false)//browser is closed        {        var request = GetRequest();
      
              request.open  ("GET", "AutoLogOut.aspx", true);        request.send();        }    }
      
          function GetRequest()    {        var request = null;        if (window.XMLHttpRequest)        {            //incase of IE7,FF, Opera and Safari browser            request = new XMLHttpRequest();        }        else        {            //for old browser like IE 6.x and IE 5.x            request = new ActiveXObject('MSXML2.XMLHTTP.3.0');        }        return request;    }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      3.  Add the following code in the body tag of master page.

      <body onunload="bodyUnload();" Onclick="clicked=true;">

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      Finally the code in Master page like this:-

      <script language="javascript" type="text/javascript">    //<![CDATA[
      
          var clicked = false;    function CheckBrowser() {        if (clicked == false) {            //Browser closed        }        else {            //redirected             clicked = false;        }    }
      
          function bodyUnload() {        if (clicked == false)//browser is closed        {            //var request = GetRequest();
      
                  //location.href = 'LogOut.aspx';            var request = GetRequest();
      
                  request.open("GET", "LogOut.aspx", true);            request.send();        }    }    function GetRequest() {        var request = null;        if (window.XMLHttpRequest) {            //incase of IE7,FF, Opera and Safari browser            request = new XMLHttpRequest();        }        else {            //for old browser like IE 6.x and IE 5.x            request = new ActiveXObject('MSXML2.XMLHTTP.3.0');        }        return request;    } 
      
          //]]></script>
      
      <body onunload="bodyUnload();" onclick="clicked=true;">    <form id="form1" runat="server">

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      Posted in Asp.Net | Tagged , , | 1 Comment

      Encrypting and Decrypting web.config Information


      The most sensitive information stored in web.config file can be the connection string. You do not want to disclose the information related to your database to all the users where the application is deployed. Every time it is not possible to have a private machine for your sites, you may need to deploy the site in shared host environment. In this situation to maintain the security to encrypt and decrypt the web.config file.

      We can encrypt the configuration sections by using two built-in providers: DPAPI (Windows Data Protection API) Provider or the RSA provider. The RSA provider (default) uses an RSA key which holds public and private keys, where as the DPAPI provider uses built-in machine-specific key. Let us explore the steps required to encrypt the sections using RSA.

      There is two method for encryption and decryption of web.config file.One through asp.net command line and second through programmatically.

      Method # 1:

       

      Encryption

        ASP.NET 2.0 provides in built functionality to encrypt few sections of web.config file. The task can be completed using Aspnet_regiis.exe. Below is the web.config file and <connectionStrings> section.  

      <?xml version="1.0"?><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">   <connectionStrings>      <add name="MembershipConnectionString" connectionString="connectionString"/>   </connectionStrings>   <system.web>      <compilation debug="true"/>      <authentication mode="Forms" />   </system.web></configuration>

       In this method for encrypting and decryption of web.config does not involve any code, instead is based on the command line tool aspnet_regiis.This command line tool can be found within the %windows%\Microsoft.NET\Framework\versionNumber folder, or can be run directly from the Visual Studio command prompt.

      aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication

       

      -pef indicates that the application is built as File System website.  The second argument is the name of configuration section needs to be encrypted. Third argument is the physical path where the web.config file is located.If you are using IIS base web site the command will be,

       aspnet_regiis.exe -pe “connectionStrings” -app “/DemoApplication”

      .-pe indicates that the application is built as IIS based site. The second argument is the name of configuration section needs to be encrypted. Third argument “-app” indicates virtual directory and last argument is the name of virtual directory where application is deployed.      If everything goes well you will receive a message “Encrypting configuration section…Succeeded!”Open your web.config file and you can see that connection string is encrypted and its look like this.

      <?xml version="1.0"?><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">   <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">      <EncryptedData>         <CipherData>            <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAed...GicAlQ==</CipherValue>         </CipherData>      </EncryptedData>   </connectionStrings>
      
         <system.web>      <compilation debug="true"/>      <authentication mode="Forms" />   </system.web></configuration>

      Decryption:

      Now to decrypt the configuration section in web.config file use following command,For File System Application,

      aspnet_regiis.exe -pdf “connectionStrings” C:\Projects\DemoApplication

      For IIS based Application

      aspnet_regiis.exe -pd “connectionStrings” -app “/DemoApplication”

           If you want to encrypt any nested section in web.config file like <pages> element within <system.web> you need to write full section name as shown below,

      aspnet_regiis.exe -pef “system.web/Pages” C:\Projects\DemoApplication

      Method # 2:

      Step 1: Open Visual Studio > File > WebSite > Select the language (C# or Visual Basic) and location to create a new ASP.NET website.Step 2: Now add a web.config file to the project. Right click the project > Add New Item > Web Configuration FileOpen the web.config and add the following sample entries in the file between the <configuration> tag as shown below:

      <configuration>      <appSettings>            <add key="var1" value="SomeValue"/>      </appSettings>      <connectionStrings> <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;" /> </connectionStrings>
      
            <system.web>...
      
      </configuration>

      Step 3: Now add two buttons to the page, called btnEncrypt and btnDecrypt. We will use these buttons to encrypt and decrypt the sections of the web.config file. Add the following code in the button click event of the two buttons:

       

      C#

      string provider = "RSAProtectedConfigurationProvider";string section = "connectionStrings";
      
      protected void btnEncrypt_Click(object sender, EventArgs e){try{    Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);    ConfigurationSection confStrSect = confg.GetSection(section);    if (confStrSect != null)    {        confStrSect.SectionInformation.ProtectSection(provider);        confg.Save();    }    // the encrypted section is automatically decrypted!!    Response.Write("Configuration Section " + "<b>" +        WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString + "</b>" + " is automatically decrypted");}catch (Exception ex){
      
      }        }
      
      protected void btnDecrypt_Click(object sender, EventArgs e){try{    Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);    ConfigurationSection confStrSect = confg.GetSection(section);    if (confStrSect != null && confStrSect.SectionInformation.IsProtected)    {        confStrSect.SectionInformation.UnprotectSection();        confg.Save();    }
      
      }catch (Exception ex){
      
      }}

      VB.NET

      Private provider As String = "RSAProtectedConfigurationProvider"Private section As String = "connectionStrings"
      
      Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs)Try      Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)      Dim confStrSect As ConfigurationSection = confg.GetSection(section)      If Not confStrSect Is Nothing Then            confStrSect.SectionInformation.ProtectSection(provider)            confg.Save()      End If      ' the encrypted section is automatically decrypted!!      Response.Write("Configuration Section " & "<b>" & WebConfigurationManager.ConnectionStrings("MyConnString").ConnectionString & "</b>" & " is automatically decrypted")Catch ex As Exception
      
      End TryEnd Sub
      
      Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs)Try      Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)      Dim confStrSect As ConfigurationSection = confg.GetSection(section)      If Not confStrSect Is Nothing AndAlso confStrSect.SectionInformation.IsProtected Then            confStrSect.SectionInformation.UnprotectSection()            confg.Save()      End If
      
      Catch ex As Exception
      
      End TryEnd Sub

      In the code above, we open the web.config file as a System.Configuration.Configuration object using the specified virtual path. We then call the GetSection() to retrieve the specified ConfigurationSection object, in our case connectionStrings. The ConfigurationSection.SectionInformation property gets us the SectionInformation object, and then we finally call the ProtectSection() method on the SectionInformation object to mark the section for protection.Similarly while decrypting the section, we call the UnprotectSection() method of the SectionInformation object.Step 4: Now run the application and click on the Encrypt button. Now close the application > Open the web.config file. You will observe that the <connectionString> has been encrypted in the following manner:

      <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider"> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"   xmlns="http://www.w3.org/2001/04/xmlenc#">   <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />   <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">    <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">     <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />     <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">      <KeyName>Rsa Key</KeyName>     </KeyInfo>     <CipherData>      <CipherValue>ZehN7B+VXBdJTe1X3NFz9Uz3NqxvjSMmbytLeHGNlZa4JkkpRkXzphm5sedHeMTk5KZCHxoYrJ4ssJ0OcZnzLxNUrAB9Ie3y8xJVWJ2s0RQdmaGk5bSJADE1xKJBuOtDIOi/Ron7qJDWXwllC3vvmNwgabmJ9RU+RN35TOQpznc=</CipherValue>     </CipherData>    </EncryptedKey>   </KeyInfo>   <CipherData>    <CipherValue>q2amqNwjeyEbMxF5pZ3XqfboNUJKSml773mPkISGi6uWCWCDPs0ICClmH1eQYcsI9FlxFvEfyRyRRugqOU2xe+gd3aRZEZ5irpGFB45Fn6M+te7kgOeTK1gjGEsbeaNjBNwgpcXMh9RiA9xVOvWlLAyJ3u8DsDQ+4JmM/zTUtxer/8DlUI7+u8D+9V4b5tWxShp4BToMFdTcefhMb19pGdn+jocGetWBJirO5CJsLXI=</CipherValue>   </CipherData> </EncryptedData> </connectionStrings>

      Note: If you are running this application from the file system, when you close the application, Visual Studio will display a dialog with the message of “The file has been modified outside the editor. Do you want to reload it?” Click yes and then view the web.config.Step 5: Run the application again and now click on the Decrypt button. You will observe that the <connectionStrings> section is no longer encrypted and can be read as plain text.Note: Take a note that ‘section groups’ like <system.net>, <mailSettings> etc. cannot be encrypted through programmatically .You can encrypt all the sections of web.config file except following using the method I displayed in this article,

      <processModel><runtime><mscorlib><startup><system.runtime.remoting><configProtectedData><satelliteassemblies><cryptographySettings><cryptoNameMapping><cryptoClasses>

         To encrypt these section you needed to use Aspnet_setreg.exe tool.

      Posted in Asp.Net, C# | Tagged | 7 Comments

      >Clear Session On Browser Close


      >

       

      How to capture logoff time when user closes browser?

      Or

      How to end user session when browser closed?

      Or

      How to end user session when user redirect to another sites.

      These are some of the frequently asked questions normally this is the requirement of any application.There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP.I am explain one of them which is very effective and tested.

       

      1. First create a page LogOut.aspx and in Page_Load event write this code:-

      protected void Page_Load(object sender, EventArgs e)
      {
      Session.Abandon();
      }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

       

      2. Then add following JavaScript code in your page or Master Page:-

      <script type="text/javascript"> 
          var clicked = false;
      function CheckBrowser()
      {
      if (clicked == false)
      {
      //Browser closed
      }
      else
      {
      //redirected
      clicked = false;
      }
      }

      function bodyUnload()
      {
      if (clicked == false)//browser is closed
      {
      var request = GetRequest();

      request.open ("GET", "AutoLogOut.aspx", true);
      request.send();
      }
      }

      function GetRequest()
      {
      var request = null;
      if (window.XMLHttpRequest)
      {
      //incase of IE7,FF, Opera and Safari browser
      request = new XMLHttpRequest();
      }
      else
      {
      //for old browser like IE 6.x and IE 5.x
      request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
      }
      return request;
      }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      3.  Add the following code in the body tag of master page.

      <body onunload="bodyUnload();" Onclick="clicked=true;">

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      Finally the code in Master page like this:-


      <script language="javascript" type="text/javascript">
      //<![CDATA[

      var clicked = false;
      function CheckBrowser() {
      if (clicked == false) {
      //Browser closed
      }
      else {
      //redirected
      clicked = false;
      }
      }

      function bodyUnload() {
      if (clicked == false)//browser is closed
      {
      //var request = GetRequest();

      //location.href = 'LogOut.aspx';
      var request = GetRequest();

      request.open("GET", "LogOut.aspx", true);
      request.send();
      }
      }
      function GetRequest() {
      var request = null;
      if (window.XMLHttpRequest) {
      //incase of IE7,FF, Opera and Safari browser
      request = new XMLHttpRequest();
      }
      else {
      //for old browser like IE 6.x and IE 5.x
      request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
      }
      return request;
      }



      //]]>
      </script>

      <body onunload="bodyUnload();" onclick="clicked=true;">
      <form id="form1" runat="server">

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      .csharpcode, .csharpcode pre
      {
      font-size: small;
      color: black;
      font-family: consolas, “Courier New”, courier, monospace;
      background-color: #ffffff;
      /*white-space: pre;*/
      }
      .csharpcode pre { margin: 0em; }
      .csharpcode .rem { color: #008000; }
      .csharpcode .kwrd { color: #0000ff; }
      .csharpcode .str { color: #006080; }
      .csharpcode .op { color: #0000c0; }
      .csharpcode .preproc { color: #cc6633; }
      .csharpcode .asp { background-color: #ffff00; }
      .csharpcode .html { color: #800000; }
      .csharpcode .attr { color: #ff0000; }
      .csharpcode .alt
      {
      background-color: #f4f4f4;
      width: 100%;
      margin: 0em;
      }
      .csharpcode .lnum { color: #606060; }

      Posted in Asp.Net | 3 Comments

      Custom Paging And Sorting Using Oracle Stored Procedure.


      Here I will explain how to create Oracle stored procedure for custom paging,sorting and base on culture .Normally you should know how many record found in table base on where clause as well as required dynamic sorting and paging.All these things possible using dynamic creation of oracle stored procedure see this give below example.
      CREATE OR REPLACE PROCEDURE GET_COUNTRY
      (
      //——– Table Paramerters——————————–
      V_COUNTRY_NO IN TRN_ORG_SYS.COUNTRY.COUNTRY_NO%TYPE DEFAULT NULL
      ,V_COUNTRY_NAME_AR IN TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_AR%TYPE DEFAULT NULL
      ,V_COUNTRY_NAME_EN IN TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_EN%TYPE DEFAULT NULL
      ,V_CREATED_BY IN TRN_ORG_SYS.COUNTRY.CREATED_BY%TYPE DEFAULT NULL
      ,V_CREATED_ON IN TRN_ORG_SYS.COUNTRY.CREATED_ON%TYPE DEFAULT NULL
      ,V_MODIFIED_BY IN TRN_ORG_SYS.COUNTRY.MODIFIED_BY%TYPE DEFAULT NULL
      ,V_MODIFIED_ON IN TRN_ORG_SYS.COUNTRY.MODIFIED_ON%TYPE DEFAULT NULL
      ,V_ISDELETED IN TRN_ORG_SYS.COUNTRY.ISDELETED%TYPE DEFAULT NULL

      //——– Parameters of Paging Sorting and culture————
      ,P_CULTURE IN VARCHAR2 DEFAULT NULL
      ,P_SORT_ORDER IN VARCHAR2 DEFAULT NULL
      ,P_SORT_FIELD IN VARCHAR2 DEFAULT NULL
      ,P_PAGE_NO_NEEDED IN NUMBER DEFAULT NULL
      ,P_NUM_PER_PAGE IN NUMBER DEFAULT NULL
      ,P_OUT_TOTAL_RECORDS OUT NUMBER
      ,ITEMS_CURSOR OUT TRN_ORG_PROC.REF_CURSOR.T_CURSOR
      )
      IS
      –Local variables >>>>>>>
      SQL_SELECT CLOB;
      SQL_SELONE VARCHAR2(4000);
      SQL_SELTWO VARCHAR2(4000);
      SQL_COUNTONE VARCHAR2(50) := ‘SELECT COUNT(*) FROM ( ‘;
      SQL_COUNTTWO VARCHAR2(50) := ‘) ‘;
      SQL_ORDER_BY VARCHAR2(100);
      FROM_ROWNUM NUMBER;
      TO_ROWNUM NUMBER;
      V_NUM_PER_PAGE NUMBER := P_NUM_PER_PAGE;
      V_PAGE_NO_NEEDED NUMBER := P_PAGE_NO_NEEDED;
      V_SORT_FIELD VARCHAR2(30);
      V_SORT_ORDER VARCHAR2(30);
      NEWLINE VARCHAR2(10) := CHR(13) || CHR(10);

      –Local variables <<<<<<<
      BEGIN
      IF (V_NUM_PER_PAGE IS NULL OR V_NUM_PER_PAGE <= 0) THEN
      V_NUM_PER_PAGE := 25;
      END IF;
      IF (V_PAGE_NO_NEEDED IS NULL OR V_PAGE_NO_NEEDED <= 0) THEN
      V_PAGE_NO_NEEDED := 1;
      END IF;
      IF (P_SORT_FIELD IS NULL) THEN
      V_SORT_FIELD := ‘ COUNTRY_NO’;
      ELSE
      V_SORT_FIELD := P_SORT_FIELD;
      END IF;
      IF (P_SORT_ORDER IS NULL) THEN
      V_SORT_ORDER := ‘ASC’;
      ELSE
      V_SORT_ORDER := P_SORT_ORDER;
      END IF;

      FROM_ROWNUM := ((V_PAGE_NO_NEEDED – 1) * V_NUM_PER_PAGE) + 1;
      TO_ROWNUM := FROM_ROWNUM -1 + V_NUM_PER_PAGE;
      SQL_SELONE := SQL_SELONE || ‘SELECT ‘ || NEWLINE;
      SQL_SELONE := SQL_SELONE || ‘ b.* ‘ || NEWLINE;
      SQL_SELONE := SQL_SELONE || ‘ FROM ( ‘ || NEWLINE;
      SQL_SELONE := SQL_SELONE || ‘ SELECT ‘ || NEWLINE;
      SQL_SELONE := SQL_SELONE || ‘ a.*, ‘ || NEWLINE;
      SQL_SELONE := SQL_SELONE || ‘ ROWNUM rnum ‘ || NEWLINE;
      SQL_SELONE := SQL_SELONE || ‘ FROM ( ‘ || NEWLINE;

      SQL_SELECT := SQL_SELECT || ‘SELECT TRN_ORG_SYS.COUNTRY.COUNTRY_NO,
      DECODE(”’|| P_CULTURE ||””||’,
      ”en-US”,TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_EN ,
      ”ar-KW”,TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_AR,
      TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_EN) COUNTRY_NAME,
      TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_AR,
      TRN_ORG_SYS.COUNTRY.COUNTRY_NAME_EN,
      TRN_ORG_SYS.COUNTRY.CREATED_BY,
      TRN_ORG_SYS.COUNTRY.CREATED_ON,
      TRN_ORG_SYS.COUNTRY.MODIFIED_BY,
      TRN_ORG_SYS.COUNTRY.MODIFIED_ON,
      TRN_ORG_SYS.COUNTRY.ISDELETED
      FROM TRN_ORG_SYS.COUNTRY’ || NEWLINE;
      –Construction of Where clause Starts here
      SQL_SELECT := SQL_SELECT || ‘ WHERE 1 = 1 ‘ || NEWLINE;

      IF(V_COUNTRY_NO IS NOT NULL AND V_COUNTRY_NO > 0 ) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.COUNTRY_NO = ‘ || V_COUNTRY_NO || ” || NEWLINE;
      END IF;
      IF(V_COUNTRY_NAME_AR IS NOT NULL) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.COUNTRY_NAME_AR Like ”%’ || V_COUNTRY_NAME_AR || ‘%”’ || NEWLINE;
      END IF;
      IF(V_COUNTRY_NAME_EN IS NOT NULL) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.COUNTRY_NAME_EN Like ”%’ || V_COUNTRY_NAME_EN || ‘%”’ || NEWLINE;
      END IF;
      IF(V_CREATED_BY IS NOT NULL) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.CREATED_BY Like ”%’ || V_CREATED_BY || ‘%”’ || NEWLINE;
      END IF;
      IF(V_CREATED_ON IS NOT NULL) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.CREATED_ON = ”’ || V_CREATED_ON || ”” || NEWLINE;
      END IF;
      IF(V_MODIFIED_BY IS NOT NULL) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.MODIFIED_BY Like ”%’ || V_MODIFIED_BY || ‘%”’ || NEWLINE;
      END IF;
      IF(V_MODIFIED_ON IS NOT NULL) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.MODIFIED_ON = ”’ || V_MODIFIED_ON || ”” || NEWLINE;
      END IF;
      IF(V_ISDELETED IS NOT NULL AND V_ISDELETED > 0 ) THEN
      SQL_SELECT := SQL_SELECT || ‘ AND COUNTRY.ISDELETED = ‘ || V_ISDELETED || ” || NEWLINE;
      END IF;
      –Construction of Where clause Ends here

      SQL_ORDER_BY := SQL_ORDER_BY || ‘ ORDER BY lower(‘ || V_SORT_FIELD || ‘) ‘ || V_SORT_ORDER || NEWLINE;

      SQL_SELTWO := SQL_SELTWO || ‘ ) a ‘ || NEWLINE;
      SQL_SELTWO := SQL_SELTWO || ‘ WHERE ‘ || NEWLINE;
      SQL_SELTWO := SQL_SELTWO || ‘ ROWNUM <= :2) b ' || NEWLINE; — TO_ROWNUM
      SQL_SELTWO := SQL_SELTWO || ‘ WHERE ‘ || NEWLINE;
      SQL_SELTWO := SQL_SELTWO || ‘ rnum >= :3 ‘ || NEWLINE; — FROM_ROWNUM

      EXECUTE IMMEDIATE SQL_COUNTONE || TO_CHAR(SQL_SELECT) || SQL_COUNTTWO INTO P_OUT_TOTAL_RECORDS;

      OPEN ITEMS_CURSOR FOR SQL_SELONE || TO_CHAR(SQL_SELECT) || SQL_ORDER_BY || SQL_SELTWO USING TO_ROWNUM, FROM_ROWNUM;

      EXCEPTION
      WHEN NO_DATA_FOUND THEN
      NULL;
      WHEN OTHERS THEN
      — Consider logging the error and then re-raise
      RAISE;
      END GET_COUNTRY;

      Base on above example you can easily create oracle stored procedure for custom paging, sorting,total record found and base on culture.

      Posted in Asp.Net, C#, Database | Tagged | 1 Comment