Monday, December 29, 2008

CSS HACKS - how to add styles based on the browser version using css

Dealing with different browsers is always an issue to most of the web developers. sometimes there is no reasonable way to accomplish a desired layout in all major browsers without the use of some special exception rules for certain layout engines.

hacks necessarily lead to potentiial complications and should be avoided whenever possible, but when the circumstances require hacks to be used.it's best to know what your options are and weigh the consequences appropriately. The purpose of this article is to describe some of the CSS hacks, also called CSS filters, with the least significant potential consequences.

Conditional comments
Due to its relatively poor level of standards support, Internet Explorer tends to be the subject of most CSS hacks. Luckily, as of version 5, it deliberately supports a rather safe-to-use hack called "conditional comments". Conditional comments are specially constructed HTML comments that Internet Explorer on Windows may treat differently from other browsers, optionally based on IE's version number. They can cause Internet Explorer to ignore the markup between comments or to include part of a comment as if it was regular markup. Conditional comments apply specifically to browsers using Internet Explorer's Trident layout engine, meaning IE-based browsers like Maxthon and Avant handle them like Internet Explorer does while browsers using other layout engines see them simply as regular comments. Internet Explorer on the Mac uses a different layout engine and doesn't support conditional comments.

The most beneficial aspect of conditional comments is that you are not relying on browser bugs when using them. When you use CSS hacks that rely on browser bugs, you run into the possibility of those bugs being fixed at an unwanted time or other browsers showing the same bugs. Conditional comments only work in browsers that specifically support them and claim to be based on Internet Explorer, which in this case all known browsers are honest about.

There are two forms of conditional comments: positive and negative. A positive conditional comment will expose the included markup only to web browsers that match the condition (meaning only the selected versions of Internet Explorer). A negative conditional comment will expose the markup only to web browsers that don't match the condition (meaning all non-IE web browsers and any versions of IE that the condition didn't match). Note that, since versions of IE older than IE 5 don't support conditional comments, you may get unexpected results in those browsers.

Syntax
The syntax for conditional comments is as follows:

