Friday, March 28, 2008

Performing Browser Detection Using ASP.NET

Introduction

When the browser wars were at their height from 1996-1999, or so, browser detection was an important facet of Web design. During these years, the features supported by Microsoft and Netscape varied quite a bit, and Web designers who wanted to make use some of the "cooler" features of a given browser would need to detect what browser the user was using in order to customize the HTML outputted by the Web page. Many sites actually maintained two sets of pages: one for Netscape and one for Internet Explorer, and the main page would redirect the user to the applicable set of Web pages based on the user's browser.

To accomplish this, Web designers used what is known as browser detection. Browser detection, as its name implies, is detecting what browser a Web visitor is using. This is possible because Web browsers, when making an HTTP request to a Web server, pass in their HTTP headers a string referred to as the User-Agent, which specifies what browser type is being used. From a server-side Web page, one can easily determine the value of this HTTP header. In ASP.NET (or classic ASP), for example, one can display this parameter using the following line of code:

Response.Write(Request.ServerVariables("HTTP_USER_AGENT"))

Specifically, your Web browser has sent the following User-Agent HTTP header:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3

The User-Agent, unfortunately, is a bit cryptic, and requires parsing to determine what browser, specifically, a visitor is using. Furthermore, it doesn't contain information like what version of JavaScript the browser supports, or if the browser supports CSS 2.0 stylesheets.

Fortunately, ASP.NET provides a HttpBrowserCapabilities class that performs all the parsing of the User-Agent HTTP header to determine what browser the visitor is browsing with. By knowing what browser the visitor is using, this class can also determine what properties the browser can support (CSS support, JavaScript version, etc.). In this article we will examine how to use the HttpBrowserCapabilities class to perform browser detection in an ASP.NET Web page!

