Wednesday, August 19, 2009

Interfaces in asp.net and interview questions regarding interfaces

Interfaces can be created in C# with the help of the “interface “keyword. Interface can have only abstract members and these can be events, methods, properties and Indexers. Interface members do not have access modifiers like public, private, etc. By default all interface members are public. It is a compile time error to use access modifiers on interface member declarations. Interface only contains member declaration not their implementation. Interface does not contain any declaration of constants, constructors, destructors, static etc members. When a class or a struct inherits an interface, the class or struct must provide implementation for all of the members declared in the interface. The interface itself provides no functionality that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.
Example :
using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Deposit Money");
}

public void WithdrawMoney()
{
Console.WriteLine("Withdraw Money");
}

public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.DepositMoney();
DemoObject.WithdrawMoney();
}
}
}
In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();

Combining Interfaces

Two or more interfaces can be combined into a single interface and implemented in a class, as shown in Listing 2:
using System;
interface Interdemo
{
void Show();
}

interface Interdemo1
{
void Display();
}

interface Combineinter:Interdemo,Interdemo1
{
//Above interfaces combined
}

class Multipleinterimp:Combineinter
{
public void Show()
{
Console.WriteLine("Show() method Implemented");
}

public void Display()
{
Console.WriteLine("Display() method Implemented");
}

public static void Main(string[] args)
{
Multipleinterimp inter = new Multipleinterimp();
inter.Show();
inter.Display();
}
}

is Operator for C# .Net interfaces

You easily can determine whether a particular interface is implemented in a class by using is and as operators. The is operator enables you to check whether one type or class is compatible with another type or class; it returns a Boolean value.
using System;

interface Interdemo
{
bool Show();
}

interface Interdemo1
{
bool Display();
}

class Interimp:Interdemo
{
public bool Show()
{
Console.WriteLine("Show() method Implemented");
return true;
}

public static void Main(string[] args)
{
Interimp inter = new Interimp();
inter.Show();

if(inter is Interdemo1)
{
Interdemo1 id = (Interdemo1)inter;
bool ok = id.Display();
Console.WriteLine("Method Implemented");
}

else
{
Console.WriteLine("Method not implemented");
}
}
}


As operator in interface:

as operator returns null if there is any incompatibility between types
using System;

interface Interdemo
{
bool Show();
}

interface Interdemo1
{
bool Display();
}

class Interimpas:Interdemo
{
public bool Show()
{
Console.WriteLine("Show() method Implemented");
return true;
}

public static void Main(string[] args)
{
Interimpas inter = new Interimpas();
inter.Show();

Interdemo1 id = inter as Interdemo1;

if(null!=id)
{

bool ok = id.Display();
Console.WriteLine("Method Implemented");
}

else
{
Console.WriteLine("Method not implemented");
}
}
}

Avoiding Name Ambiguity

Suppose you are declaring same method definitions in two different interfaces. The compiler will naturally show an error due to the ambiguity of the implemented method. Even if you use the "is" keyword, the compiler still will show warnings. To avoid this, you have to follow the following syntax as shown:
Void .
{
//Body goes here
}
Following example illustrates the application of the preceding concept in detail:
using System;

interface Interdemo
{
void Show();
}

interface Interdemo1
{
void Show();
}


class Interclash:Interdemo,Interdemo1
{
void Interdemo.Show()
{
Console.WriteLine("Show() method Implemented");
}

void Interdemo1.Show()
{
Console.WriteLine("Display() method Implemented");
}

public static void Main(string[] args)
{
Interclash inter = new Interclash();
inter.Interdemo.Show();
inter.Interdemo1.Show();
}
}

Multiple inheritance using interfaces:

Multiple inheritance is not possible with classes but this can be achieved with the help of the interfaces.

Abstract Class versus Interface

1. A class can implement more than one interface but can only inherit from one abstract class.
2. An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
3. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public. An abstract class can contain access modifiers for the subs, functions, properties.
4. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method where as If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
5. No fields can be defined in interfaces where as an abstract class can have fields and constants defined.

***********Questions****************


Can an Interface contain fields?
No, an Interface cannot contain fields.

What is the difference between class inheritance and interface inheritance?
Classes and structs can inherit from interfaces just like how classes can inherit a base class or struct. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example depicting the same is shown below.

