Total Pageviews

Showing posts with label .NET. Show all posts
Showing posts with label .NET. Show all posts

Friday, October 23, 2009

Handling Session Timeouts

With new technology making the web a viable option for more and more applications, we are now seeing the web browser take over for the traditional desktop. Developers making this transition, quickly learn about some of the key differences between the two paradigms.  One of the issues they are often forced to deal with is Session expiration.  Out of the box, ASP.NET and IIS typically allow only 20 minutes of idle time before the session expires. This can be configured, but knowing that the session expired, or redirecting to a particular page often comes in handy.  One way to do this is to add a cookie during the Session_Start method of the global.ascx.cs file, and then check for that same cookie the next time a session is created.  If the cookie is there, the session either timed out, or was reset.

Here is an example:

protected void Session_Start(Object sender, EventArgs e)
 {
     //Check if there is a cookie from when the session started.
     //If not, the session has not been started yet,
     //so add the cookie.
     HttpContext context = HttpContext.Current;
     HttpCookieCollection cookies = context.Request.Cookies;
     HttpCookie SessionCookie = cookies["SessionStarted"];
     if (SessionCookie == null)
     {
         HttpCookie cookie = new HttpCookie("SessionStarted", DateTime.Now.ToString());
         cookie.Path = "/";
         context.Response.Cookies.Add(cookie);
     }
     else
     {
         //If there was a cookie, but we are in this method starting a session
         //Then the session must have expired or been reset.

         //TODO: Do something useful with this info, log it, etc.
         //update the cookie with the new session start time
         cookies.Remove("SessionStarted");
         SessionCookie.Value = DateTime.Now.ToString();
         context.Response.Cookies.Add(SessionCookie);

         //Redirect to the whatever page you want to handle this situation.
         //An error page, login page, etc.
         context.Response.Redirect("~/Login.aspx", true);
     }
 }
 
 ---
thnx...enjoy programming.

Thursday, October 22, 2009

What is httpHandler & httpModule?

httpHandler – Extenstion Based Preprocessor :
ASP.NET HTTP handler is the process that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
httpModule – Event based Preprocessor :
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
When to use HTTP handlers:
  • RSS feeds: To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
  • Image server:   If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler’s response.
When to use HTTP modules:
  • Security:   Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
  • Statistics and logging:   Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
  • Custom headers or footers:   Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
Main Features:
  • The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
    The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.
  • Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
  • Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.
  • Modules can subscribe to a variety of request-pipeline notifications. Modules can receive notification of events of the HttpApplication object.
Built-in HTTP Handlers in ASP.NET
  • ASP.NET page handler (*.aspx): The default HTTP handler for all ASP.NET pages.
  • Web service handler (*.asmx): The default HTTP handler for Web service pages created as .asmx files in ASP.NET.
  • Generic Web handler (*.ashx): The default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive.
  • Trace handler (trace.axd): A handler that displays current page trace information.

Wednesday, October 14, 2009

URL rewriting in asp.net

what is URL rewriting ?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.

http://msdn.microsoft.com/en-us/library/ms972974.aspx

why URL rewriting?

1) Make User Friendly and Secure URL

Example :  In your application, you create a page which display category information and it’s relevant category. At that time we normally passing a value via query string,

http://Site.com/category.aspx?categoryid=1. Any user play with URL, you can also do the URL Encryption. but sometime case is complex at that time it is not possible.

2) Make SEO Friendly URL

3) Usability & Maintainability

Use Of Browser file?

ASP.NET uses .browser files to determine the capabilities of the browser, and how to render markup to that browser.

Browser files are used to reduce the load of the page made by the view state by storing it in a server side session variable.

In particular Rewriting Module: Handling Post back with URL Rewriting.

what is ControlAdapter?

for more detail please check :

http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx

Create demo project for URL Rewriting:

Step 1:

Create Web application with (Asp.net 2.0 with c#)

Step 2:

Put two button in the form (default.aspx)

Put Below code for Button1_Click Event :

Response.Redirect("Default.aspx?id=1");

Put Below code for Button2 _Click Event:

Response.Redirect("/urlrewriting/FirstSection/Default.html");

Step 3: Run Application

once you press Button2 it give Error page.

Step 4:

Create Class FormRewriterControlAdapter.cs

1: using System;

2: using System.Data;

3: using System.Configuration;

4: using System.Web;

5: using System.Web.Security;

6: using System.Web.UI;

7: using System.Web.UI.WebControls;

8: using System.Web.UI.WebControls.WebParts;

9: using System.Web.UI.HtmlControls;

10: 

11: public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter

12: {

13: protected override void Render(HtmlTextWriter writer)

14: {

15: base.Render(new RewriteFormHtmlTextWriter(writer));

16: }

17: }

18: 

19: public class RewriteFormHtmlTextWriter : HtmlTextWriter

20: {

21: public RewriteFormHtmlTextWriter(HtmlTextWriter writer)

22: : base(writer)

23: {

24: this.InnerWriter = writer.InnerWriter;

25: }

26: 

27: public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)

28: : base(writer)

29: {

30: base.InnerWriter = writer;

31: }

32: 

33: public override void WriteAttribute(string name, string value, bool fEncode)

34: {

35: if (name == "action")

36: {

37: HttpContext Context = HttpContext.Current;

38: if (Context.Items["ActionAlreadyWritten"] == null)

39: {

40: value = Context.Request.RawUrl;

41: Context.Items["ActionAlreadyWritten"] = true;

42: }

43: }

44: base.WriteAttribute(name, value, fEncode);

45: }

46: }

