Tuesday, October 28, 2008

A Glass of Water

Create an illustration of a glass of water with lemon – from scratch, in Photoshop, with medium skills.

This tutorial will teach you how you can use basic shapes to create eye-catching illustrations and how to use gradients and different shades of the same color to create the illusion of depth. Learn simple trick that can help you add realism to your illustrations.

Click on the image to see the final version.










1. Create a new document: Ctrl + N – at 1000 x 1000 pixels. Hit G to select your gradient tool and choose a light blue for the foreground color (#edf8fc) and a slightly darker one for the background color (#ccedf9). With the gradient on linear, drag diagonally from the upper right corner to the lower left corner.

2. Make a new layer. With the Elliptical marquee tool, make a circle that’s fairly large. Pick your gradient tool again. Select a very light color for the foreground (#f9fcfe) and a light gray for the background (#e5ecef). With your selection still active, make a gradient diagonally in the same direction as before. Deselect. Rename your layer “Rim” – this will make the rim of your glass. Then, click on the layer, hold Shift and click on the Background layer. With your Move tool active, center the two layers by clicking these icons:

What this does is it positions the circle in the middle of your canvas.
You should have something very similar to this:

3. Ctrl + click on the Rim layer’s thumbnail to select the non-transparent pixels. Go to Select > Modify > Contract and type in 20 pixels. Hit Ok. Make a new layer and pick the gradient tool. Set your foreground color to #e7eef1 and your background color to #ebf7fd and make a gradient diagonally just like before. Rename the layer “Glass walls”.

Note: what’s the logic behind the choice of shades? When you made the first gradient, you set up also a light direction: the top right corner. Therefore, the top right corner of the glass rim will get the most light, while the top right visible portion of the glass walls will be shaded (it is on the inside), and the opposite will be lighter. (Btw, to make life easier, we’ll consider our glass to be frosted, not transparent).

4. On a new layer which you can name “Bottom”, create a new circle. Make it about 300 px in diameter, but you don’t have to be precise with this. Set #dde9ee for the foreground color and #e0f0f6 for the background color and make a gradient just like before. Deselect. Then, click on the layer Bottom, hold Shift and click on the Background layer. With your Move tool active, align the two layers just like you did at step 1.
Back on the Bottom layer, hit Ctrl + J to duplicate it. Then hit Ctrl + T to bring up the control transforms and hold Shift and Alt while dragging from any corner to make the circle slightly smaller. Then, set the layer’s blending mode to Multiply and its Opacity to 20%.

5. Let’s add water. Make a new layer and create a circle that’s larger than the Bottom layer but smaller than the Glass walls layer. Name it Water. Set you foreground color to #e5f7fd and you background color to # f0fafd and fill the circle with a gradient on diagonal like before. Deselect and then set the layer’s blending mode to Multiply.

6. Let’s add some variations of hues to the water so it won’t appear so “flat”. Ctrl + click on the Water layer to select its pixels. Ten create a new layer above it. Name it “Waves”. Pick the brush tool and choose a large hard-edged brush. Draw lines by holding Shift while you paint. You don’t need to be precise with this step. Use different shades of blue.

When you’re done covering the circle, don’t deselect yet. Go to Filter > Liquify and pick a large brush. Select the Twirl Clockwise tool and drag around the surface until you distort the straight lines to make them look wavy. Hit Ok. Now, hit Ctrl + Shift + I to invert your selection and hit Delete to get rid of the fringed edge around the circle. Now you can deselect.

Lower the opacity of the layer until it looks good to you (depending on what colors you used). You can also switch the blending mode to Multiply. I used 5% for opacity.

7. Let’s create the shadow. Make a new layer and call it Shadow. With the Elliptical Marquee, make an ellipse and rotate it to go around the bottom circle, like below. Use Select > Transform Selection to rotate the ellipse. Set your foreground color to a very light gray (#ececed) and your background color to white. Fill the ellipse with a gradient diagonally just like before. Deselect and set the blending mode to Multiply.

Let’s fade the shadow a little more: add a layer mask to the Shadow layer (click on the third icon from the left at the bottom of the layers palette). Hit D to set your colors to black and white, then X to invert them, then with the gradient tool drag as indicated by the arrow below (or experiment until you lose the hard edge of the shadow in the bottom-left corner).

8. Let’s add bubbles. Make a new folder and call it Bubbles. Create a new layer inside the folder and create a small circle on it. Fill it with white, but switch the Fill to 0% in the Layers palette properties. Then, double click the layer to get to the Layer Style and fill in the settings below:

Duplicate your bubble layer a couple of times, and change its size… Place a couple of bubbles in the water like below.

9. Let’s make a straw. Create a new folder in your Layers palette and call it Straw. Make a new layer inside the folder. Create a thin white rectangle like in the picture below:

Ctrl + J to duplicate the rectangle layer. Change its color to a bright saturated red (Ctrl + click on the layer thumb to select the pixels, then fill the selection with red.) Then, hit Ctrl + T and make the red rectangle thinner. Then, duplicate the red stripe and place them like below:

Back on the white rectangle, double click it to bring up the Layer Style and click on the Gradient Overlay. Apply a gradient at 0 degrees angle, from a very light gray to white.

Now, select the three layers in the Straw folder and hit Ctrl + E to merge them. Let’s shape the straw – hit Ctrl + T to bring up the transform controls. Right-click and choose Skew from the contextual menu. Adjust the ends to give some perspective, until your straw looks like below:

Make a small elliptical selection at the top end, invert the selection (Ctrl + Shift + I), and, with the eraser tool, delete the top of the straw. This will make it look round. Then, at the large end, make a larger ellipse (the diameter should be the width of the straw at its largest end). Don’t forget, if you don’t get the selection right from the first try, you can use Select > Transform Selection to adjust it. Make a new layer on top of the straw layer. Fill the selection with a light gray (#c7c7c7). Make a new layer on top of this and create a small rectangle that you can fill with a slightly darker red than the one used for the stripes. Center it with the ellipse from the layer below. Then, slightly skew the red rectangle to give it some perspective (like you did with the straw a few minutes ago). Zoom in to make more precise adjustments.

Then, Ctrl + click on the circle layer’s thumbnail in the Layers palette to select its pixels. Move back to the small rectangle’s layer and invert the selection, then press Delete to get rid of the extra pixels. Now, you can merge the small red rectangle with the circle layer. Name the new layer Hole.



Now, link the hole layer with the straw layer and rotate them to position them like below.



10. Let’s integrate the straw better with our environment. Make a new layer on top of the Hole layer. Create an elliptical selection over the right side – and try to make it parallel with the shadow cast by the glass. Look at the picture below for reference.



Then, hold Ctrl + Alt + Shift and click on the Hole layer’s thumbnail in the Layers palette. This will intersect your selection with the visible pixels in the Hole layer. Still on the new layer, fill the selection with #aeadad, then switch the blending mode to Multiply and the opacity to 20%. Name the layer “Shade”.



Select the Straw group in the layer palette and add a layer mask to it. We will use this to make the straw look like it comes out of the water in the glass.



Select the transparent pixels in the Water layer (Ctrl + click on the thumb). Make sure you are on the mask of the Straw folder and fill in the selection with #b7b7b7. Deselect. Now let’s make the straw look like it’s coming out of the water: we’ll “cut” a hole in the water. Make a small circular selection over the straw like below:



Make sure you are on the Straw mask and fill in the selection with white. But don’t deselect yet: we’ll need this exact selection later, so we’ll save it. Make a layer in the Straw folder and name it Circle Reserve. Fill the selection with any color, then click on the eye icon to switch the visibility off.
Then, Ctrl + click on the Straw layer’s thumb to select its pixels, then back in the Straw mask, pick a small hard-edged brush and paint with white to cover the area between the circle you did earlier and the edge of the glass. This is what you should have so far:



Now let’s make use of the selection we saved earlier. Make a new layer on top of Shade. Name it “Ripple”. Then Ctrl + click on the thumb of the Circle Reserve layer (it works when hidden too). Stay in the Ripple layer and apply a 2 px white stroke. (Edit > Stroke). Deselect. Apply Motion Blur at 0 degrees on a distance of 7 pixels. Then delete the part of the circle that overlaps the part of the straw that is out of the water. (Use the Eraser).



11. Let’s add a few subtle reflections: one at the water edge and one at the bottom of the glass. Select the Water layer and duplicate it (Ctrl + J). Move the duplicated layer a little up and a little to the right, like below:



Ctrl + click on the Water layer’s thumb to select the visible pixels. Then, hold down the Alt key and click on the Water copy layer’s thumb. This will exclude the overlapping areas. Keep the selection active. You can delete the Water copy layer. Then, make a new layer above the Water layer and call it Reflection 1. Fill it with white and switch the Fill to 0%. You can deselect. Then double click the layer to bring up the Layer Styles, chose Gradient Overlay and use the settings below.





Note that the first slider is white and the opacity slider above it is set at 0%. Just play around with the sliders until you get a similar result as in the image below.
Using the same procedure, create another reflection based on the Bottom layer instead of water this time. Copy the layer style of the Reflection 1 layer and paste it on the new reflection.
Tip: if you cannot see the copy of the Bottom layer (because it’s the same color), hit Ctrl + I to invert the color. You will delete the layer afterwards anyway.



12. Let’s add a slice of lemon. Use this great tutorial from PSDTuts to create a slice of lemon, or create the circle and then cut it in half. Create the lemon slice in a separate document, then save a flat copy on a transparent background and drag it in your glass-of-water document. Place the lemon slice right under the Bubble folder in the Layers palette. Switch the opacity to 90% so it looks like it’s submerged.



The only problem now is that the straw shows over the lemon slice. We can fix this easily though: Ctrl + click on the Lemon layer’s thumb to select its pixels. Then click on the layer mask of the Straw group and fill the selection with black. This will make the straw invisible where it overlaps the lemon.



Let’s make a reflection of the lemon too: duplicate the lemon layer and name it Lemon reflection. Place it under the Lemon layer, rotate it and move it more to the left, as below. Then apply gaussian Blur with a radius of 5 px and change the Opacity of the layer to 20%. Then, add a layer mask to the Lemon Reflection layer. Next, go to the Straw layer and select the transparent pixels (Ctrl + click on the thumb). Go back to the mask you have just created and fill it in with black.



You can save your work because you’re done. Enjoy your refreshing drink!

Monday, October 27, 2008

How Google Adwords works

How Google Adwords works

Adwords is a trademarked name for Google's online keyword based advertisement system. Adwords also refers to the Keywords "taken" by the advertiser for the campaign. Taking the above example, the keywords "monitor," "Keyboard," and "mouse" are called the Adwords. When a Google user searches on Google by typing in this keywords - which you as the advertiser have chosen - the ad appears on the right hand side (or the top) of the result page, alongside the generic Web search results on the left. The placement of the ads depends upon the cost per click and also according to the relevance of the keyword to your ads, as explained before. Ebay, for example, has purchase hundred of fast-moving consumer keywords such as "mobile", "phone", "laptop", "ipod", and so on, so that when a potential user types in this keywords, he sees eBay.in (or ebay.com) in the sponsored links. Since eBay also set a higher price for many of the keywords it has purchased (highest cost per click), eBay ads are displayed first in the sponsored ads section.

Remeber that even if your site is listed in the organic link section, there is no guarantee that it will be listed in the first few search results. The web links could be in one of the gazillions of pages of the search results!

Sponsored Links have the name of the ads as the title followed with a very brief synopsis of the sponsored site. The title and synopsis of the ad is set by the advertiser. This is follwed with the address to the website, which, again, is set by the advertiser.

The advertiser here has more control of the ad because he can project certain ads to only certain geographic locations, or by only certain languages, allowing him to precisely control ad spending. Adswords offer more value for money because the adverstiser gets charged only when the user clicks the sposered link. To know more, visit https://adwords.google.com. and watch this video:



Building Adwords

There are two ways to sign up for Adwords, depending on the type of advertising campaign you are planning.


Choose the right edition


Location and Language_Starter

understand interface with a simplified sign-up process to advertise a single product or business. An advertiser can choose one or many keywords relating to his ad. Basic reporting like the number of clicks that was registered for the ad, the number of ads that were displayed for that keyword (the impressions), and the cost incurred due to clciks to advertisers advertisement are shown on this edition. One can also taget ads to a city, country or even by language in this edition.

Write Ad Here

This edition also has the templates that assist one in building the ad, by asking a few simple questions. Step-by-Step procedures allow the advertiser to get tips on what keywords should be selected.

Keywords

You fix your monthly budget and pay google in your local currency. The more you spend for the keyword, the ad will be displayed more often with higher ad positioning wheb the keyword is typed in to the search engine. This is bidding process: ads of the highest- qouted keywords are dislayed more often, with higher paid positioning.


Adwords Standard Edition has all the features of Starter Edition with a lot more tools. Here ads, can be targeted to multiple regions at once, whereas in the Stater Edition, it is only for one region or one language.


Budgeting your ad spend

When it comes to the pricing of the keywords, you have more options than with that of Starter Edition. Here, you have options of setting the price for each keywords, giving you, the advertiser, more control of how the ad money is spent, and proper strategy for the ad. For example, for the keywords we mentioned, you can select "keyboard" to be at higher price per click than the rest, thus having the ad displayed more often for "keyboard."

The content that goes as the brief description for the ad can also be bif for in this edition, where the higher bidder for keywords can display a certain set of words relating to the ad.

The placement of the ads - such as second position, also called position preference, can be done with the Standard Edition.

Adwords Standard Edition allows you to have multiple products with multiple ad campaigns, with each campaign having many keywords - and each one of these campaigns can runs simuntaneously. For example, Tata, a diversified company, has multiple products and each product has multiple ads for the different regions. The configurationfor such a scenario can be done at the second page.

Standard Edition also provides:
  • Extensive reports of impressions (numver of ads that were displayed for the keywords)
  • Number of times user clicked on your ads.
  • Statistics of impressions and click rates.
  • Billing of your ads, and custom report like the region where the most number of clicks were generated and the time of the clicks.
  • A graphical representation of the number of timeseach kewords was typed that month.
  • A traffic estimator that can estimate the traffic of certain keywords. It gives you an estimate as to when a paticular keyword search was more, like the time of a month or a month of a year.
  • Keywords tips so as to make the ads pop up more often.
  • An option to get the statistics of keywords, so that you can understand which keyword was use more often in the set of keywords that you chose - allowing you a stratagic and plan keywords more effectively.
  • Hints on relevent sites here ads can be placed through adsense, so as to increase traffic to your site.)
Hope you understand how to setup account to advertise online with Google adwords.
Get you Free Adwords ebook here

Basic of GDI+ and Graphics in ASP.NET

Introduction

In this article, I will explain about GDI+ in .NET Framework. If you haven't heard about GDI+, then GDI+ is a set of classes in .NET framework that deal with graphics. You can use GDI+ to draw custom drawing on the screen. GDI provides a layer of abstraction, hiding the differences between different video cards.

You simply need to call the Windows API function to do the specific task, and internally the GDI figures out how to get to the client's particular video card to do whatever that you want.

Although GDI exposes a relatively high level API to developers, it is still an API that based on the old Windows API with C style functions. GDI+ sits as a layer between GDI and your application providing more intuitive and inheritance based object model.

GDI+ is generally considered a Windows technology. However, some of the new GDI+ features make this technology an excellent choice for Web applications, enabling developers to generate images, graphs, diagrams, and much more.

Drawing Shapes with GDI+ in ASP.NET

In this example below, we will try to draw some simple rectangle and ellipse using GDI+ in ASP.NET
Start by Adding new ASPX page and named it Image.aspx. Add reference to System.Drawing and System.Drawing.Imaging. Paste the code below to your Page_Load Event.

Bitmap bmp = new Bitmap(100, 300);

Graphics dc = Graphics.FromImage(bmp);
Pen bluePen = new Pen(Color.Blue, 3);
dc.DrawRectangle(bluePen, 0, 0, 50, 50);

Pen redPen = new Pen(Color.Red, 2);
dc.DrawEllipse(redPen, 0, 50, 80, 60);
Response.ContentType = "image/gif";
bmp.Save(Response.OutputStream, ImageFormat.Gif);

In the code above, you can see that you draw a rectangle at cordinates(0,0) and with the width and height of 50.
For the Ellipse, we draw it at cordinates(0,50) and the width 80 and height 50. Note that coordinates(x,y) translates to x pixels to the right and y pixels down from the top-left corner of the images

When you try to view the page, you can see that the output of the page is an image. And if you try to add some code in the Aspx page such as Header "This is my image". You won't be able to see that in the browser. The reason is because we set the Response.OutputStream to ImageFormat.Gif.

To fix this, just create new aspx page and named it Test.aspx
After that add the following code
This is my image

<BR>
<img src="Image.aspx" />

Drawing String with GDI+ and ASP.NET

Have you ever wondered when you try to view someone else page, they actually write down the emailaddress in image format to prevent spam from robots.
Nah, in the example below, I will show you how to do that


Image.aspx

Bitmap bmp = new Bitmap(300, 30);

Graphics dc = Graphics.FromImage(bmp);
Font f = new Font("Verdana", 11);
dc.DrawString("myemail@mydomainname.com", f, Brushes.Yellow, 0, 0);
bmp.Save(Response.OutputStream, ImageFormat.Gif);

Test.aspx
 Please email me at

<BR />
<IMG src="Image.aspx" />

Output

Pretty Easy right. Now you can start doing this for your website. So rather than showing your email addresses as text, you can change it to image. This will prevent your email address being spam by web robot.

Creating Captcha using GDI+ and ASP.NET

If you haven't heard about Captcha, then probably I can explain a bit about that. Have you seen in most of the websites especially forums or Registration form, there is a small images showing some text and you need to verify the text before you can actually register. Nah, that is called as Captcha image.

The purpose of the Captcha is to defeat the robots from submitting to the form automatically.

In the code below, I will show you how

 Random Rand = new Random();

// Create a new random number between the specified range
int iNum= Rand.Next(10000, 99999);
Bitmap Bmp = new Bitmap(90, 50);
Graphics gfx = Graphics.FromImage(Bmp);
Font fnt = new Font("Verdana", 12);

// Draw the random number
gfx.DrawString(RandNum.ToString(), fnt, Brushes.Yellow, 15, 15);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);


This is all the code we need. A random number between 10000 and 99999 is generated and displayed as a graphic so robots can't pass it.

Now you would only need a text box where the visitor should type the number and a few lines of code to compare it with the random value inside iNum.

Technology is getting more advanced from days to days and so are the spammer. Now, there are smart robots actually can read the text from the images by using character recognition. We can actually try to make things harder for them to break. We can add few lines into the images to fool the robot.

 Random Rand = new Random();

int iNum = Rand.Next(10000, 99999);
Bitmap Bmp = new Bitmap(90, 50);
Graphics Gfx = Graphics.FromImage(Bmp);
Font Fnt = new Font("Verdana", 12, FontStyle.Bold);
Gfx.DrawString(iNum.ToString(), Fnt, Brushes.Yellow, 15, 15);
// Create random numbers for the first line
int RandY1 = Rand.Next(0, 50);
int RandY2 = Rand.Next(0, 50);

// Draw the first line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
// Create random numbers for the second line
RandY1 = Rand.Next(0, 50);
RandY2 = Rand.Next(0, 50);
// Draw the second line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
Session["Number"] = iNum;


From the image above, you can see that we as human can still read the image. However robot might have some difficulties on reading it. It is up to your imagination really, how you can fool the robots. You can draw some dots, rectangle and etc.

Now, for the aspx part.
<SCRIPT RUNAT=server>

protected void Button1_Click(object sender, EventArgs e)
{
if (txtNumber.Text.Trim() == Session["Number"].ToString().Trim())
{
Response.Write("Match");
}
else
{
Response.Write("Not Match");
}
}
SCRIPT>
<BODY>
<FORM ID="form1" RUNAT="server">
<DIV>
<BR />
<IMG src="Default.aspx" />
<BR />
Please Enter the Image number
<ASP:TEXTBOX ID="txtNumber" RUNAT="server">ASP:TEXTBOX>DIV>
<ASP:BUTTON ID="Button1" RUNAT="server" TEXT="Button" ONCLICK="Button1_Click" />
FORM>
BODY>

As you can see we store the random numbers in Session variables. Then on your page, we just compare the Session variables with the input that the users provide, If it match then we can make sure that the form is not filled by the robots, and you can proceed to the next step.

Conclusion

GDI+ is a powerful set of classes that dealing with graphics and it is impossible to discuss all the powerful features here. Microsoft has provides lots of methods and properties in GDI+ that you can use and actually the only limit is your imagination. Happy GDI ing

Download Source Code

ASP.NET HTTP Modules:

HTTP Modules:

HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to needs like authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching....

HTTP Modules are activated/called/invoked before and after HTTP Handler execution.

HTTP Modules are integral part of ASP.NET framework now and heavily being used as it cater grips upon request and let developers to generate response in a customized way, according to user requirement. Web development is all about playing with request from client to server and response from server to client.

When any request goes to web server, request passes through different phases and then at last response gets generate for client.

HTTP Modules are .Net based components/Plugins and programmed by implementing System.Web.IHTTPModule interface of .Net.

HTTP Module Background:

Before HTTP Modules, web developers/programmers used to implement Internet Server Application Programming Interface (ISAPI) Filters like me (wish interviewer asked me about by terms of ISAPI at that time then I tell him (:D)), anyhow jokes apart.

As name implies ISAPI is a web server based API and used to manage request which comes to web server and generate response. ISAPI based upon web server (IIS) where as NSAPI is Netscape based web server API.

ISAPI is based upon win32 DLL and programmed in unmanaged code C/C++, which is somehow painful (:$) and due to unmanaged code, is less reliable, scalable and quite complex to implement than HTTP Modules by managed code under the framework of .Net. Hope you got it why ISAPI Filters replaced by HTTP Modules (;))

Asp.net requests goes through HTTP Modules events just like (oil flowing through pipeline and that pipeline has some filters to refine that oil)

HTTP Modules Events:

Every HTTP Module must implement following two methods of IHTTPModule interface:

Init: To register/initialize event handler to the events of HTTP Module for HTTP based application.

Dispose: To perform a clean up code means resource releasing, object removing from memory and such other resources releasing which used explicitly.

Following are list of events with their brief description:

BeginRequest: Event fired whenever any asp.net based request sent to web server. If you need to do perform at the beginning of a request for example, modify show banners, log HTTP Header information, Get/Set cultures, Response.Filter to generate response for browser according to your need.

AuthenticateRequest: If you want to check authentication of request that request comes from authenticated user or not means wants to implement custom authentication scheme. For example, look up a requested user credentials against a database to validate.

AuthorizeRequest: This method is used specifically to implement authorization mechanisms means authenticated user/request has what privileges/rights/access in that specific application for example, either user has access on all pages or not of that website or has write to create file or not or visit report pages and like this.

ResolveRequestCache: This event determines if a page served from the Output cache. If you want to write your own caching module (for example, build a file-based cache rather than a memory cache), synchronize this event to determine whether to serve the page from the cache.

AcquireRequestState: Session state is retrieved from the state store. If you want to build your own state management module, synchronize this event to grab the Session state from your state store.

PreRequestHandlerExecute: This event occurs before the HTTP handler is executed.

PostRequestHandlerExecute: This event occurs after the HTTP handler is executed.

ReleaseRequestState: Session state is stored back in the state store. If you are building a custom session state module, you must store your state back in your state store.

UpdateRequestCache: This event writes from output back to the Output cache. If you are building a custom cache module, you have to write the output back to your cache.

Error: this event always occurs when any exception (unhandled error occurs in application, this event specifically uses to handle or log error messages of that web application. (Heavily used in Error Logging Modules and Handlers (ELMAH) kind of applications). You can learn about ELMAH more from following link in detail: http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx

EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information on the page.

By above events list you must be getting wonder about difference between Global.asax as somehow events of Global.asax are pretty same, so let me tell you difference between Global.asax and HTTP Module (another common question asked in interviews)

But you need to register/initialize these Events explicitly in “Init” method; following is sample code of IHTTPModule implementation for couple of events.

using System;
using System.Web;
using System.Collections;

public class HelloWorldModule : IHttpModule
{
public String ModuleName
{
get { return "HelloWorldModule"; }
}

// In the Init function, register for HttpApplication
// events by adding your handlers.

public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));

}