using System;
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}

//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}

//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}

public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}

public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}

2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

Can an interface inherit from another interface?

Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

Can you create an instance of an interface?

No, you cannot create an instance of an interface.

If a class inherits an interface, what are the 2 options available for that class?

Option 1: Provide Implementation for all the members inheirted from the interface.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}

class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

Option 2: If the class does not wish to provide Implementation for all the members inheirted from the interface, then the class has to be marked as abstract.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}

abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}


A class inherits from 2 interfaces and both the interfaces have the same method name as shown below. How should the class implement the drive method for both Car and Bus interface?

namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}

class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}

To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method type cast the demo object to the respective interface and then call the drive method.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}

class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}

static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}

What do you mean by "Explicitly Implemeting an Interface". Give an example?

If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An example is shown below.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}

class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}

static void Main()
{
Demo DemoObject = new Demo();

//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type cast the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}

Tuesday, August 18, 2009

Practical interview asp.net interview questions?

1.The XML file below has a list of employees. Your job is to bind the employee IDs and Names to a dropdownlist. ID must be dropdownlist value field and name must be the dropdownlist Text field. Also, only the active employees must be binded to the dropdownlist and the names should be in the ascending order. When I select a name from the dropdownlist, the name and ID of the selected employee must be printed on the webform.
Employees.xml


David
101
true


Tom
102
true


Rick
103
false


Mark
104
true



Code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Employees.xml"));

DataView DV = DS.Tables["Employee"].DefaultView;
DV.RowFilter = "IsActive='true'";
DV.Sort = "Name asc";

DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
---------------------------------------------------------------------------------
2.Write a custom function in c-sharp. The custom function parameters should be an instance of a dropdownlist, an xml file and a string?

The sample code for custom function is shown below. For this example to work drop the XML file in the root folder of the web application.

protected void Page_Load(object sender, EventArgs e)
{
PopulateDropdownlist(DropDownList1, "DropDownListSource.xml", "Select State");
}

public void PopulateDropdownlist(System.Web.UI.WebControls.DropDownList DropDownListObjectToBePopulated,string XMLFilePath, string InitialString)
{
try
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath(XMLFilePath));
if (InitialString != string.Empty)
{
ListItem LI = new ListItem(InitialString, "-1");
DropDownListObjectToBePopulated.Items.Add(LI);
}
foreach (DataRow DR in DS.Tables["State"].Rows)
{
ListItem LI = new ListItem();
LI.Text = DR["StateName"].ToString();
LI.Value = DR["StateCode"].ToString();
DropDownListObjectToBePopulated.Items.Add(LI);
}
}
catch(Exception Ex)
{
}
}
--------------------------------------------
3. How to read and write cookies in asp.net?


1. The following example shows how to write a "USER" cookie to a client's computer. The "USER" cookie, stores
FirstName
LastName
LastVisit

2. Create the user interface to enter FirstName and LastName.




3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}

4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}

5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.

Interview Questions with Design patterns in asp.net

Which of Gang of Four (GOF) design pattern is shown below?
public class A {
private A instance;
private A() {
}
public
static A Instance {
get
{
if ( A == null )
A = new A();
return instance;
}
}
}
1. Factory
2. Abstract Factory
3. Singleton
4. Builder
Answer : Singleton

C# Interview Questions on constructors

What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object.

In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.

Structs are not reference types. Can structs have constructors?

Yes, even though Structs are not reference types, structs can have constructors.

We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.

Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.

using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}

Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.

Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}

class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}

public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from child class");
}
}
}

If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Will the following code compile?
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
//Call the base class contructor from child class
public ChildClass() : base("A call to base class constructor")
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}

Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.

using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}

Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.

Can you have parameters for static constructors?
No, static constructors cannot have parameters.

What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?

1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Does C# provide copy constructor?
No, C# does not provide copy constructor.

What is an array?
An array is a data structure
that contains several variables of the same type.

What are the 3 different types of arrays?
1. Single-Dimensional
2. Multidimensional
3. Jagged

Are arrays value types or reference types?
Arrays are reference types.

Can you use foreach iteration on arrays in C#?
Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#.

What is Jagged Array?
A jagged array is an array of arrays.

What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.

