Does Session use cookies in Asp.Net?

It’s very confusing for many developers that session use cookies or not, and also a interesting interview question for .net developer ūüôā Let’s understand the relation between session and cookies-

Does session use cookies? Answer is- YES and NO.

One more confusion?

While using session in the application we have two things which are SessionID which is used to uniquely identify the session variables and Session Value which is the actual data stored in the session variables.

As session is a server side and cookies are client side state management techniques, so session actual data always stored on the server memory by default. The following list describes the available session storage modes-

  • InProc¬†mode,¬†which stores session state in memory on the Web server. This is the default.
  • StateServer¬†mode,¬†which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer¬†mode¬†stores session state in a SQL¬†Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom¬†mode, which enables you to specify a custom storage provider.
  • Off¬†mode,¬†which disables session state.

I hope it’s clear that session data is stored on the server and has no relationship with the cookies.

Now let’s understand the session keys storage types-

 

 

 

 

Session and cookies relationship are limited to only session keys not session value.

 

Session¬†use¬†cookies¬†‚ÄstYes¬†: ¬†By default¬†Session key is stored in an HTTP ¬†non-persistent cookie that the client sends to the server (and server to client)¬†on each request/responses.¬†The server can then read the key from the cookie and re-inflate the server session state.

If we will try to run below code after disabled the cookies then it will not work that proves that session use the cookies.

Session¬†use¬†cookies¬†‚ÄstNo¬†: There is the possibility that¬†browser does not support cookie or disabled, then asp.net can not create a cookie to store session keys.¬†ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session keys not in a cookie, but in the URLs. This can be done by setting cookieless=‚ÄĚtrue‚ÄĚ in the web.config file ¬†as-

<configuration>
<sessionstate cookieless=‚ÄĚtrue‚ÄĚ />
</configuration>

http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx

 

Programming is Easy…

Advertisements

ASP.NET – Page life cycle – Part-2

Below are the General Page Life-cycle Stages :-

Some parts of the life cycle occur only when a page is processed as a postback. For postbacks, the page life cycle is the same during a partial-page postback (as when you use an UpdatePanel control) as it is during a full-page postback.

Page request :-

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled , or whether a cached version of the page can be sent in response without running the page.

Start:-

In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization :- 

During page initialization, controls on the page are available and each control’s¬†UniqueID¬†property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load :-  

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling :- 

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValidproperty of individual validator controls and of the page. (There is an exception to this sequence: the handler for the event that caused validation is called after validation.)

Rendering :- 

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the¬†Render¬†method for each control, providing a text writer that writes its output to the¬†OutputStream¬†object of the page’s¬†Response¬†property.

Unload :- 

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such asResponse and Request are unloaded and cleanup is performed.

 

Life Cycle Events :- 

Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.


PreInit :- 

Raised after the start stage is complete and before the initialization stage begins. Use this event for the following:

1) Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
2) Create or re-create dynamic controls.
3) Set a master page dynamically.
4) Set the Theme property dynamically.
5) Read or set profile property values.

Init :-  

Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Initevent of the page.

Use this event to read or initialize control properties.

InitComplete :- 

Raised at the end of the page’s initialization stage. Only one operation takes place between the¬†Init¬†and¬†InitComplete¬†events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the¬†ViewState¬†collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their¬†Init¬†event.

Use this event to make changes to view state that you want to make sure are persisted after the next postback.

PreLoad :- 

Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.

Load :- 

The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.

Use the OnLoad event method to set properties in controls and to establish database connections.

Control events : –

Use these events to handle specific control events, such as a¬†Button¬†control’s¬†Click¬†event or ¬†¬†TextBox¬†control’s¬†TextChanged¬†event.

LoadComplete :- 

Raised at the end of the event-handling stage.

Use this event for tasks that require that all other controls on the page be loaded.

PreRender :- 

Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)

The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.

Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.

PreRenderComplete :- 

Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.

SaveStateComplete:-

Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.

Render:- 

This is not an event; instead, at this stage of processing, the¬†Page¬†object calls this method on each control. All ASP.NET Web server controls have aRender¬†method that writes out the control’s markup to send to the browser.

