Wednesday, July 24, 2013

ASP.NET Page Life Cycle

In this article I’ll talk about the ASP.NET page life cycle. We will try to see what all events are important for an ASP.NET developer and what can be achieved in these events.
As an ASP.NET developer, it is essential to understand the ASP.NET application life cycle and Page life cycle. With the ease of development provided by Visual Studio, sometimes new programmers get started with writing ASP.NET pages without understanding the Application and Page life cycle.


From an end user's perspective, a request for a web page is made to the web server and web server will return the page to the user. So simple isn’t it J

However for a little bit technical users, we can also state that the web server will receive the request, perform some server side activities like reading from database, process data received and return the output back to the user.
As an ASP.NET developer, one need to understand how this request is being processed i.e. the Application life cycle and how the web page is being processed and getting served to the user i.e. the Page life cycle.

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps.
Steps like; initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering.
It is important for you to understand the page life cycle so that you can write code better and at the appropriate stage of life-cycle for the effect you intend.

Let’s see Page life cycle stages 


















Stage
Description
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 (therefore beginning the life of a page), 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 IsValid property 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 as Response and Request are unloaded and cleanup is performed.

As I was said earlier; it is important for an ASP.NET developer and what can be achieved in these events, similarly we also need to understand in which event or stage of life cycle what is available to us.
For example ViewState is available in which all events or stages of a life cycle – see below image.
















We can find list of all events available in Page Lifecycle at Microsoft MSDN Library


When we use server controls on ASP.net Page, we do not care about the individual controls life cycle – Yes each individual server control has its own life cycle which is similar to the page lifecycle.
For example: each control’s Init and Load event occurs during the corresponding page events

Below image can show you the flow of page life cycle – for detail information click here (reference of Microsoft MSDN Library)



































You can refer below links for more information on Lifecycle

Hope next time when you will be writing your code you will consider page lifecycle J


Friday, May 31, 2013

ASP.NET Impersonation


ASP.NET Impersonation controls the application identity of Web application.
This is a security element
This element can be declared at any level (machine, site, application, subdirectory, or page).
Impersonation is disabled by default.

Impersonation is disabled. This is the default setting. For backward compatibility with ASP, you must enable impersonation and change the ASP.NET process identity to use the Local System account. In this instance, the ASP.NET thread runs using the process token of the application worker process regardless of which combination of IIS and ASP.NET authentication is used. By default, the process identity of the application worker process is the ASPNET account. For more information, see ASP.NET Process Identity.
<identity impersonate="false" />
Impersonation enabled. In this instance, ASP.NET impersonates the token passed to it by IIS, which is either an authenticated user or the anonymous Internet user account (IUSR_machinename).
<identity impersonate="true" />

Impersonation enabled for a specific identity. Above example is to impersonate a specific user for all the requests on all pages of an ASP.NET application, you can specify the userName and password attributes in the <identity> tag of the Web.config file for that application. For example

<identity impersonate="true"
          userName="domain\user" 
          password="password" />

However sometimes this is risky to impersonate any user to your sites, especially when your application is embedded in SharePoint sites. Because if you do so; then all users who logs in to the SharePoint site will be treated as impersonated user which you have mentioned in the identity element.

For example: if you have a system account used in identity element of a SharePoint site, then after any log in to site, user will be considered as System Account only, hence user will get full access to your site.











Since we cannot add all users in Web.config based on their access rights. To avoid such scenario, we can authenticate logged in users programmatically.

Below is the small example in C# to authenticate user programmatically
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

\\Insert your code that runs under the security context of the authenticating user here.

impersonationContext.Undo();



Thursday, March 28, 2013

Excel VBA (Visual BASIC for Applications)


Excel VBA also known as Macros.
Now a day’s office programs are playing very vital part in our work and personal life.

We do use almost all office programs in our daily routine like Work, Excel, PowerPoint, and Outlook.
So by using these programs we prepare lots of documents, presentations, huge excel files with so complicated formulas to achieve what we want.

However, still sometimes we are unable to achieve few things even by using complex Excel Formulas and to achieve those we spend lots of our time.
Those are actually pretty much quick and easy to achieve by using macros.

What is macro?
A macro is a set of commands that can be run in the back to perform a given task with a single click. These tasks may be something as simple as calculating 2 numbers into a cell or more complex.
So you can automate almost everything in office program, even you can perform such task which you might not even know they are possible.

So when we speak about the macros, people thing that it’s a programming and I am not from programming background or a developer to write fine macros.
Well pal you are not 100% right, but yes you are partially right MACROS are programming, but you do not need to be from programming background or a developer to use them.

Macros can be created in office programs and they are written in a language called Microsoft Visual Basic for Applications, usually know as VBA.

When and why we should use macros?
Macros save time and extend capabilities of the programs you use every day. You can use them to automate document production tasks, simplify bulky tasks. When you will be well-versed with VBA can use macros to create your own add-ins that can include templates, dialog boxes, and even store information for frequent use.