Positive
<!--[if condition]> HTML <![endif]-->
Negative
<!--[if !condition]><![IGNORE[--><![IGNORE[]]> HTML <!--<![endif]-->
condition is one of the following:

IE
Any version of IE
lt IE version
Versions less than version
lte IE version
Versions less than or equal to version
IE version
Only version version
gte IE version
Versions greater than or equal to version
gt IE version
Versions greater than version
version is the version of Internet Explorer, typically 5, 5.5, 6, or 7

HTML is the HTML to be included if the condition does or doesn't match, depending on the type of conditional comment. When included, the HTML is placed right where the conditional comment is in the source.

For negative conditions, <![IGNORE[--><![IGNORE[]]> can be replaced with --> if the condition is simply IE. The longer version is only needed when Internet Explorer might parse the contents.

The <![IGNORE[ ... ]]> directive is not available in XML, so it is illegal to use it in XHTML. A solution would be to split it up into two special conditional comments: <!--[if !condition]> XHTML <![endif]--> <!--[if !IE]>--> XHTML <!--<![endif]--> where XHTML is the same both places. Note that Internet Explorer 7 and below don't yet recognize XHTML as a form of XML, so this is merely forward-looking.

Fixing stand-alone versions of Internet Explorer
Internet Explorer was not designed to allow multiple versions to be installed at once, and Microsoft doesn't officially support any such configurations. If you use one of the hacked third party packages that attempts to do this, you will experience problems with version-specific conditional comments, among other things. This is because the different stand-alone copies still rely on a common centralized registry for certain data, including version information.

Although there is no simple way to cut through all of the issues with stand-alone versions of Internet Explorer, it is possible to force them to look elsewhere for their version information, thus fixing this issue with conditional comments. The trick is to remove the normal centralized version indicator. To do this, first open up regedit.exe from the "Run..." dialog. Navigate to HKEY_LOCAL_MACHINE/Software/Microsoft/Internet Explorer/Version Vector/ (If HKEY_LOCAL_MACHINE doesn't exist, try HKLM instead). In the right pane, you should see a row with a Name value of IE. Rename this by clicking on it and changing it to zIE (or anything unique and different). Restart Internet Explorer to see the effects. Now when it looks for the IE key for its version information, the key will be missing and it will be forced to determine the correct version number from its own module.

Stand-alone versions of Internet Explorer have a number of other issues, and it therefore may be better to instead use a separate virtual machine for each version of Internet Explorer to ensure that what you see is what your users will see. I recommend VMware Server, which is completely free of charge and fairly easy to set up.

Conditional comments as a CSS hack
Conditional comments can be used as a CSS hack by including links to stylesheets based on the layout engine. Here is an example of how stylesheets can be separated in this way:
<!CDATA[
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<link href="all_browsers.css" rel="stylesheet" type="text/css">
<!--[if IE]> <link href="ie_only.css" rel="stylesheet" type="text/css"> <![endif]-->
<!--[if lt IE 7]> <link href="ie_6_and_below.css" rel="stylesheet" type="text/css"> <![endif]-->
<!--[if !lt IE 7]><![IGNORE[--><![IGNORE[]]> <link href="recent.css" rel="stylesheet" type="text/css"> <!--<![endif]-->
<!--[if !IE]>--> <link href="not_ie.css" rel="stylesheet" type="text/css"> <!--<![endif]-->

In the above example, all_browsers.css applies to all browsers, ie_only.css only applies to all versions of Internet Explorer, ie_6_and_below.css applies to all versions of Internet Explorer below IE 7, recent.css applies to all browsers except IE versions below 7, and not_ie.css applies to all non-IE browsers.

See also: Conditional Comments of IE

some more info
The syntax I use is:

<p><!--[if IE]>
According to the conditional comment this is Internet Explorer<br />
<![endif]-->
<!--[if IE 5]>
According to the conditional comment this is Internet Explorer 5<br />
<![endif]-->
<!--[if IE 5.0]>
According to the conditional comment this is Internet Explorer 5.0<br />
<![endif]-->
<!--[if IE 5.5]>
According to the conditional comment this is Internet Explorer 5.5<br />
<![endif]-->
<!--[if IE 6]>
According to the conditional comment this is Internet Explorer 6<br />
<![endif]-->
<!--[if IE 7]>
According to the conditional comment this is Internet Explorer 7<br />
<![endif]-->
<!--[if gte IE 5]>
According to the conditional comment this is Internet Explorer 5 and up<br />
<![endif]-->
<!--[if lt IE 6]>
According to the conditional comment this is Internet Explorer lower than 6<br />
<![endif]-->
<!--[if lte IE 5.5]>
According to the conditional comment this is Internet Explorer lower or equal to 5.5<br />
<![endif]-->
<!--[if gt IE 6]>
According to the conditional comment this is Internet Explorer greater than 6<br />
<![endif]-->
</p>

CSS hack?
Are conditional comments CSS hacks? Strictly speaking, yes, since they can serve to give special style instructions to some browsers. However, they do not rely on one browser bug to solve another one, as all true CSS hacks do. Besides, they can be used for more than CSS hacks only (though that rarely happens).

Since conditional comments are not based on a browser hack but on a deliberate feature I believe they are safe to use. Sure, other browsers could implement conditional comments, too (though as yet none have done so), but they're unlikely to react to the specific query <!--[if IE]>.

I use conditional comments, though sparingly. First I see if I can find a real CSS solution to an Explorer Windows problem. If I can't, though, I don't hesitate to use them.

Comment tag
A reader told me Explorer (Windows and Mac) supports the (non-standard) <comment> tag.

<p>This is <comment>not</comment> Internet Explorer.</p>
This is Internet Explorer.

This tag might come in handily if you want to use tags or styles for all non-Explorer browsers. Unfortunately these situations are rather scarce, especially since both Explorer Windows and Mac support this tag and you usually want to serve special content or style to only one of them.

ASP.NET HACKS
http://wiki.lessthandot.com/index.php/ASP.NET_Hacks

Monday, December 8, 2008

Online Test Url

Attend Online Tests in the following urls.

http://www.thinkinterview.com/Interview-Questions/q108_Which-of-the-following-ways-can-you-proactively-clean-up-a-database-connect.aspx
http://www.allinterview.com/showanswers/20860.html
http://www.dotnetspider.com/questions/ViewInterviewQuestion.aspx?InterviewQuestionId=3707

More links:
http://www.devbistro.com/tech-interview-questions/.NET.jsp

SslStream Class

SslStream Class

Provides a stream used for client-server communication that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally the client.


Namespace: System.Net.Security
Assembly: System (in System.dll)
Syntax
Visual Basic (Declaration)
Public Class SslStream _
Inherits AuthenticatedStream
Visual Basic (Usage)
Dim instance As SslStream
C#
public class SslStream : AuthenticatedStream
Visual C++
public ref class SslStream : public AuthenticatedStream
JScript
public class SslStream extends AuthenticatedStream

Remarks
SSL protocols help to provide confidentiality and integrity checking for messages transmitted using an SslStream. An SSL connection, such as that provided by SslStream, should be used when communicating sensitive information between a client and a server. Using an SslStream helps to prevent anyone from reading and tampering with information while it is in transit on the network.

An SslStream instance transmits data using a stream that you supply when creating the SslStream. When you supply this underlying stream, you have the option to specify whether closing the SslStream also closes the underlying stream. Typically, the SslStream class is used with the TcpClient and TcpListener classes. The GetStream method provides a NetworkStream suitable for use with the SslStream class.

After creating an SslStream, the server and optionally, the client must be authenticated. The server must provide an X509 certificate that establishes proof of its identity and can request that the client also do so. Authentication must be performed before transmitting information using an SslStream. Clients initiate authentication using the synchronous AuthenticateAsClient methods, which block until the authentication completes, or the asynchronous BeginAuthenticateAsClient methods, which do not block waiting for the authentication to complete. Servers initiate authentication using the synchronous AuthenticateAsServer or asynchronous BeginAuthenticateAsServer methods. Both client and server must initiate the authentication.

The authentication is handled by the Security Support Provider (SSPI) channel provider. The client is given an opportunity to control validation of the server's certificate by specifying a RemoteCertificateValidationCallback delegate when creating an SslStream. The server can also control validation by supplying a RemoteCertificateValidationCallback delegate. The method referenced by the delegate includes the remote party's certificate and any errors SSPI encountered while validating the certificate. Note that if the server specifies a delegate, the delegate's method is invoked regardless of whether the server requested client authentication. If the server did not request client authentication, the server's delegate method receives a null certificate and an empty array of certificate errors.

If the server requires client authentication, the client must specify one or more certificates for authentication. If the client has more than one certificate, the client can provide a LocalCertificateSelectionCallback delegate to select the correct certificate for the server. The client's certificates must be located in the current user's "My" certificate store. Client authentication via certificates is not supported for the Ssl2 (SSL version 2) protocol.

If the authentication fails, you receive a AuthenticationException, and the SslStream is no longer useable. You should close this object and remove all references to it so that it can be collected by the garbage collector.

When the authentication process, also known as the SSL handshake, succeeds, the identity of the server (and optionally, the client) is established and the SslStream can be used by the client and server to exchange messages. Before sending or receiving information, the client and server should check the security services and levels provided by the SslStream to determine whether the protocol, algorithms, and strengths selected meet their requirements for integrity and confidentiality. If the current settings are not sufficient, the stream should be closed. You can check the security services provided by the SslStream using the IsEncrypted and IsSigned properties. The following table shows the elements that report the cryptographic settings used for authentication, encryption and data signing.

Element
Members

The security protocol used to authenticate the server and, optionally, the client.
The SslProtocol property and the associated SslProtocols enumeration.

The key exchange algorithm.
The KeyExchangeAlgorithm property and the associated ExchangeAlgorithmType enumeration.

The message integrity algorithm.
The HashAlgorithm property and the associated HashAlgorithmType enumeration.

The message confidentiality algorithm.
The CipherAlgorithm property and the associated CipherAlgorithmType enumeration.

The strengths of the selected algorithms.
The KeyExchangeStrength, HashStrength, and CipherStrength properties.


After a successful authentication, you can send data using the synchronous Write or asynchronous BeginWrite methods. You can receive data using the synchronous Read or asynchronous BeginRead methods.

If you specified to the SslStream that the underlying stream should be left open, you are responsible for closing that stream when you are done using it.

Note:
If the application that creates the SSLStream object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so.


Examples
The following code example demonstrates creating an TcpListener that uses the SslStream class to communicate with clients.

C# Copy Code
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
public sealed class SslTcpServer
{
static X509Certificate serverCertificate = null;
// The certificate parameter specifies the name of the file
// containing the machine certificate.
public static void RunServer(string certificate)
{
serverCertificate = X509Certificate.CreateFromCertFile(certificate);
// Create a TCP/IP (IPv4) socket and listen for incoming connections.
TcpListener listener = new TcpListener(IPAddress.Any, 8080);
listener.Start();
while (true)
{
Console.WriteLine("Waiting for a client to connect...");
// Application blocks while waiting for an incoming connection.
// Type CNTL-C to terminate the server.
TcpClient client = listener.AcceptTcpClient();
ProcessClient(client);
}
}
static void ProcessClient (TcpClient client)
{
// A client has connected. Create the
// SslStream using the client's network stream.
SslStream sslStream = new SslStream(
client.GetStream(), false);
// Authenticate the server but don't require the client to authenticate.
try
{
sslStream.AuthenticateAsServer(serverCertificate,
false, SslProtocols.Tls, true);
// Display the properties and settings for the authenticated stream.
DisplaySecurityLevel(sslStream);
DisplaySecurityServices(sslStream);
DisplayCertificateInformation(sslStream);
DisplayStreamProperties(sslStream);

// Set timeouts for the read and write to 5 seconds.
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
// Read a message from the client.
Console.WriteLine("Waiting for client message...");
string messageData = ReadMessage(sslStream);
Console.WriteLine("Received: {0}", messageData);

// Write a message to the client.
byte[] message = Encoding.UTF8.GetBytes("Hello from the server.");
Console.WriteLine("Sending hello message.");
sslStream.Write(message);
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine ("Authentication failed - closing the connection.");
sslStream.Close();
client.Close();
return;
}
finally
{
// The client stream will be closed with the sslStream
// because we specified this behavior when creating
// the sslStream.
sslStream.Close();
client.Close();
}
}
static string ReadMessage(SslStream sslStream)
{
// Read the message sent by the client.
// The client signals the end of the message using the
// "" marker.
byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
// Read the client's test message.
bytes = sslStream.Read(buffer, 0, buffer.Length);

// Use Decoder class to convert from bytes to UTF8
// in case a character spans two buffers.
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
decoder.GetChars(buffer, 0, bytes, chars,0);
messageData.Append (chars);
// Check for EOF or an empty message.
if (messageData.ToString().IndexOf("") != -1)
{
break;
}
} while (bytes !=0);

return messageData.ToString();
}
static void DisplaySecurityLevel(SslStream stream)
{
Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
Console.WriteLine("Protocol: {0}", stream.SslProtocol);
}
static void DisplaySecurityServices(SslStream stream)
{
Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
Console.WriteLine("IsSigned: {0}", stream.IsSigned);
Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
}
static void DisplayStreamProperties(SslStream stream)
{
Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
}
static void DisplayCertificateInformation(SslStream stream)
{
Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

X509Certificate localCertificate = stream.LocalCertificate;
if (stream.LocalCertificate != null)
{
Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
localCertificate.Subject,
localCertificate.GetEffectiveDateString(),
localCertificate.GetExpirationDateString());
} else
{
Console.WriteLine("Local certificate is null.");
}
// Display the properties of the client's certificate.
X509Certificate remoteCertificate = stream.RemoteCertificate;
if (stream.RemoteCertificate != null)
{
Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
remoteCertificate.Subject,
remoteCertificate.GetEffectiveDateString(),
remoteCertificate.GetExpirationDateString());
} else
{
Console.WriteLine("Remote certificate is null.");
}
}
private static void DisplayUsage()
{
Console.WriteLine("To start the server specify:");
Console.WriteLine("serverSync certificateFile.cer");
Environment.Exit(1);
}
public static int Main(string[] args)
{
string certificate = null;
if (args == null ||args.Length < 1 )
{
DisplayUsage();
}
certificate = args[0];
SslTcpServer.RunServer (certificate);
return 0;
}
}
}

Url Rewriting with ASP.NET

Url Rewriting with ASP.NET
People often ask me for guidance on how they can dynamically "re-write" URLs and/or have the ability to publish cleaner URL end-points within their ASP.NET web applications. This blog post summarizes a few approaches you can take to cleanly map or rewrite URLs with ASP.NET, and have the option to structure the URLs of your application however you want.
Why does URL mapping and rewriting matter?
The most common scenarios where developers want greater flexibility with URLs are:
1) Handling cases where you want to restructure the pages within your web application, and you want to ensure that people who have bookmarked old URLs don't break when you move pages around. Url-rewriting enables you to transparently forward requests to the new page location without breaking browsers.
2) Improving the search relevancy of pages on your site with search engines like Google, Yahoo and Live. Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites, which can often increase the chance of someone clicking your link. Moving from using querystring arguments to instead use fully qualified URL's can also in some cases increase your priority in search engine results. Using techniques that force referring links to use the same case and URL entrypoint (for example: weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) can also avoid diluting your pagerank across multiple URLs, and increase your search results.
In a world where search engines increasingly drive traffic to sites, extracting any little improvement in your page ranking can yield very good ROI to your business. Increasingly this is driving developers to use URL-Rewriting and other SEO (search engine optimization) techniques to optimize sites (note that SEO is a fast moving space, and the recommendations for increasing your search relevancy evolve monthly). For a list of some good search engine optimization suggestions, I'd recommend reading the SSW Rules to Better Google Rankings, as well as MarketPosition's article on how URLs can affect top search engine ranking.
Sample URL Rewriting Scenario
For the purpose of this blog post, I'm going to assume we are building a set of e-commerce catalog pages within an application, and that the products are organized by categories (for example: books, videos, CDs, DVDs, etc).
Let's assume that we initially have a page called "Products.aspx" that takes a category name as a querystring argument, and filters the products accordingly. The corresponding URLs to this Products.aspx page look like this:
http://www.store.com/products.aspx?category=bookshttp://www.store.com/products.aspx?category=DVDshttp://www.store.com/products.aspx?category=CDs
Rather than use a querystring to expose each category, we want to modify the application so that each product category looks like a unique URL to a search engine, and has the category keyword embedded in the actual URL (and not as a querystring argument). We'll spend the rest of this blog post going over 4 different approaches that we could take to achieve this.
Approach 1: Use Request.PathInfo Parameters Instead of QueryStrings
The first approach I'm going to demonstrate doesn't use Url-Rewriting at all, and instead uses a little-known feature of ASP.NET - the Request.PathInfo property. To help explain the usefulness of this property, consider the below URL scenario for our e-commerce store:
http://www.store.com/products.aspx/Bookshttp://www.store.com/products.aspx/DVDshttp://www.store.com/products.aspx/CDs
One thing you'll notice with the above URLs is that they no longer have Querystring values - instead the category parameter value is appended on to the URL as a trailing /param value after the Products.aspx page handler name. An automated search engine crawler will then interpret these URLs as three different URLs, and not as one URL with three different input values (search engines ignore the filename extension and just treat it as another character within the URL).
You might wonder how you handle this appended parameter scenario within ASP.NET. The good news is that it is pretty simple. Simply use the Request.PathInfo property, which will return the content immediately following the products.aspx portion of the URL. So for the above URLs, Request.PathInfo would return "/Books", "/DVDs", and "/CDs" (in case you are wondering, the Request.Path property would return "/products.aspx").
You could then easily write a function to retrieve the category like so (the below function strips out the leading slash and returning just "Books", "DVDs" or "CDs"):
Function GetCategory() As String If (Request.PathInfo.Length = 0) Then Return "" Else Return Request.PathInfo.Substring(1) End If End Function
Sample Download: A sample application that I've built that shows using this technique can be downloaded here. What is nice about this sample and technique is that no server configuration changes are required in order to deploy an ASP.NET application using this approach. It will also work fine in a shared hosting environment.
Approach 2: Using an HttpModule to Perform URL Rewriting
An alternative approach to the above Request.PathInfo technique would be to take advantage of the HttpContext.RewritePath() method that ASP.NET provides. This method allows a developer to dynamically rewrite the processing path of an incoming URL, and for ASP.NET to then continue executing the request using the newly re-written path.
For example, we could choose to expose the following URLs to the public:
http://www.store.com/products/Books.aspxhttp://www.store.com/products/DVDs.aspxhttp://www.store.com/products/CDs.aspx
This looks to the outside world like there are three separate pages on the site (and will look great to a search crawler). By using the HttpContext.RewritePath() method we can dynamically re-write the incoming URLs when they first reach the server to instead call a single Products.aspx page that takes the category name as a Querystring or PathInfo parameter instead. For example, we could use an an Application_BeginRequest event in Global.asax like so to do this:
void Application_BeginRequest(object sender, EventArgs e) { string fullOrigionalpath = Request.Url.ToString(); if (fullOrigionalpath.Contains("/Products/Books.aspx")) { Context.RewritePath("/Products.aspx?Category=Books"); } else if (fullOrigionalpath.Contains("/Products/DVDs.aspx")) { Context.RewritePath("/Products.aspx?Category=DVDs"); } }
The downside of manually writing code like above is that it can be tedious and error prone. Rather than do it yourself, I'd recommend using one of the already built HttpModules available on the web for free to perform this work for you. Here a few free ones that you can download and use today:
UrlRewriter.net
UrlRewriting.net
These modules allow you to declaratively express matching rules within your application's web.config file. For example, to use the UrlRewriter.Net module within your application's web.config file to map the above URLs to a single Products.aspx page, we could simply add this web.config file to our application (no code is required):

The HttpModule URL rewriters above also add support for regular expression and URL pattern matching (to avoid you having to hard-code every URL in your web.config file). So instead of hard-coding the category list, you could re-write the rules like below to dynamically pull the category from the URL for any "/products/[category].aspx" combination:

This makes your code much cleaner and super extensible.
Sample Download: A sample application that I've built that shows using this technique with the UrlRewriter.Net module can be downloaded here.
What is nice about this sample and technique is that no server configuration changes are required in order to deploy an ASP.NET application using this approach. It will also work fine in a medium trust shared hosting environment (just ftp/xcopy to the remote server and you are good to go - no installation required).
Approach 3: Using an HttpModule to Perform Extension-Less URL Rewriting with IIS7
The above HttpModule approach works great for scenarios where the URL you are re-writing has a .aspx extension, or another file extension that is configured to be processed by ASP.NET. When you do this no custom server configuration is required - you can just copy your web application up to a remote server and it will work fine.
There are times, though, when you want the URL to re-write to either have a non-ASP.NET file extension (for example: .jpg, .gif, or .htm) or no file-extension at all. For example, we might want to expose these URLs as our public catalog pages (note they have no .aspx extension):
http://www.store.com/products/Bookshttp://www.store.com/products/DVDshttp://www.store.com/products/CDs
With IIS5 and IIS6, processing the above URLs using ASP.NET is not super easy. IIS 5/6 makes it hard to perform URL rewriting on these types of URLs within ISAPI Extensions (which is how ASP.NET is implemented). Instead you need to perform the rewriting earlier in the IIS request pipeline using an ISAPI Filter. I'll show how to-do this on IIS5/6 in the Approach 4 section below.
The good news, though, is that IIS 7.0 makes handling these types of scenarios super easy. You can now have an HttpModule execute anywhere within the IIS request pipeline - which means you can use the URLRewriter module above to process and rewrite extension-less URLs (or even URLs with a .asp, .php, or .jsp extension). Below is how you would configure this with IIS7:

Note the "runAllManagedModulesForAllRequests" attribute that is set to true on the section within . This will ensure that the UrlRewriter.Net module from Intelligencia, which was written before IIS7 shipped, will be called and have a chance to re-write all URL requests to the server (including for folders). What is really cool about the above web.config file is that:
1) It will work on any IIS 7.0 machine. You don't need an administrator to enable anything on the remote host. It will also work in medium trust shared hosting scenarios.
2) Because I've configured the UrlRewriter in both the and IIS7 section, I can use the same URL Rewriting rules for both the built-in VS web-server (aka Cassini) as well as on IIS7. Both fully support extension-less URLRewriting. This makes testing and development really easy.
IIS 7.0 server will ship later this year as part of Windows Longhorn Server, and will support a go-live license with the Beta3 release in a few weeks. Because of all the new hosting features that have been added to IIS7, we expect hosters to start aggressively offering IIS7 accounts relatively quickly - which means you should be able to start to take advantage of the above extension-less rewriting support soon. We'll also be shipping a Microsoft supported URL-Rewriting module in the IIS7 RTM timeframe that will be available for free as well that you'll be able to use on IIS7, and which will provide nice support for advanced re-writing scenarios for all content on your web-server.
Sample Download: A sample application that I've built that shows using this extension-less URL technique with IIS7 and the UrlRewriter.Net module can be downloaded here.
Approach 4: ISAPIRewrite to enable Extension-less URL Rewriting for IIS5 and IIS6
If you don't want to wait for IIS 7.0 in order to take advantage of extension-less URL Rewriting, then your best best is to use an ISAPI Filter in order to re-write URLs. There are two ISAPI Filter solutions that I'm aware of that you might want to check-out:
Helicon Tech's ISAPI Rewrite: They provide an ISAPI Rewrite full product version for $99 (with 30 day free trial), as well as a ISAPI Rewrite lite edition that is free.
Ionic's ISAPI Rewrite: This is a free download (both source and binary available)
I actually don't have any first-hand experience using either of the above solutions - although I've heard good things about them. Scott Hanselman and Jeff Atwood recently both wrote up great blog posts about their experiences using them, and also provided some samples of how to configure the rules for them. The rules for Helicon Tech's ISAPI Rewrite use the same syntax as Apache's mod_rewrite. For example (taken from Jeff's blog post):
[ISAPI_Rewrite]# fix missing slash on folders# note, this assumes we have no folders with periods!RewriteCond Host: (.*)RewriteRule ([^.?]+[^.?/]) http\://$1$2/ [RP]# remove index pages from URLsRewriteRule (.*)/default.htm$ $1/ [I,RP]RewriteRule (.*)/default.aspx$ $1/ [I,RP]RewriteRule (.*)/index.htm$ $1/ [I,RP]RewriteRule (.*)/index.html$ $1/ [I,RP]# force proper www. prefix on all requestsRewriteCond %HTTP_HOST ^test\.com [I]RewriteRule ^/(.*) http://www.test.com/$1 [RP]# only allow whitelisted referers to hotlink imagesRewriteCond Referer: (?!http://(?:www\.good\.comwww\.better\.com)).+RewriteRule .*\.(?:gifjpgjpegpng) /images/block.jpg [I,O]
Definitely check out Scott's post and Jeff's post to learn more about these ISAPI modules, and what you can do with them.
Note: One downside to using an ISAPI filter is that shared hosting environments typically won't allow you to install this component, and so you'll need either a virtual dedicated hosting server or a dedicated hosting server to use them. But, if you do have a hosting plan that allows you to install the ISAPI, it will provide maximum flexibility on IIS5/6 - and tide you over until IIS7 ships.
Handling ASP.NET PostBacks with URL Rewriting
One gotcha that people often run into when using ASP.NET and Url-Rewriting has to-do with handling postback scenarios. Specifically, when you place a form server control on a page, ASP.NET will automatically by default output the "action" attribute of the markup to point back to the page it is on. The problem when using URL-Rewriting is that the URL that the form control renders is not the original URL of the request (for example: /products/books), but rather the re-written one (for example: /products.aspx?category=books). This means that when you do a postback to the server, the URL will not be your nice clean one.
With ASP.NET 1.0 and 1.1, people often resorted to sub-classing the form control and created their own control that correctly output the action to use. While this works, it ends up being a little messy - since it means you have to update all of your pages to use this alternate form control, and it can sometimes have problems with the Visual Studio WYSIWYG designer.
The good news is that with ASP.NET 2.0, there is a cleaner trick that you can use to rewrite the "action" attribute on the form control. Specifically, you can take advantage of the new ASP.NET 2.0 Control Adapter extensibility architecture to customize the rendering of the form control, and override its "action" attribute value with a value you provide. This doesn't require you to change any code in your .aspx pages. Instead, just add a .browser file to your /app_browsers folder that registers a Control Adapter class to use to output the new "action" attribute:

You can see a sample implementation I created that shows how to implement a Form Control Adapter that works with URLRewriting in my sample here. It works for both the Request.PathInfo and UrlRewriter.Net module approaches I used in Approach 1 and 2 above, and uses the Request.RawUrl property to retrieve the original, un-rewritten, URL to render. With the ISAPIRewrite filter in Approach 4 you can retrieve the Request.ServerVariables["HTTP_X_REWRITE_URL"] value that the ISAPI filter uses to save the original URL instead.
My FormRewriter class implementation above should work for both standard ASP.NET and ASP.NET AJAX 1.0 pages (let me know if you run into any issues).
Handling CSS and Image Reference Correctly
One gotcha that people sometime run into when using Url Rewriting for the very first time is that they find that their image and CSS stylesheet references sometimes seem to stop working. This is because they have relative references to these files within their HTML pages - and when you start to re-write URLs within an application you need to be aware that the browser will often be requesting files in different logical hierarchy levels than what is really stored on the server.
For example, if our /products.aspx page above had a relative reference to "logo.jpg" in the .aspx page, but was requested via the /products/books.aspx url, then the browser will send a request for /products/logo.jpg instead of /logo.jpg when it renders the page. To reference this file correctly, make sure you root qualify CSS and Image references ("/style.css" instead of "style.css"). For ASP.NET controls, you can also use the ~ syntax to reference files from the root of the application (for example:

Bubbling an Event

Bubbling an Event
The ASP.NET page framework provides a technique called event bubbling that allows a child control to propagate events up its containment hierarchy. Event bubbling enables events to be raised from a more convenient location in the controls hierarchy and allows event handlers to be attached to the original control as well as to the control that exposes the bubbled event.

Event bubbling is used by the data-bound controls (Repeater, DataList, and DataGrid) to expose command events raised by child controls (within item templates) as top-level events. While ASP.NET server controls in the .NET Framework use event bubbling for command events (events whose event data class derives from CommandEventArgs), any event defined on a server control can be bubbled.

A control can participate in event bubbling through two methods that it inherits from the base class System.Web.UI.Control. These methods are OnBubbleEvent and RaiseBubbleEvent. The following code shows the signatures of these methods.

[C#] Copy Code
protected virtual bool OnBubbleEvent(
object source,
EventArgs args
);
protected void RaiseBubbleEvent(
object source,
EventArgs args
);
[Visual Basic]
Overridable Protected Function OnBubbleEvent( _
ByVal source As Object, _
ByVal args As EventArgs _
) As Boolean
Protected Sub RaiseBubbleEvent( _
ByVal source As Object, _
ByVal args As EventArgs _
)
The implementation of RaiseBubbleEvent is provided by Control and cannot be overridden. RaiseBubbleEvent sends the event data up the hierarchy to the control's parent. To handle or to raise the bubbled event, a control must override the OnBubbleEvent method.

A control that has an event bubbled to it does one of the following three things.

It does nothing, in which case the event is automatically bubbled up to its parent.
It does some processing and continues to bubble the event. To accomplish this, a control must override OnBubbleEvent and invoke RaiseBubbleEvent from OnBubbleEvent. The following code fragment (from the Templated Data-Bound Control Sample) bubbles an event after checking for the type of the event arguments.
[C#] Copy Code
protected override bool OnBubbleEvent(object source, EventArgs e) {
if (e is CommandEventArgs) {
// Adds information about an Item to the
// CommandEvent.
TemplatedListCommandEventArgs args =
new TemplatedListCommandEventArgs(this, source, (CommandEventArgs)e);
RaiseBubbleEvent(this, args);
return true;
}
return false;
}
[Visual Basic]
Protected Overrides Function OnBubbleEvent(source As Object, e As EventArgs) As Boolean
If TypeOf e Is CommandEventArgs Then
' Adds information about an Item to the
' CommandEvent.
Dim args As New TemplatedListCommandEventArgs(Me, source, CType(e, CommandEventArgs))
RaiseBubbleEvent(Me, args)
Return True
End If
Return False
End Function
It stops bubbling the event and raises and/or handles the event. Raising an event involves invoking the method that dispatches the event to listeners. To raise the bubbled event, a control must override OnBubbleEvent to invoke the OnEventName method that raises the bubbled event. A control that raises a bubbled event generally exposes the bubbled event as a top-level event. The following code fragment (from the Templated Data-Bound Control Sample) raises a bubbled event.
[C#] Copy Code
protected override bool OnBubbleEvent(object source, EventArgs e) {
bool handled = false;

if (e is TemplatedListCommandEventArgs) {
TemplatedListCommandEventArgs ce = (TemplatedListCommandEventArgs)e;

OnItemCommand(ce);
handled = true;
}
return handled;
}
[Visual Basic]
Protected Overrides Function OnBubbleEvent(source As Object, e As EventArgs) As Boolean
Dim handled As Boolean = False

If TypeOf e Is TemplatedListCommandEventArgs Then
Dim ce As TemplatedListCommandEventArgs = CType(e, TemplatedListCommandEventArgs)

OnItemCommand(ce)
handled = True
End If
Return handled
End Function
For samples that demonstrate event bubbling, see Event Bubbling Control Sample and Templated Data-Bound Control Sample.

Note While the method that enables event bubbling, OnBubbleEvent, follows the standard .NET Framework naming pattern for methods that raise events, there is no event named BubbleEvent. The bubbled event is exposed as a top-level event in the control that stops event bubbling. For example, the DataList control exposes Command events from controls in its template as ItemCommand events. Note also that the standard signature of OnEventName methods in the .NET Framework has one argument (protected void OnEventName (EventArgs e)). However, OnBubbleEvent has two arguments because the event originates outside the control; the second argument supplies the source.
The discussion so far shows how a control can respond to an event that is bubbled up to it. The following section shows how to author a control that defines a bubbled event.

Defining a Bubbled Event
If you want your control to enable event bubbling for an event that it defines, it must invoke the RaiseBubbleEvent from the OnEventName method that raises the event. No additional work needs to be done from within the control. The following code fragment shows a control that defines a Command event that enables bubbling.

[C#] Copy Code
protected virtual void OnCommand(CommandEventArgs e) {
CommandEventHandler handler = (CommandEventHandler)Events[EventCommand];
if (handler != null)
handler(this,e);

// The Command event is bubbled up the control hierarchy.
RaiseBubbleEvent(this, e);
}
[Visual Basic]
Protected Overridable Sub OnCommand(e As CommandEventArgs)
Dim handler As CommandEventHandler = CType(Events(EventCommand), CommandEventHandler)
If Not (handler Is Nothing) Then
handler(Me, e)
End If
' The Command event is bubbled up the control hierarchy.
RaiseBubbleEvent(Me, e)
End Sub
Note Event bubbling is not limited to command events. You can use the mechanism described here to bubble any event.

Usefull Questions on Asp.NET

What is the roll of JIT in asp.net?

JIT convert Intermediate languge(IL) to machine code at run
time or at the point where the software is installed.

1)Pre JIT - JIT convert Intermediate languge(IL) to machine
code before compilation time

2)Eco JIT -JIT convert Intermediate languge(IL) to machine
code At the time of compilation

3)Normal JIT - JIT convert Intermediate languge(IL) to
machine code After the time of compilation

Types of caching. How to implement caching?

there are 3 types of caches is there they ara
1)page caching
2)page fragmentaion caching
3)data caching
in case of the page caching the total page will be cached
for certain amount of time(i.e the time will declared by
ourself)and in case of page fragmentation caching only a
part of the data will be cached for some amount of time
Data caching, which allows developers to programmatically
retain arbitrary data across requests