If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the¬†Render¬†method. For more information, seeDeveloping Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

Unload:-

Raised for each control and then for the page.

In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

 

References :-  http://msdn.microsoft.com/en-us/library/ms178472(v=vs.110).aspx

 

Programming is Easy….

What is ASP.NET AJAX ?

ASP.NET includes many components that help to enable AJAX features for developers. These components have a common goal:-

To improve the user’s experience by providing developers with the ability to create more responsive web applications.

The following are the ASP.NET components related to AJAX capabilities:
1)Microsoft AjAX Library :- The Microsoft AJAX Library is a set of JavaScript files that make programming client-side JavaScript easier.
2)ASP.NET AjAX server controls :-ASP.NET ships with a set of AJAX server controls that can be embedded in your webpages to enable partial-page updates, communicate with a server process to indicate progress, and periodically update portions of a page.
3)jQuery:- jQuery is a code library that makes it easier to write client-side scripts and AJAX applications. It is actually an open source library (see http://jquery.com/). ASP.NET includes the scripts for jQuery and jQuery IntelliSense support within the Visual Studio IDE. 
4)AjAX Control Toolkit :-The AJAX Control Toolkit is a set of community-created and supported controls that show off the power of AJAX. You can use these controls in your webpages to enable many client-side features typically found only in applications running on the desktop, controls such as masked edit boxes, slider controls, filtered text boxes, modal pop-up windows, and much more.
5)Client-side web service support :-ASP.NET and AJAX provide support for calling web services asynchronously from the client by using JavaScript Object Notation (JSON) serialization and XML.
6)ASP.NET standard controls:- The controls that ship with ASP.NET also make use of JavaScript on the client. It is easy to forget about this because you are not required to write any JavaScript to get this interactivity. Examples of ASP.NET controls that use JavaScript include the validation controls, the Web Part controls, the menu control, the TreeView control, and the Calendar control.

Uses and Benefits of ASP.NET AJAX :-
1)Partial-page updates :- This feature allows you to define an area of a webpage to post back and update independently from the rest of the page. Only the updated content will be refreshed when the request completes. This ensures that the user stays within his or her current context. It also gives users the feeling that they are interacting with the application (and not a server).

2)Client-side processing :-This interactivity provides immediate feedback and responsiveness to users. With client script, you can enable functionality such as collapsible areas of a page, tabs on a webpage, data sorting on the client, and much more.

3)Desktop-like Ui :- With AJAX, you can provide users with controls such as modal dialog boxes, progress indicators, masked edit boxes, tooltips, and more. This helps make the user experience between web and rich desktop applications much more similar.

4) Progress indication :- This allows you to track the progress of a server-side process and continuously update the user. This gives users the feeling that they are in control and assures them that the application is still processing (as with a desktop application).

5) improved performance and higher scale :- You can achieve increased performance and scale by processing portions of a page on just the client. You then take advantage of the user’s machine, which takes the load off the server. This results in real and perceived performance and scalability increases.

6)Web service calls from the client:- This allows you to call back to the server directly from client script running in a browser and then show the results to the user (often by using partial-page updates).

7)Cross-browser, cross-platform support :- JavaScript, AJAX, and jQuery are all supported on multiple browsers and multiple platforms. This allows you to write interactive applications that run in more client environments than the average desktop application.

The AJAX Server Controls:-
The ScriptManager Controls:-
Each page you write that uses ASP.NET AJAX requires one (and only one) instance of a ScriptManager control. The ScriptManager control is responsible for pushing the Microsoft AJAX Library down to the client when your page is requested.
It also manages partial-page updates, progress indicators, and more. You add the ScriptManager control to your page source. It does not have a visual representation. It is simply a control used to manage AJAX processing.
The basic page markup for a ScriptManager control in Source view looks as follows.

&lt;asp:ScriptManager ID=&quot;ScriptManager1&quot; runat=&quot;server&quot;&gt; 
&lt;/asp:ScriptManager&gt;

By default, the ScriptManager control’s EnablePartialRending property is set to true. This indicates that the page supports partial-page updates. You can use this property to turn this feature off if needed.