First Off - Does Browser Detection Matter Anymore?
One of the primary motivations behind browser detection in the late 1990s was to be able to direct users to an appropriate set of Web pages that has been customized for their particular browser. Today, however, you will rarely find Web sites that have separate pages for different browsers, in large part because Microsoft's Internet Explorer has come to dominate the browser market landscape. Also, as Web designers from the late 1990s can attest to, maintaining multiple sets of Web pages can be expensive and time-consuming. A smarter approach to Web design is to limit the features used to those that are supported by the vast majority of your expected user base. That is, refrain from the whiz-bang features that are only supported well in one particular browser, and stick to the plain ol' vanilla HTML. (Have you ever noticed that the Web's busiest Web sites - Yahoo, Amazon.com, Ebay, etc. - all use very simply HTML design that is renderable with the same look and feel on nearly every browser available?)

So why would one want to do browser detection anymore? One possible reason might be for browser exclusion. Typically, large corporations standardize on a particular browser, say IE 5.5, which they require installed on all corporate computers. Hence, the corporation's intranet expects only one type of browser, and the Web designer can take full advantage of features that he or she knows to be in that browser that might be lacking from older versions. Therefore, on a corporate intranet, if someone visits with a non-standard browser (be it a different browser or an older version of the accepted browser), you might wish to direct the user to a page explaining that the use of the intranet requires the corporation's standard browser.

Additionally, when Web search engines index a site they send a "crawler" to visit the various pages of your site and add them to their database. (This crawler is really just some script making HTTP requests to your page.) Typically these crawlers use a User-Agent string that indicates that they are crawlers (and not live users). In such a case, you may wish to serve up different content. For example, if you have a Web page that, whenever visited, performs a lengthy database call to display rapidly changing dynamic data, you may wish to show some cached version of the data when a crawler comes by. You may opt to do this in order to save the burden of having to run the query for a visitor that is not, after all, a real visitor.

Browser Detection in Classic ASP
In classic ASP there was four ways to perform browser detection:

  1. Using client-side script
  2. Using the User-Agent server variable
  3. Using the Browser Capabilities component
  4. Using a third-party program

The first technique uses client-side JavaScript to determine the browser version, and can also be employed in an ASP.NET Web page. The second technique references the User-Agent HTTP header, as discussed earlier, which can also be done in an ASP.NET Web page by accessing Request.ServerVariables("HTTP_USER_AGENT"). The third technique involves using a COM component that shipped with classic ASP, MSWC.BrowserType. Finally, the fourth technique involves using a commercial product like CyScape's Browserhawk.

These four methods are examined in detail in an earlier article of mine, Obtaining your User's Browser Information. If you are interested in learning more about browser detection with classic ASP, be certain to read that article.

Performing Browser Detection in ASP.NET
As aforementioned, in ASP.NET you can use client-side JavaScript for browser detection or direct examination of the User-Agent HTTP header. However, ASP.NET provides a much simpler way to determine browser information: the
Request.Browser property, which is an instance of the HttpBrowserCapabilities object. The BrowserCapabilities object contains properties that describe the features available in a particular browser. These properties, which are enumerated in the technical documentation, include:

  • ActiveXControls - a Boolean, indicating if the browser supports ActiveX controls
  • AOL - a Boolean, indicating if the browser is an AOL-supplied browser
  • Cookies - a Boolean, indicating if the browser supports cookies
  • Crawler - a Boolean, indicating if the browser is a Web search engine crawler
  • Frames - a Boolean, indicating if the browser supports frames
  • JavaApplets - a Boolean, indicating if the browser supports Java applets
  • MajorVersion - the browser's major version. The major version of IE 5.3 would be 5.
  • MinorVersion - the browser's major version. The minor version of IE 5.3 would be 3.
  • Platform - a String that specifies the user's computer platform, such as WinNT, Win95, UNIX, etc.
  • VBScript - a Boolean, indicating if the browser supports client-side VBScript code

Note that these Boolean values specify whether or not the browser can support such features. For example, IE 6.0 has cookie support; therefore, if you want to check to see if a user's browser supports cookies using the Request.Browser property, a value of True will be returned for any user using IE 6.0. However, users can configure their browsers so that they do not accept cookies; regardless of the user's configuration, the Cookies property will always return True if the user's browser has the ability to support cookies.

The following code sample shows code that will display many of the properties of the user's browser.

Your browser is:

Here is your browser's information:

What's Happening Behind the Scenes
As discussed earlier, the only way for the Web server to know what type of Web browser a visitor is using is by the User-Agent HTTP header sent by the browser. This string, as was shown, is quite simple, and you may be wondering how in the world ASP.NET can determine what features a particular browser can support just by this simple User-Agent string.

The answer is, it can't - it relies on information in the machine.config file that specifies what properties each of these browsers supports. The machine.config, which can be found in the directory $WINDIR$\Microsoft.NET\Framework\v1.0.3705\CONFIG, is an XML-formatted configuration file that specifies configuration options for the machine. This file contains, among many other XML elements, a browserCaps element. Inside this element are a number of other elements that specify parse rules for the various User-Agents, and what properties each of these parsings supports.

For example, to determine what platform is used, a filter element is used that specifies how to set the platform property based on what platform name is found in the User-Agent string. Specifically, the machine.config file contains:

platform=Win95

platform=Win98

platform=WinNT

...

That is, if in the User-Agent string the string "Windows 95" or "Win95" is found, the platform property is set to Win95. There are a number of filter elements in the browserCaps element in the machine.config file that define the various properties for various User-Agent strings.

Hence, when using the Request.Browser property to determine a user's browser features, the user's agent string is matched up to particular properties in the machine.config file. The ability for being able to detect a user's browser's capabilities, then, is based upon the honesty in the browser's sent User-Agent string. For example, Opera can be easily configured to sent a User-Agent string that makes it appear as if it's IE 5.5. In this case from the Web server's perspective (and, hence, from your ASP.NET Web page's perspective), the user is visiting using IE 5.5, even though, in actuality, he is using Opera.