ASP.NET Caching Features
ASP.NET Web Applications


------------------------------------------------------------
--------------------

When clients access an ASP.NET page, there are basically
two ways to provide them with the information they need:

the ASP.NET page can either obtain information from server
resources, such as from data that has been persisted to a
database, or
the ASP.NET page can obtain information from within the
application.
Retrieving information from a resource outside the
application will require more processing steps, and will
therefore require more time and resources on the server
than if the information can be obtained from within the
application space.

If the information that will be sent to the browser has
already been prepared by a previous request, the
application will be able to retrieve that information
faster if it has been stored in memory, somewhere along the
request/response stream.

Known as caching, this technique can be used to temporarily
store page output or application data either on the client
or on the server, which can then be re-used to satisfy
subsequent requests and thus avoid the overhead of re-
creating the same information.

Caching is particularly suitable when you expect to return
the same information in the same format for many different
requests.

ASP.NET provides the following types of caching that can be
used to build highly responsive Web applications:

Output caching, which caches the dynamic response generated
by a request.
Fragment caching, which caches portions of a response
generated by a request.
Data caching, which allows developers to programmatically
retain arbitrary data across requests.


What is the difference between an EXE and a DLL?
EXE file has Entry point, but in dll no Entry point.
EXE file is a excutable file which runs in a seperate
process which is managed by OS,where as a DLL file is a
dynamic link library which can be used in exe files and
other dll files.
In .net frame work both are assemblies.
EXE is a Self Executable File where as dll is not self
executable file,To run dll file we need a exe file