The ScriptManagerProxy Controls:-
You will often need to support AJAX in a user control you write or directly in the master page of a site. This presents an issue, because a page can contain only a single ScriptManager control. Having one inside your user control and another inside the page that consumes the user control, for example, would be a problem. To overcome this issue, you can use the ScriptManagerProxy control.
The ScriptManagerProxy control can be used either by child pages that use a master page that already defines a ScriptManager control or by user and custom controls that you write. You use it much the same way you would a ScriptManager control. You can register scripts that are specific to the child page or control that you are writing. ASP.NET takes care of the rest.

The UpdatePanel Control :-
The UpdatePanel control allows you to define areas of a page that should post back to the server independent of the rest of the page. The UpdatePanel control is a container for other controls. The controls you put inside the UpdatePanel control that cause a postback to the server will be managed as partial-page updates.


 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">   
<Triggers>     
<asp:AsyncPostBackTrigger ControlID="ButtonSearch" EventName="Click" />   
</Triggers>   
<ContentTemplate>     
        ... Grid View markup ...    
</ContentTemplate>
 </asp:UpdatePanel>

The UpdateProgress Control:-
The UpdateProgress control is used to provide information in the form of graphics or text that is displayed to the user during a partial-page update.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">   <ContentTemplate>            
 <asp:GridView ID="GridView1" runat="server">     </asp:GridView>     <asp:UpdateProgress ID="UpdateProgress1" runat="server">       <ProgressTemplate>        
 <div style="font-size: large">Processing ...</div>       </ProgressTemplate>     
</asp:UpdateProgress>   
</ContentTemplate> 
</asp:UpdatePanel>

The Timer Control:-
The ASP.NET Timer control is an AJAX control that can be used to update portions of a page on a periodic, timed basis. This is useful if you need to update an image such as an advertisement on a webpage or perhaps a value such as a stock ticker or a news ticker. The Timer control can also be used to simply run code on the server on a periodic basis.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">   <ContentTemplate>    
 <asp:Image ID="Image1" runat="server"        ImageUrl="~/images/contoso.png" />     
<asp:Timer ID="Timer1" runat="server"       Interval="5000" ontick="Timer1_Tick">     </asp:Timer>         
</ContentTemplate> 
</asp:UpdatePanel>

Programming is Easy…..

ASP.NET Application Life Cycle Events and Global.asax

During the application life cycle, the application raises events that you can handle and calls particular methods that you can override. To handle application events or methods, we can create a file named Global.asax in the root directory of your application.

If we create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication class, and then uses the derived class to represent the application.

ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event,  such as Application_BeginRequest.

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

Below is the commonly used events and methods during the application life cycle :-

1)Application_Start :-  

Called when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method is called only one time during the life cycle of an application.

You can use this method to perform startup tasks such as loading data into the cache and initializing static values.You should set only static data during application start. Do not set any instance data because it will be available only to the first instance of theHttpApplication class that is created.

 

2) Application_event :-

Raised at the appropriate time in the application life cycle.
Application_Error can be raised at any phase in the application life cycle.
Application_EndRequest  is the only event that is guaranteed to be raised in every request, because a request can be short-circuited.

3)Init :- 

Called once for every instance of the HttpApplication class after all modules have been created.

4) Dispose:- 

Called before the application instance is destroyed. You can use this method to manually release any unmanaged resources. For more information, see Cleaning Up Unmanaged Resources.

5) Application_End :-

Called once per lifetime of the application before the application is unloaded.

 
Reference :- http://msdn.microsoft.com/en-us/library/ms178473(v=vs.100).aspx

 

Programming is Easy…..

ASP.NET Application Life Cycle

ASP.NET Application Life Cycle  Overview for IIS 5.0 and 6.0 are divided in below stages:-

Stage 1:-  User requests an application resource from the Web server

The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server.  ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.

NoteNote : If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx.

Stage 2 :- ASP.NET receives the first request for the application.

When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain.  Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provi;-des access to information about the application such as the name of the folder where the application is stored.

The following diagram illustrates this relationship:

 

Stage 3:- ASP.NET core objects are created for each request