// Your BeginRequest event handler.

private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("<h1>HelloWorldModule: Beginning of Request
"
);
}

// Your EndRequest event handler.

private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("<hr>

HelloWorldModule: End of Request

"
);
}
public void Dispose()
{
}
}

Ref: msdn

HTTP Module vs Global.asax

1. HTTP Module is pluggable component that’s why could be use for other web applications as well as on other server or in same server where as Global.asax couldn’t.

2. According to life cycle of Request, Request passed through HTTP Module first and then through Global.asax

3. Following are list of events which are supported in Global.asax but unfortunately not in HTTP Module.

  1. Application_OnStart
    This event is raised when the very first request passed through the web application.
  2. Application_OnEnd
    This event is raised just before the application is going to terminate.
  3. Session_OnStart
    This event is raised for the very first request of the user's session.
  4. Session_OnEnd
    This event is raised when the session is abandoned or expired.

Here I would like to share one more interview experience of me but now its about my friend’s interview, for which he did preparation from me/took my help or guidance for it Anyhow whilst I was helping him in his preparation for asp.net technical interview, I asked him: “ tell me when session starts?” He replied: “Simple when user logins from login page”, I said ok! Suppose site has no login page and could be accessible by anonymous user, session will never start and Session_OnStart event of Global.asax will never fire then is it? He replied: of course, I couldn’t stop me to smile; I might not laugh if he has no experience or less experience but he has more than 4 years of experience. Anyhow next day when he went for interview, interviewer asked him the same question and he smiled and said, “If you think I will say when user login session_Onstart event will fire then you are wrong. (They also started laughing).