DLL:
1)it has versioning
2)it is not self executable
3)it runs in application process memory
4)it has no entry point
5)it is reusable

Exe:
1)it is self executable
2)it has no versioning
3)it runs in own memory
4)it have main function(Entry point)
5)it is self executable

Note:DLL is Superset of Exe

Which property on a Combo Box do you set with a column name,
prior to setting the DataSource, to display data in the
combo box?
DataTextField property

What is shadowing?

When two programming elements share the same name, one of
them can hide, or shadow, the other one. In such a
situation, the shadowed element is not available for
reference; instead, when your code uses the shared name,
the Visual Basic compiler resolves it to the shadowing
element.
Shadowing through inheritance is hiding a method of a
base class and providing a new implementation for the same.
This is the default when a derived class writes an
implementation of a method of base class which is not
declared as overridable in the base class. This also serves
the purpose of protecting an implementation of a new method
against subsequent addition of a method with the same name
in the base class.

http://www.allinterview.com/showanswers/4575.html

ASP.NET 2.0 Profile: Simple User Personalization for Your Web Apps

Most enterprise Web applications need to track user preferences across multiple visits. In ASP.NET 1.x, you need to write lots of code to create this functionality. ASP.NET 2.0 introduces a new object named profile that simplifies the steps involved in tracking personalization information. This article provides an introduction to the profile object and differentiates it from the session object. It also demonstrates how to define user profiles, both simple name/value pair profiles and profile groups. Finally, it explains the procedures involved in configuring profiles to work with different providers.
An Overview of Profile Object
In an ASP.NET profile, information is stored in a persistent format and is associated with an individual user. The ASP.NET profile allows you to easily manage user information without having to create and maintain your own database. You can store any type of object in the profile because of its generic storage system. In addition, you can also make the same data available in a type-safe manner.
Is the Profile Object the Same as the Session Object?
At first look, the profile object might look very similar to the session object. But there are a number of differences between the two objects. Table 1 outlines these differences.