Conclusion
In this article we have seen how to perform browser detection using ASP.NET. The technique of using the Request.Browser property is much simpler than parsing through the User-Agent HTTP header by hand. Additionally, it is easier to use than classic ASP's BrowseCap COM object, which required instantiation of a COM component.

Happy Programming!

Thursday, March 27, 2008

Latest Technical Interview Questions & Answers

What is the difference between group by and order by ?

Group by controls the presentation of the rows, order by controls the presentation of the columns for the results of the SELECT statement.

What is a subselect? Is it different from a nested select?

A subselect is a select which works in conjunction with another select. A nested select is a kind of subselect where the inner select passes to the where criteria for the outer select.

Explain an outer join ?

An outer join includes rows from tables when there are no matching values in the tables.

What is a view? Why use it?

A view is a virtual table made up of data from base tables and other views, but not stored separately.

What do the initials DDL and DML stand for and what is their meaning ?

DDL is data definition language and DML is data manipulation language. DDL statements are CREATE, ALTER, TRUNCATE. DML statements are SELECT, INSERT, DELETE and UPDATE.

What are foreign keys ?

These are attributes of one table that have matching values in a primary key in another table, allowing for relationships between tables.

What is normalization and what are the five normal forms ?

Normalization is a design procedure for representing data in tabular format. The five normal forms are progressive rules to represent the data with minimal redundancy.

What are the levels of isolation available with DB2V4 ?

CS RR UR( added new for DB2V4 which stands for uncommitted read which allows to retrieve records from the space which has exclusive locks also but data integrity will be affected if this option is used )The best available option for data integrity & data concurrency is CS.

What is the difference between TYPE 1 index & TYPE 2 index ?

TYPE 1 & TYPE 2 are specified when an index is created on the table. TYPE 2 index is the option which comes with DB2V4. With TYPE 2 index data can be retrieved faster as only the data pages are locked and not the index pages. Hence TYPE 2 index is recommended.

What does CURRENTDATA option in bind indicate ?

CURRENTDATA option ensures block fetch while selecting rows from a table. In DB2V4 the default has been changed to NO. Therefore it is necessary to change all the bind cards with CURRENTDATA(YES) which is default in DB2V3 & earlier to CURRENTDATA(NO).

Thursday, February 7, 2008

Program asked frequently in interviews

These are the list of programs asked frequently in interviews. If anyone has the answers or new questions , add to this ---

1. Factorial
2. Factors of a given No.
3. Prime No.
4. Sum of the Factors
5. Armstrong
6. Palindrome
7. Reverse
8. Amicable
9. Recursion
10. Fibonacci Series
11. Searching and Sorting
12. Matrix Multiplication
13. Reverse a String
14. Swapping or two variables with out using 3rd variable
15. String Concatenation
16. Print second largest no out of given.
17. Write a program to print the following?
*
***
*****
***

18. Largest number from 3 numbers without using array.
19. Fahrenheit to Celsius conversion program
20. Multiplication of two matrix
21. write a program to count no of vowels in your name.

22. convert a decimal no. into hexadecimal. 23. WAP for square root of a no.

24. Write a program so that if we enter the marks of students they get grade a b c. that is if the student gets more than 80% then he should be given rank a and if between 70% n 80% then b and below 70% is c.

Thursday, January 24, 2008

Introducing C# 2.0

With the release of Visual Studio 2005 (formerly codenamed Whidbey), C# is back with some new innovations. The C# language has been updated to version 2.0 and comes with several language extensions which we will explore in this 2 part series article. Besides Generic types, the C# language introduces some other interesting features such as Iterators, Partial Classes and Anonymous methods, which are briefly mentioned below.