Create Class MyHttpHandler.cs

1: using System;

2: using System.Data;

3: using System.Configuration;

4: using System.Web;

5: using System.Web.Security;

6: using System.Web.UI;

7: using System.Web.UI.WebControls;

8: using System.Web.UI.WebControls.WebParts;

9: using System.Web.UI.HtmlControls;

10: 

11: public class MyHttpHandler : IHttpModule

12: 

13: {

14: public MyHttpHandler()

15: {

16: //

17: // TODO: Add constructor logic here

18: //

19: }

20: 

21: #region IHttpModule Members

22: 

23: public void Dispose()

24: {

25:

26: }

27: 

28: public void Init(HttpApplication app)

29: {

30: app.BeginRequest += new EventHandler(Application_BeginRequest);

31: }

32: 

33: private void Application_BeginRequest(object sender, EventArgs e)

34: {

35: System.Web.HttpApplication app = (System.Web.HttpApplication)sender;

36: string requestedUrl = app.Request.Path.ToLower();

37: string realUrl = GetRealUrl(requestedUrl);

38: if (!String.IsNullOrEmpty(realUrl))

39: app.Context.RewritePath(realUrl, false);

40: }

41: 

42: private string GetRealUrl(string requestedUrl)

43: {

44: // Implement your own logic here

45: MyURL obj = new MyURL();

46: return obj.GetRealPath(requestedUrl);

47: }

48: #endregion

49: }

create Class MyURL.cs

1: 

2: using System;

3: using System.Data;

4: using System.Configuration;

5: using System.Web;

6: using System.Web.Security;

7: using System.Web.UI;

8: using System.Web.UI.WebControls;

9: using System.Web.UI.WebControls.WebParts;

10: using System.Web.UI.HtmlControls;

11: using System.Collections.Generic;

12: 

13: ///

14: /// Summary description for MyURL

15: ///

16: public class MyURL

17: {

18: public MyURL()

19: {

20: //

21: // TODO: Add constructor logic here

22: //

23: }

24: 

25: public string GetRealPath(string requestedUrl)

26: {

27: string path = "";

28: Dictionary<string, string> paths = GetPathsFromDatabase();

29: if (paths.ContainsKey(requestedUrl))

30: paths.TryGetValue(requestedUrl, out path);

31: return path;

32: }

33: 

34: private static Dictionary<string, string> GetPathsFromDatabase()

35: {

36: Dictionary<string, string> paths = new Dictionary<string, string>();

37: paths.Add("/urlrewriting/FirstSection/Default.html".ToLower(), "/urlrewriting/Default.aspx?SectionID=1");

38: paths.Add("/urlrewriting/SecondSection/Default.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2");

39: paths.Add("/urlrewriting/FirstSection/Page1.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=1&Item=1");

40: paths.Add("/urlrewriting/FirstSection/Page2.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=1&Item=2");

41: paths.Add("/urlrewriting/SecondSection/Page1.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2&Item=1");

42: paths.Add("/urlrewriting/SecondSection/SubSection/AnotherOne/Page5.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2&Item=5");

43: paths.Add("/urlrewriting/Default.aspx".ToLower(), "/urlrewriting/Default.aspx");

44: return paths;

45: }

46: }

Register Http Handler in to Web.Config

1: <system.web>

2: <httpModules>

3: <add name="MyHttpHandler" type="MyHttpHandler"/>

.Browser File

Add New .browser file from Add New Item.

1: <browsers>

2: <browser id="NewBrowser" parentID="Mozilla">

3: <identification>

4: <userAgent match="Unique User Agent Regular Expression" />

5: identification>

6: 

7: <capture>

8: <userAgent match="NewBrowser (?'version'\d+\.\d+)" />

9: capture>

10: 

11: <capabilities>

12: <capability name="browser" value="My New Browser" />

13: <capability name="version" value="${version}" />

14: capabilities>

15: browser>

16: 

17: <browser refID="Mozilla">

18: <capabilities>

19: <capability name="xml" value="true" />

20: capabilities>

21: browser>

22:

23: <browser refID="Default">

24: <controlAdapters>

25: <adapter controlType="System.Web.UI.HtmlControls.HtmlForm"

26: adapterType="FormRewriterControlAdapter" />

27: controlAdapters>

28: browser>

29: browsers>

step 5: Run Application

Now Press Button 2:

http://localhost:2696/urlrewriting/FirstSection/Default.html and it is run.

Now made some change in to system. Remove browser file and click button2, after that made postback at that time above URL is change to original URL.

Reference Site :

For Detail Example :

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Hope this help you.

Thnx

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...