Anyhow normally people say or according to books to tell reader in easy way that session are user based, NO! Sessions are actually browser based. Anyhow shouldn’t go away from topic as much.

Registering HTTP Module

The following is an example of registering/adding an HTTP module:

<httpModules>
<add type="ClassName, AssemblyName" name="ModuleName" />
<httpModules>

The following is a general example of removing an HTTP module from web application.

<httpModules>
<remove name="ModuleName" />
<httpModules>
All code suppose to be in either web.config or in machine.config

Following is the list of module is defined at machine.config or web.config by default. ($WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG\ CONFIG Files)

<httpModules>
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication" ="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/>
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/>
<add name="RoleManager" type="System.Web.Security.RoleManagerModule"/>
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/>
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/>
<add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/>
<add name="Profile" type="System.Web.Profile.ProfileModule"/>
<add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
httpModules>

Performance:

You can improve performance of your application by removing default (but not in used) HTTP Modules registered in machine.config file as these are activated/invoked/called on each request for your application unnecessarily by for example,

<httpModules>

<remove name="Session" />
<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
<remove name="OutputCache" />
<remove name="RoleManager" />
<remove name="Profile" />
<remove name="ErrorHandlerModule" />
<remove name="ServiceModel" />
httpModules>

But please make sure before its implementation/applying that you are not using them. If you are using any of these, you may exclude that from existing list.

Conclusion

HTTP Modules are quite simple to understand and quite flexible by means of its number of events. HTTP modules integrate with whole application and every request passed through HTTP Module. So HTTP Module should be implemented very carefully. Take the time to completely understand its advantages, disadvantages, implementation and concepts before implementing a solution.

To get more detailed understanding of HTTP Modules with real time examples implmentation, I would recommend you to visit following links:


Recommended Links:

For URL Redirection example click here

For Security based example click here

For IP based security example click here

For Error Manager Example click here

For Videos click here and here