Generics
Although new to the .NET platform, this concept has been around for years. Generics is a term used to describe generic types. It greatly enhances application performance and type safety and allows you to write highly general, flexible and safe code. It permits classes, interfaces, structs, delegates and methods to be parameterized by the types of data they store and manipulate.
Iterators
Iterators specify how a for-each loop will iterate over a collection and return its internal items. They allow you to create enumerable classes with minimum coding.
Partial Classes
Partial Classes allows you to split a single type, like your class, across more than one file (.cs). They are useful if you have extremely large, unwieldy types.
Nullable Types
Nullable types allow a variable to contain a value that is undefined. This is useful when working with databases where the value returned might be null
Anonymous Methods
Anonymous Methods Are Inline Delegates. It enables you to pass a block of code as a parameter. Anonymous methods enables you to directly associate a block of code statements to a given event. You use them anywhere a delegate is used . So there is no need to define a new method.
Namespace alias qualifier
C# 2.0 adds the namespace alias qualifier, the :: operator, to provide more control over accessing namespace members.
Static Classes
With C# 2.0, now you also can declare classes as static. This signals the compiler that this class should not be instantiated and can only contains static members.
Property Accessor Accessibility
C# 2.0 allows a fine control over the accessibility of accessors and indexers within a property.
Covariance and Contravariance in Delegates
The method passed to a delegate may now have greater flexibility in its return type and parameters.