Let’s take an example: For formatting multiple tables in a document. Let’s say that there are 50 tables in your document that need to be reformatted.
Even as a proficient user will take more than four hours for that one task but you can take just five minutes to format each table, that is. If you record a macro to format the tables and then edit that macro to repeat the changes throughout the document, you can complete that task in minutes rather than hours.

How to created macros?
In many Office programs, you can create a macro either by recording a series of actions or by writing the macro by yourself.

Record Macro
This is the simplest way to create macro, just turn tape recorder on (or off) while you are performing your actions.
When you use macro recorder, a macro is automatically written for you based on the actions you take.

In Office, you can record macros in Word, Excel, PowerPoint, Visio, and Project. I know it is exiting for you are you are ready to kick start.


For example, let’s take a look at recording a macro for the first task as I mentioned at the beginning of article - formatting several tables in a Word document. You can apply a table style to accomplish a lot of table formatting, but you might also need to apply formatting that cannot be part of a style, such as the width of the tables or the height of table rows.

Let’s begin J

To record this macro, start with your insertion point in the first table you want to format, and then do the following:
  • Office 2003 - On the Tools menu; click Macro and then click Record New Macro.
  • Office 2007 onwards – ON Developer tab click Record New Macro.
  • In the Record Macro dialog box, as shown here, you can name the macro, assign it to a toolbar or keyboard shortcut for easy access, customize where the macro is saved, and add a description of the macro for later reference. Or, if you prefer, you can skip all of those steps for now and just click OK to begin recording.













  1. You can rename the automatically assigned numeric name for your macro. Macro names can include letters and numbers, but no spaces.
  2. By default, new macros you record are saved in the global template named Normal.dot. You can also save the macro in the active document or template, or in another custom template.
  3. You can assign a macro to be accessible from a toolbar or with a keyboard shortcut. If you skip this part, you can make these assignments anytime after creating the macro.
  4. The macro description includes the date and name of the user who is recording the macro. You can edit this description as needed.

After you click OK, in office 2003 a small toolbar will open containing two buttons, Stop Recording  and Pause Recording.
In office 2007 onwards we will get both these button in Developer tab


  • Take each of the steps you need to format your table. For example, you might apply a table style, set the width of the table to be 50% of the available page width, select the table, and then remove row height settings from all table rows. When you have finished applying any formatting that will be the same for all of the tables that you need to format, click the Stop Recording button.
  • You can now click into any table in your document and then run this macro to automatically repeat all of the actions you took in the first table.

Note we have not assigned the macro to a toolbar or keyboard shortcut, you can access it through the Macros dialog box.
To do this
In office 2003 on the Tools menu, click Macro and then click Macros. Select your macro from the Macro name list and then click Run.
In office 2007 onwards, on Developer tab click Macros. Select your macro from the Macro name list and then click Run.

That’s it you have created your first macro and its quick a simple and fun too.

So let’s now start creating macro by other way, writing our own macro.

Tip A good way to begin learning VBA is to record a macro and then look at the macro in the Visual Basic Editor.
To do this, in office 2003 on the Tools menu click Macro, and then click Macros. Select your recorded macro from the Macro name list and then click Edit.
In 2007 onwards do to Developer tab and click on Visual Basic button.

Well before we start writing macro just security information as macros can be harmful to you system in case in case they are written by someone else and you do not know the use of it.

What about macro security?
It is a fact that, while most macros are both harmless and helpful, macros are an important security issue. When created with malicious intentions, macros can contain destructive code that causes harm to your documents or your system.

To protect your system and your files, do not enable macros from unknown sources. In order to have the option to enable or disable macros, but still have access to any macros you want to use, set macro security in your Office programs to Medium. This will provide you with the option to enable or disable macros anytime you open a file that contains a macro, but will allow you to run any macros you choose.

To set macro security in any Office program that offers VBA macros follow below steps
In Office 2003

  • On the Tools menu click Macro
  • Click Security
  • Select your preferred Security Level and then click OK.
Note that setting security to Low is not recommended.

In Office 2007 onwards

  • On the Developer tab click Macro Security
  • Select your preferred Security Level and then click OK.


So to begin with simple macro, we can open excel and write below code in macro editor (Visual Basic Editor).
To open macro
In office 2003 – Click on Tools, then select Visual Basic.
In office 2007 onwards – go to Developer tab and click Visual Basic.

This example will show Hello World text in cell A1.


Sub Macro1()
    'Showing “hello world” text in A1 cell
    Range("A1").Value = "Hello World :)"
End Sub


Another very simple addition of 2 numbers calculation using macros


Sub Macro1()
    'Adding 2 numbers to cell C1
    Range("C1").Value = Range("A1").Value + Range("B1").Value
End Sub


So similarly you can write your own macros and run them, you can also assign them to buttons and then you are just a click away from a magic.

The simplest way is to add buttons from the Forms Toolbar - display this from the View Menu > Toolbars & click Forms.

  1. Click on the Button icon on the menu & the cursor will hang to +, click on the sheet to add a button
  2. The Assign Macro Dialog will show listing available macros, in the "Macros in:" box select This Workbook for ease.
  3. Now simply click on a macro to assign it.

I will show you more complex macros and more tips in my next article.

Till then enjoy MACROS.