Is there a way to clear all the rows from all the tables in a DataSet at once?
Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.

Can you enforce constarints and relations on tables inside a DataSet?
Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.



What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?
absoluteExpiration

A DateTime object that identifies when the data should be removed from the cache. If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.
slidingExpiration
A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.

Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object.

ASP.NET Interview Questions on Data Access Security

What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server
secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.

Why is "Connecting to SQL Server using Integrated Security" considered a best practice?
Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.

What is the advantage of storing an XML file in the applications App_Data folder? The contents of the App_Data folder will not be returned in response to direct HTTP requests.

What is Script injection?

A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.

What is SQL injection?

A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application.

What are the best practices to keep in mind when accepting user input on a web application?
1. Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.

What are the steps to follow to avoid Script Injection attacks?
1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode.

What are the steps to follow to avoid SQL Injection attacks?
Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together.

Can you encrypt view state data of an aspx page?

Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.

Thursday, August 13, 2009

How to log the Error/ Exceptions details into the event viewer using c#?

Any kind of exception or error can be logged into the event viewer using few lines of code by writing into Global.asax.cs file of your application.
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
/// Get reference to the source of the exception chain and log the exception into Event Log
void Application_Error(object sender, EventArgs e)
{
//Get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();

//Log the details of the exception and page state to the
//Windows 2000 Event Log
EventLog.WriteEntry("My Application",
"MESSAGE: " + ex.Message +
"\nSOURCE: " + ex.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + ex.TargetSite +
"\nSTACKTRACE: " + ex.StackTrace,
EventLogEntryType.Error);
}

How to remove white spaces between tags and lines of html render by asp.net page ?

When asp.net page loaded in to browser there are lots of white spaces between tags and in tags that will increase your html kb. For example if your page around 300 kb then it will take 3 second to load on 100 kbps internet connection and in dial up connection it will still take time. So if you want to load your site fast on dial up internet connection then you need to decrease html kb as much you can and removing white spaces from the html will be good idea for that.
Following is the code for the page on which you want to remove white spaces from the html. It will decrease your html kb by 30 percentage.

using System.Text;
using System.Text.RegularExpressions;

private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);

private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);


///
/// Initializes the object and calls on the child
/// controls of the to render.
///

/// The that receives the page content.
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
this.Page.Title = CommonFunctions.HtmlEncode(this.Page.Title);
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();

html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

writer.Write(html.Trim());
}

}

How to move the files from one folder to another folder using C#?

Files can be moved from source to destination using System.IO namespace in c#.
This code will move the files from source directory having 1 sub level of directory or not.
string destination = string.Empty;
string source = string.Empty;
destination = Server.MapPath("Destination");
source = Server.MapPath("Source");

//follwing code can used to move the directory files from one folder to
//another
DirectoryInfo dir = new DirectoryInfo(source);
if (dir.Exists)
{
DirectoryInfo[] subDirs = dir.GetDirectories();
if (subDirs.Length > 0)
{
foreach (DirectoryInfo d in subDirs)
{
FileInfo[] files = d.GetFiles();
foreach (FileInfo f in files)
{
f.MoveTo(destination);
}
}
}
else
{
FileInfo[] files = dir.GetFiles();
if (files.Length > 0)
{
foreach (FileInfo f in files)
{
//f.CopyTo(destination);

f.MoveTo(Path.Combine(destination, f.Name));
}
}
else
{
Response.Write("file does not exists");
}
}
}
else
{
Response.Write("Source Directory Does not exists");
}

Monday, August 10, 2009

Web Application Performance – Caching and compressing the multiple JavaScript and css files.

Performance is the main target in the web applications development. One of the major factors that can boost the performance of the site is rendering of the JavaScript and css files. It is always better to have small number of java script files instead of one large file for better code maintainability, but bad in terms of web site performance. If your application contains large number of java script and css files that needs to be rendered, always makes one HTTP request per file. So, if you have four JavaScripts and three CSS files loaded by a page, you are wasting time in seven network roundtrips. The browser cannot show the page properly until CSS and JavaScripts are fully loaded.
Here is one solution where developer can create an handler process the combination of different javascript files by caching and compressing the files. In order to achieve this add the various reference keys in the web config as follows:



CommonCssVersionNo and CommonJsVersionNo keys are used to make the cache key used in caching the combined multiple javascript file. So in changes made in javascript file needs to change their corresponding version keys in web.config file in order to expire that cache and render with new javascript files.

In the page header part add the following code to render the javascript and css files.



ReadConfiguration.CommonCssVersionNo is used to read the version no of common css files based on which css files are rendered by either from cache if same version found or first cache them and then render it.
ApplicationPath.GetApplicationPath is used to get the complete application path of the application.
HttpCombiner.ashx is handler class which process the request for rendering the javascript and css files by caching and compressing them. This class contains the following code :


using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;

namespace MyApplication
{
public class HttpCombiner : IHttpHandler
{


private const bool DO_GZIP = true;
private readonly static TimeSpan CACHE_DURATION = TimeSpan.FromDays(3);
public void ProcessRequest(HttpContext context)
{

HttpRequest request = context.Request;

// Read setName, contentType and version. All are required. They are
// used as cache key
string setName = request["s"] ?? string.Empty;
string contentType = request["t"] ?? string.Empty;
string version = request["v"] ?? string.Empty;

// Decide if browser supports compressed response
bool isCompressed = DO_GZIP && this.CanGZip(context.Request);

// Response is written as UTF8 encoding. If you are using languages like
// Arabic, you should change this to proper encoding
UTF8Encoding encoding = new UTF8Encoding(false);

// If the set has already been cached, write the response directly from
// cache. Otherwise generate the response and cache it
if (!this.WriteFromCache(context, setName, version, isCompressed, contentType))
{
using (MemoryStream memoryStream = new MemoryStream(5000))
{
// Decide regular stream or GZipStream based on whether the response
// can be cached or not
using (Stream writer = isCompressed ?
(Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) :
memoryStream)
{

// Load the files defined in and process each file
string setDefinition =
System.Configuration.ConfigurationManager.AppSettings[setName] ?? "";
string[] fileNames = setDefinition.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);

foreach (string fileName in fileNames)
{
byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
writer.Write(fileBytes, 0, fileBytes.Length);
}

writer.Close();
}

// Cache the combined response so that it can be directly written
// in subsequent calls
byte[] responseBytes = memoryStream.ToArray();
context.Cache.Insert(GetCacheKey(setName, version, isCompressed),
responseBytes, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
CACHE_DURATION);

// Generate the response
this.WriteBytes(responseBytes, context, isCompressed, contentType);
}
}
}

private byte[] GetFileBytes(HttpContext context, string virtualPath, Encoding encoding)
{
if (virtualPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
{
using (WebClient client = new WebClient())
{
return client.DownloadData(virtualPath);
}
}
else
{
string physicalPath = context.Server.MapPath(virtualPath);
byte[] bytes = File.ReadAllBytes(physicalPath);
// TODO: Convert unicode files to specified encoding. For now, assuming
// files are either ASCII or UTF8
return bytes;
}
}

private bool WriteFromCache(HttpContext context, string setName, string version,
bool isCompressed, string contentType)
{
byte[] responseBytes = context.Cache[GetCacheKey(setName, version, isCompressed)] as byte[];

if (null == responseBytes || 0 == responseBytes.Length) return false;

this.WriteBytes(responseBytes, context, isCompressed, contentType);
return true;
}

private void WriteBytes(byte[] bytes, HttpContext context,
bool isCompressed, string contentType)
{
HttpResponse response = context.Response;

response.AppendHeader("Content-Length", bytes.Length.ToString());
response.ContentType = contentType;
if (isCompressed)
response.AppendHeader("Content-Encoding", "gzip");

context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
context.Response.Cache.SetMaxAge(CACHE_DURATION);
context.Response.Cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

response.OutputStream.Write(bytes, 0, bytes.Length);
response.Flush();
}

private bool CanGZip(HttpRequest request)
{
string acceptEncoding = request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding) &&
(acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")))
return true;
return false;
}

private string GetCacheKey(string setName, string version, bool isCompressed)
{
return "HttpCombiner." + setName + "." + version + "." + isCompressed;
}

public bool IsReusable
{
get
{
return true;
}
}
}
}

This handler is responsible for caching compressing and rendering of the javascript and css files which will boost the performance of the web application.