Generics
Classes are templates that you can use to build new objects. Generics are templates that you can use to build new classes. This code template can be applied to use the same code repeatedly. A generic class is tied to one or more specific data types.
Generics permit classes, interfaces, structs, delegates and methods to be parameterized by the types of data they store and manipulate. They are Type-independent algorithms and collections. They enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generics are defined with left and right brackets: . Here ‘T’ in is the name of the type that is going to be used.
Let's demonstrate the use of Generics by taking a simple example:
namespace GenericsDemo
{
class TestGenerics
{
static void Main(string[] args)
{
GenericsExample();
}
private void GenericsExample()
{
ClsGeneric intGeneric = new ClsGeneric(1000);
ClsGeneric strGeneric = new ClsGeneric("Voila");
ClsGeneric fGeneric = new ClsGeneric(23.38f);
ClsGeneric dGeneric = new ClsGeneric(444.4);
ClsGeneric bGeneric = new ClsGeneric(true);
}
}
public class ClsGeneric
{
public ClsGeneric(T Type)
{
Console.WriteLine("T over here is {0} ", typeof(T).ToString());
}
}
}
By using a generic type parameter T, you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.
Iterators
In the earlier versions of C#, in order to use the for-each loop, you need to implement the IEnumerable interface which in turn demands the implementation of the GetEnumerator() method. This method returns an IEnumerator object using which you can use the foreach loop.
An iterator on the other hand, enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface.
Let me demonstrate this with an example :
public class StringCollection : System.Collections.IEnumerable
{
string[] names = { "Tom", "Dick", "Harry”, "Ralph", "Jack", "Jill” };
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i <>
{
yield return names[i];
// In C#1.x you would have specified it using
// return names[i].GetEnumerator();
}
}
}
class TestStringCollection
{
static void Main()
{
// Create an instance
StringCollection strNames = new StringCollection();
foreach (string name in strNames)
{
System.Console.WriteLine(name);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}

Partial Classes
C# 2.0 introduces the concept of partial type definitions for classes, structs, and interfaces that allows you to define a C# type across multiple *.cs files. This leads to easier maintenance and development as more than one developer can simultaneously write the code for the class.
public partial class A
{
public void methodA()
{
// Code for methodA
}
}
public partial class A
{
public void methodB()
{
// Code for methodB
}
}
Nullable Types
A type is said to be nullable if it can be assigned a value or can be assigned a null reference. This change makes it easier to integrate with databases, especially for fields that are optional.
A null type is very similar to its equivalent non-nullable type. The difference lies in how it is declared. For example : To declare an integer, you would declare it like this :
int iVal = 1; 
However in order to enable iVal to store a null value, you will declare it like this :
int? iVal = 1;
Now the way to define any valuetype as a nullable type is to define the generic System.Nullable type. So the syntax to define a nullable integer is:
System.Nullable iVal;
However this is somewhat difficult to read and that is why C# provides a cleaner syntax for the nullable type by adding a question mark to the immediate right of the type name when defining a variable. The Syntax is [Value-Type]? 

So
System.Nullable iVal and int? iVal are equivalent.
Similarly you can also assign it a value null and use the HasValue and Value read-only properties to test for null and retrieve the value. Here’s an example :
int? iVal = null;
if (iVal.HasValue == true)
{
System.Console.WriteLine("iVal = " + iVal.Value);
}
else
{
System.Console.WriteLine("iVal = Null");
}
Anonymous Methods
Anonymous methods help you reduce the coding overhead in instantiating delegates, by eliminating the need to create a separate method. This construct allows you to directly associate a block of code statements to a given event. In general, you can use anonymous methods anywhere you can use a delegate. An anonymous method consists of the keyword delegate, an optional parameter list, and a statement list enclosed in { and } delimiters. In some cases, the anonymous methods can omit the parameter list.
public class frmOld : Form
{
// This method connects the event handler.
public frmOld()
{
InitializeComponent();
btnOld.Click += new EventHandler(ButtonClick);
}
// This is the event handling method.
private void ButtonClick(object sender, EventArgs e)
{
MessageBox.Show("Old method of handling ButtonClick");
}
}
Using Anonymous methods :
public class frmNew : Form
{
public frmNew()
{
InitializeComponent();
btnNew.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show(“New way of handling button click using anonymous methods");
};
}
}
// Declare a delegate
delegate void PrintHello(string str);
class TestAnonymous
{
static void Main()
{
hello = new PrintHello(TestAnonymous.TestMethod);
Without anonymous method you would associate the delegate with a named method. For eg:
hello = new PrintHello(TestAnonymous.TestMethod);
//and declared a method to associate it with the named delegate
static void TestMethod(string test)
{
System.Console.WriteLine(test);
}
Static Classes
Static classes are classes that contain only static members. These static members can be initialized only by using static constructors. The data and functions that these classes create, can be accessed without creating an instance of the class. Static classes are sealed so they can not be inherited. TheSystem.Math class is an example of this construct.
Static classes can be used when there is no data or behavior in the class that depends on object identity. One of the advantages of static classes is improved performance. Since there is no instantiation of object, the framework maintains a single object in memory for static members. They are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Creating a static class is much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. Lets see an example of a static class.
Property Accessor Accessibility
Properties provide flexibility to read and write the values of private fields. They can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
In C# 1.x, we declare a property in our class in the following manner:
class ClsProp
{
private string strMyName = "Suprotim";
public string StrMyName
{
get { return strMyName; }
set { strMyName = value; }
}
}
Here the ‘get’ and the ‘set’ accessors have the same accessibility level i.e., they are both ‘public’ as the property itself is ‘public’. However, it is sometimes useful to restrict access to one of these accessors, which was not possible for us in C# 1.x.
In C# 2.0, this has changed :
public string StrMyName
{
get
{
return strMyName;
}
protected set
{
strMyName = value;
}
}
In this example, a property called StrMyName defines a get and set accessor. The get accessor receives the accessibility level of the property itself, public in this case, while the set accessor is explicitly restricted by applying the protected access modifier to the accessor itself.
Note : This feature of having Accessor Accessibility was provided in C# v1.0 beta. However Microsoft removed it before the C# v1.0 RTM as they felt it was too complicated for developers. In C# 2.0, it has been re-introduced.
Covariance and Contravariance

In .NET 1.1, delegates could only be created with methods whose arguments strictly matched the signature of that delegate. With .NET 2.0, Covariance and contravariance provide a degree of flexibility when matching delegate methods with delegate signatures.

Created by Windy Road - Blogger port by Blogger Templates