After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies.

 

Stage 4:- An HttpApplication object is assigned to the request

After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

 

NoteNote :- The first time an ASP.NET page or process is requested in an application, a new instance of HttpApplication is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.
Stage 5:-  The request is processed by theHttpApplication pipeline
The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.

  1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.
  2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.
  3. Raise the BeginRequest event.
  4. Raise the AuthenticateRequest event.
  5. Raise the PostAuthenticateRequest event.
  6. Raise the AuthorizeRequest event.
  7. Raise the PostAuthorizeRequest event.
  8. Raise the ResolveRequestCache event.
  9. Raise the PostResolveRequestCache event.
  10. Based on the file name extension of the requested resource (mapped in the application’s¬†configuration file), select a class that implementsIHttpHandler¬†to process the request. If the request is for an object (page) derived from the¬†Page¬†class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of it.
  11. Raise the PostMapRequestHandler event.
  12. Raise the AcquireRequestState event.
  13. Raise the PostAcquireRequestState event.
  14. Raise the PreRequestHandlerExecute event.
  15. Call the ProcessRequest method (or the asynchronous version IHttpAsyncHandler.BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.
  16. Raise the PostRequestHandlerExecute event.
  17. Raise the ReleaseRequestState event.
  18. Raise the PostReleaseRequestState event.
  19. Perform response filtering if the Filter property is defined.
  20. Raise the UpdateRequestCache event.
  21. Raise the PostUpdateRequestCache event.
  22. Raise the EndRequest event.
  23. Raise the PreSendRequestHeaders event.
  24. Raise the PreSendRequestContent event.
Programming is Easy….

ASP.NET MVC request lifecycle

All ASP.NET MVC application life cycle starts out like any other website application: with a request to a
URL.

Routing :- ASP.NET Routing framework is at the core of every ASP.NET MVC request.
In simple terms, ASP.NET routing is just a pattern-matching system. At startup,
the application registers one or more patterns with the framework’s route table to tell
the routing system what to do with any requests that match those patterns. When the
routing engine receives a request at runtime, it matches that request’s URL against the
URL patterns registered with it.

When the routing engine finds a matching pattern in its route table, it forwards the
request to the appropriate handler for that request.
Otherwise, when the request’s URL does not match any of the registered route patterns,
the routing engine indicates that it could not figure out how to handle the request by
returning a 404 HTTP status code.

Download/Save image from URL in

Once, I was working on the excel import functionality in one of my project. There was a image url field in excel file and i need to import all data and save image at specific location from given url. We can easily save/download image from a url as below, May be it can help you.

     
        public bool SaveImageFromUrl(string _prmStrFromImageUrl, string _prmStrSaveFilePath)
        {
            WebResponse _response = null;
            Stream _remoteStream = null;
            StreamReader _readStream = null;

            try
            {
                WebRequest _request = WebRequest.Create(_prmStrFromImageUrl);

                if (_request != null)
                {
                    _response = _request.GetResponse();

                    if (_response != null)
                    {
                        _remoteStream = _response.GetResponseStream();
                        string content_type = _response.Headers["Content-type"];
                        System.Drawing.Imaging.ImageFormat _imageType;

                        if (content_type == "image/jpeg" || content_type == "image/jpg")
                        {
                            _imageType = ImageFormat.Jpeg;
                        }
                        else if (content_type == "image/png")
                        {
                            _imageType = ImageFormat.Png;
                        }
                        else if (content_type == "image/gif")
                        {
                            _imageType = ImageFormat.Gif;
                        }
                        else
                        {
                            return false;
                        }

                        _readStream = new StreamReader(_remoteStream);
                        System.Drawing.Image img = System.Drawing.Image.FromStream(_remoteStream);

                        if (img == null)
                            return false;

                        //Save Image
                        img.Save(_prmStrSaveFilePath, _imageType);
                        img.Dispose();
                    }
                }
            }

            finally
            {
                //Clean Up objects
                if (_response != null) _response.Close();
                if (_remoteStream != null) _remoteStream.Close();
                if (_readStream != null) _readStream.Close();
            }

            return true;
        }