Table 1. Differences Between the Profile and Session Objects
Characteristics
Profile
Session
Scope
Each user has his own profile object
Each user has his own session object
Strongly typed nature
Profile object is strongly typed
Session object is not strongly typed and requires type casting when assigning and retrieving from the session object
Persistent duration
Profile values are available for the users, even between visits
Session object contents are available only for the duration of the current browser session
Persistent location
Profile object can be stored in a SQL Server Express database or in a SQL Server database and can be configured through the Web Site Administration tool
Session object can be configured to be stored in a database, IIS in-process, or in a session state server, depending on the configuration setting
Performance
Profile may have a negative impact on performance because of the chatty interface between the profile object and the persistent data store
Can be configured using properties such as EnableSessionState attributes at the page level
IntelliSense
Provides IntelliSense because of its strongly typed nature
No support for IntelliSense

Now that you have a general understanding of the important characteristics of the profile object, take a look at an example.
Defining User Profiles
You define a user profile within the application root web.config file. You cannot create a web.config file containing a profile section in an application subfolder. This means that you can have only one profile element declaration for one Web application. The following declaration in the web.config contains a simple profile definition:









-----
-----



As you can see, the profile defines two properties: Name and UserCount. The default data type for profile properties is the System.String data type. In the above example, the Name property explicitly declares the data type to be of System.String. The UserCount property is assigned the type Int16 since it is used to represent an integer value.

Once you define a profile, whenever someone requests a page from the Web site ASP.NET automatically generates a class named ProfileCommon that corresponds to the profile definition. This class is stored in the Temporary ASP.NET Files directory, and an instance of this class is made available through the profile property of the HttpContext object.

The following section shows how to utilize this class to access the profile properties.
Working with User Profiles from an ASP.NET Page
Once you have the profiles declared, the next step is to access the profile object from within the ASP.NET page so that you can set or get the values stored in the profile properties. The following code uses the Name and UserCount properties declared in the previous section:

<%@ Page Language="C#" %>

The above listing declares two command buttons. The first, btnSetName, assigns the name entered in the textbox to the Profile.Name property. The click event of the second command button, btnGetProfileValues, results in the values of the profile properties being displayed in the label controls that in turn are contained in a Panel control. In the Page_Load event, the UserCount property is incremented by 1. As you can see from the code listing, setting the value of a profile property is very simple:

Profile.Name = txtName.Text;

Similarly, retrieving the values stored in the profile object is also very simple and straightforward:

lblName.Text = Profile.Name;

Note that you don’t need to typecast when retrieving the profile values since the properties stored in the profile object are strongly typed. Navigate to the above page using your browser, set the name, and click on the Get Profile Values button. You should see an output similar to

This example enabled Windows authentication through IIS and enabled impersonation through the following settings in the web.config file:



Note that it enabled impersonation so that the ASP.NET code has sufficient permissions to create a new SQL Server Express database for the first time.
How Profile Properties Are Stored
You might be wondering where exactly the profile properties Name and UserCount are stored in the above example. By default, ASP.NET 2.0 comes with two profile providers: SQL Server Express and SQL Server. By default, the SQL Server Express provider is used. (A later section will show how to change the provider.)

If you refresh your project listing in Solution Explorer, you will notice a database file called ASPNETDB.MDF within the App_Data folder. If you double click on this database, you will see that the database is opened through the Server Explorer view. Within this database, you will see a table called aspnet_Profile. Figure 2 shows the contents of the table and the values that have been saved through the Profile properties shown in the previous example.
 
hit counter
Download a hit counter here.