Monday, June 25, 2007

Color Picker control in ASP.NET

      Recently I have to use color picker control in my project so that each user has its own UI. The best color picker example I found on blogger.com. This inspired me to create my own color picker control. 

      You can find the user control here.

Happy Programming !!

Wednesday, June 20, 2007

Create/Delete/View Virtual Directory or Website in IIS using C#

     Hi, in my previous atrlicle I show how to create virtual directory. Here I have attched the code for creating , deleteing or listing virtual directories or website in IIS using ASP.NET and C#. 

    Code uses DirectoryService name space which allows access to Internet Information Services (IIS). The System.DirectoryServices namespace also provides access to the Active Directory. The classes in this namespace can be used with any of the Active Directory service providers including Internet Information Services (IIS), the Lightweight Directory Access Protocol (LDAP), the Novell Directory Services in NetWare (NDS), and WinNT.

   Following softeares are required for this project to run successfully.

   * IIS 5.1 or later version
   * Dotnet SDK 2.0
   * Admin access to server on which IIS in installed

     You can download the Source Code  here. Once you download the file pls change the extension from “doc” to “zip”.    

        Sorry for uploading the code this way. I do not found any option to upload zip file. :)

Happy Programming !!

Tuesday, June 19, 2007

PNG issue in IE 6 or previous version

      In my recent project, I found a starnge behaviour of PNG file. We have created PNG files with transparent back ground for logo. Everything is working fine in IE 7 , Opera, Firefox and even in Safari. However when we saw the image in IE 6 we found a problem that it does not display as transparent back ground.

    Here is the PNG file with transparent back ground. Just save it to your PC and than open it in IE. If you have IE 6 than you can see light blue back ground and if you have IE 7 it will be transparent.

    Below is the html page that display png image.

<html>
<head>
<title>PNG in IE: JS Inc File </title>

<!-- Add below 3 lines in Head section as shown here. -->

<!--[if lt IE 7]>
<script defer type="text/javascript" src="pngfix.js"></script>
<![endif]-->

</head>
<body>
<div class="content">
<h1>PNG in Windows IE: Inc File Demo </h1>
<p>IE now renders this PNG image properly. View the source to see how
to use the JS Include file method.</p>
<img src="AboutUSIcon.png" alt="a PNG logo" />
</div>
</body>
</html>

Fig (1) HTML page that shows PNG file.

  

   Below is the javascript for "pngfix.js" file.Copy the above JS in new file and name it "pngfix.js". 


var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

if ((version >= 5.5) && (document.body.filters))
{
     for(var i=0; i<document.images.length; i++)
     {
             var img = document.images[i]
             var imgName = img.src.toUpperCase()
             if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
            {
                    var imgID = (img.id) ? "id='" + img.id + "' " : ""
                    var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='"
                                                  + img.alt + "' "
                    var imgStyle = "display:inline-block;" + img.style.cssText
                    if (img.align == "left") imgStyle = "float:left;" + imgStyle
                    if (img.align == "right") imgStyle = "float:right;" + imgStyle
                    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle
                                   + " style=\"" + "width:" + img.width + "px; height:" + 
                                    img.height + "px;" + imgStyle + "" + 
                                   "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                                   + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                  
                    img.outerHTML = strNewHTML
                   i = i-1
            }
     }
}  

Fig (2) Content of "pngfix.js"" file

Happy Programming !! 

Wednesday, June 13, 2007

Moving Options/values up and down in list box using javascript

         Recently I found a really good article on moving options up and down in list box using javascript. Here is the link.

Happy Programming !!

Moving value from one list box to other list box using javascript

           Recent ly I found a really good article on moving value from one list box to another list box using javascript. Here is the link.

Happy Programming !!

Wednesday, June 06, 2007

Shadow Copying

A fantastic feature of ASP.NET is that the code for a Web site can be changed on the fly without shutting down the Web server. When a Web site's file is changed on the hard disk, ASP.NET detects this, unloads the AppDomain that contains the old version of the files (when the last currently running request finishes), and then creates a new AppDomain, loading into it the new versions of the files. To make this happen, ASP.NET uses an AppDomain feature called
shadow copying.

Shadow Copying Assemblies

Shadow copying allows assemblies that are used in an application domain to be updated without unloading the application domain. This is particularly useful for applications that must be available continuously, such as ASP.NET sites.

The common language runtime locks an assembly file when the assembly is loaded, so the file cannot be updated until the assembly is unloaded. The only way to unload an assembly from an application domain is by unloading the application domain, so under normal circumstances, an assembly cannot be updated on disk until all the application domains that are using it have been unloaded.

When an application domain is configured to shadow copy files, assemblies from the application path are copied to another location and loaded from that location. The copy is locked, but the original assembly file is unlocked and can be updated.

The following list describes how to use the properties of the AppDomainSetup class to configure an application domain for shadow copying.

  • Enable shadow copying by setting the ShadowCopyFiles property to the string value "true".

    By default, this causes all assemblies in the application path to be copied to a download cache before they are loaded. This is the same cache maintained by the common language runtime to store files downloaded from other computers, and the common language runtime automatically deletes the files when they are no longer needed.

A little example

Let's come to the point. How to enable this kind of stuff in your own application? A really simple and short example:

First, write a method to create a new app domain to host the new version of the assembly. As you might know, it's impossible to unload an assembly once loaded in an appdomain, you can only unload the associated appdomain entirely. What the following method does is pretty straightforward: it tells the CLR (assembly loader) where to look for files and then tells it to enable shadow copying by setting the (wrong-typed; a boolean property would have been much better) ShadowCopyFiles property to the string "true". Next, an appdomain is created with a unique name using some counter, and the assembly with the functionality is loaded (notice the _ indicates private members of the current class). This method is called when the app starts.

private void LoadAppDomain()
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "c:\\temp";
setup.ShadowCopyFiles = "true";
AppDomain domain = AppDomain.CreateDomain("ShadowCopy
domain " + _domainNumber, null, setup);
_currentAssembly = domain.Load("Server", null);
_domainNumber++;
}

Add items in Drop Down List or List Box using Javascript

        I have seen lots of questions in diffrent forums for adding items in drop down list or list box using javascript. Below is the script for the same.

 

<script type="text/javascript">
function AddItem(Text,Value)
{
// Create Option object
var opt = document.createElement("option");



// Add Option to Dropdown/Listbox
document.getElementById
("DropDownList").options.add(opt);

// Assign text and value to option
opt.text = Text;
opt.value = Value;


}
<script />
        You can use this function in for loop and add more than one Items.
Happy Programming !!

Monday, June 04, 2007

Create Virtual Directory in IIS using C#

            In my recent project I need to create virtual directory in IIS programmatically.  I was searching on net and found a really good article posted by Dipali Choksi. You can find the artilce here. I have copied that article below for my reference.

 

Using System.DirectoryServices;
private
void btnCreateDirectory_Click(object sender, EventArgs e)
{
          string strSchema = "IIsWebVirtualDir";
          string strRootSubPath = "/W3SVC/1/Root" ;

           // you can specify any server name , "localhost" is for example
           DirectoryEntry deRoot =
                        new DirectoryEntry("IIS://" + "localhost" + strRootSubPath);
         try
        {
                 deRoot.RefreshCache();
                 DirectoryEntry deNewVDir =
                                    deRoot.Children.Add("Name of Virtual Directory", strSchema);

                 deNewVDir.Properties["Path"].Insert(0, "Path for Virtual Directory");
                 deNewVDir.CommitChanges();
                 deRoot.CommitChanges();

                // Create a Application
                if (strSchema == "IIsWebVirtualDir")
                           deNewVDir.Invoke("AppCreate", true);
                // Save Changes
                           deNewVDir.CommitChanges();
                
                deRoot.CommitChanges();
                deNewVDir.Close();
                deRoot.Close();
                lblResult.Text = "Virtual Directory "
                                   + ("Name of Virtual Directory"+ "(" + "Path for Virtual
                                             Directory
" + ") has  been created";
       }
      catch (Exception ex)
     {
                lblResult.Text = ex.Message;
      }
}

Fig (1) Code to create virtual directory using C#

Monday, May 28, 2007

Thousand Separator function for Java Script

     In my project, I have to display the total of selected item in thousand separated format. I am using java script to find total of selected values. Now I have to display the result in Thousand deperated format (like 12,345.00). Here the function that I have used to do that.   

 

 <script language = "javascript">
function ThousandSeparator(decimalDigits,Value)
{

// Separator Length. Here this is thousand separator
var separatorLength = 3;

var OriginalValue=Value;

var TempValue = "" + OriginalValue;

var NewValue = "";

// Store digits after decimal
var pStr;

// store digits before decimal
var dStr;

// Add decimal point if it is not there
if (TempValue.indexOf(".")==-1){TempValue+="."}

dStr=TempValue.substr(0,TempValue.indexOf("."));

pStr=TempValue.substr(TempValue.indexOf("."))

// Add "0" for remaining digits after decimal point
while (pStr.length-1< decimalDigits){pStr+="0"}

if(pStr =='.') pStr ='';

if(dStr.length > separatorLength)
{
// Logic of separation
while( dStr.length > separatorLength)
{
NewValue = "," + dStr.substr(dStr.length - separatorLength) + NewValue;
dStr = dStr.substr(0,dStr.length - separatorLength);
}

NewValue = dStr + NewValue;

}
else
{
NewValue = dStr;
}


// Add decimal part
NewValue = NewValue + pStr;

// Show Final value
alert(NewValue);



}

</script>
 Fig (1) Thousand Separator Function in Java Script

   You just need to  pass 2 parameters. Number of digits require after decimal point and value you want to conver in thousand seperated format.


Happy Programming !!

Saturday, May 26, 2007

An error occured while establishing a connection to server. When connectiing to SQL Server 2005,...SQL Network Interfaces, error:26 - Error Locating Server/Instance Specified.

      I have seen this error so many time so I thought that let me post the solution that work for me. First thing check your connection string that it points correct server. This is the most common mistake. Sometime connection string points to SQL Express, while machine does not have SQL Expressed installed.

      If the connection string is correct, second step is to check congiguration of SQL. Click on Start - All Programms - Sql Server 2005 - Configuration Tool - SQL Server Configuration Manager. 

      Click on SQL Server 2005 Network configuration - Protocols for MS SQL Server. Make sure that TCP/IP and Named Piped are Enable. If not that enable it. Now click on SQL Server 2005 Services. Restart Sql Server Browser Service and then restart SQL Server (MSSQLSERVER) service. Yupiiii !!! its all. Check your application now your error should be resolved.

Happy Programming !!

Thursday, May 24, 2007

Disable right click on page.

       Here is the code to disable right click on page.

<html>
<body oncontextmenu="return false;">
     Try right click.
</body>
</html>

   Happy Programming !!

Prototype.js

       Today while surfing, I found a good javascript framework Prototype.js. It is a JavaScript library written by Sam Stephenson. This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.

       This framework helps the developers to write a good javascript witout knowing much about syntax of javascript and reduce the overhead of remembering lots of complex function.

      You can download this library from here.

       Here is a really good artilce which explains few methods of prototype.js with examples.

UML Diagrams

      I have to create class and Sequence diagrams in my recent project. I was searching for for some quick and good material for UML diagrams. I found the really cool article here.

Thursday, May 03, 2007

Custom DateTime Format Specifier

      Yesterday during surfing I foud really important material on net. I was feeling sleepy so not addded site in favorite and hence notable to give reference here. However I have copied the content in notepad. Its really very helpfull.

d

Displays the current day of the month.

dd

Displays the current day of the month, where values < 10 have a leading zero.

ddd

Displays the three-letter abbreviation of the name of the day of the week.

dddd(+)

Displays the full name of the day of the week represented by the given DateTime value.

f(+)

Displays the x most significant digits of the seconds value. The more f's in the format specifier, the more significant digits. This is total seconds, not the number of seconds passed since the last minute.

F(+)

Same as f(+), except trailing zeros are not displayed.

g

Displays the era for a given DateTime (for example, "A.D.")

h

Displays the hour, in range 112.

hh

Displays the hour, in range 112, where values < 10 have a leading zero.

H

Displays the hour in range 023.

HH

Displays the hour in range 023, where values < 10 have a leading zero.

m

Displays the minute, range 059.

mm

Displays the minute, range 059, where values < 10 have a leading zero.

M

Displays the month as a value ranging from 112.

MM

Displays the month as a value ranging from 112 where values < 10 have a leading zero.

MMM

Displays the three-character abbreviated name of the month.

MMMM

Displays the full name of the month.

s

Displays the number of seconds in range 059.

ss(+)

Displays the number of seconds in range 059, where values < 10 have a leading 0.

t

Displays the first character of the AM/PM indicator for the given time.

tt(+)

Displays the full AM/PM indicator for the given time.

y/yy/yyyy

Displays the year for the given time.

z/zz/zzz(+)

Displays the timezone offset for the given time.

 

       Take a look at the following lines of code, which demonstrate using string format specifiers to create custom-formatted date and time strings:  

DateTime dt = DateTime.Now;
Console.WriteLine(string.Format(
"Default format: {0}", dt.ToString()));
Console.WriteLine(dt.ToString(
"dddd dd MMMM, yyyy g"));
Console.WriteLine(string.Format(
("Custom Format 1: {0:MM/dd/yy hh:mm:sstt}", dt));
Console.WriteLine(string.Format(
("Custom Format 2: {0:hh:mm:sstt G\\MT zz}", dt));
 

Here is the output from the preceding code:

Default format: 9/24/2005 12:59:49 PM
Saturday 24 September, 2005 A.D.
Custom Format 1: 09/24/05 12:59:49PM

Custom Format 2: 12:59:49PM GMT -06


Happy Programming!!

Monday, April 30, 2007

HTTP 405 -Resource not allowed Error in IIS

       When attempting to POST to a web page in Internet Information Services (IIS) 5.1 under Windows 2000 (Win2k) or Windows XP, you may receive the following error:

The page cannot be displayed The page you are looking for cannot be displayed because the page address is incorrect.

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

Please try the following: If you typed the page address in the Address bar, check that it is entered correctly. Open the 127.0.0.1 home page and then look for links to the information you want. HTTP 405 - Resource not allowedInternet Information Services

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

Technical Information (for support personnel) More information:Microsoft Support 

Fig - (1) HTTP 405

Cause

         The file type is not registered in the IIS script map settings (e.g. .html or .htm). IIS 5.1 only allows HTTP requests of type to GET to unmapped files. HTTP requests of type POST, HEAD, and all others are responded to with a 405 resource not allowed error.

          As a security note, you should always remove unused script mappings. This is the default behavior of IIS 6, which will only serve named extensions and refuse all others.

Solution

           Add a script map for the extension. A script map associates a particular file type with a given script module. The web server runs the module on the given file and sends the output to the browser, instead of sending the file directly to the browser.

  1. Go to "Control Panel"-"Administrative Tools"-"Internet Information Services".
  2. Expand the tree to "COMPUTERNAME"-"Web Sites"-"Default Web Site".
  3. Right-click on "Default Web Site" and select "Properties". (Alternately, select "Default Web Site" and press Alt+Enter.)
  4. Select the "Home Directory" tab.
  5. Click the "Configuration" button.
  6. From the "Mappings" tab, select the "Add" button.
  7. Click the "Browse..." button, choose "Dynamic Link Libraries *.dll" from the "Files of Type" dropdown, and select c:\WINDOWS\System32\inetsrv\asp.dll.
  8. Type ".html" (without quotes) in the "Extension" box.
  9. Select the "Limit to:" radio button, and type in "GET, POST" (without quotes) in the box next to it.
  10. Click the "OK" button and close all the dialogs. (If the "OK" button is greyed out, then make sure all the entries are correct and try clicking in the file name box.)

You must adjust the above instructions to your particular OS, web site configuration, and file type. You can associate the file type with a different script engine besides asp.dll, which is the ASP 3.0 script engine. There is no need to give IWAM_COMPUTERNAME permission to the file, only IUSR_COMPUTERNAME needs NTFS read and execute permission.

Happy Programming!!

Friday, April 20, 2007

ASP.NET Session State Management Using SQL Server

            Web applications are by nature stateless. Statelessness is both an advantage and a disadvantage. When resources are not being consumed by maintaining connections and state, scalability is tremendously improved. But the lack of state reduces functionality severely. Ecommerce applications require state to be maintained as the user navigates from page to page. ASP.NET’s Session object makes it easy for developers to maintain state in a Web application. State can be maintained in-process, in a session state server, or in SQL Server.

           In-process state management is the ASP.NET default, and it offers the fastest response time, but does not work in a Web farm. Consequently, it is not practical in high capacity Web applications requiring the load to be spread over multiple servers. A dedicated session state server is shared by all servers in a Web farm, so it provides scalability of the Session objects across all Web servers. It cannot store state persistently. If a dedicated session state server goes down for any reason, all session state data is lost. SQL Server is another alternative for storing session state for all of the servers in a Web farm. Since SQL Server is a database, there is a popular misconception that ASP.NET session state maintained in SQL Server is stored persistently. By default, it is not. If the SQL Server is stopped, the session state data is lost. By making a few simple changes, state can be stored persistently. It is important to understand that persistent is not the same thing as permanent. ASP.NET places a time limit (timeout in web.config) on how long a session’s state is maintained. If the SQL Server is configured to store state persistently and it is down for longer than the ASP.NET session timeout interval, the session state data is lost.

Configuring ASP.NET Session State Management

             Use the sessionState section of the web.config file to configure an ASP.NET Web application to use a SQL Server for session state management. The session state timeout interval is specified by using the timeout parameter.

 

<!--  SESSION STATE SETTINGS
        By default ASP .NET uses cookies to identify which requests
        belong to a particular session.
        If cookies are not available, a session can be tracked by
        adding a session identifier to the URL.
        To disable cookies, set sessionState cookieless="true".
-->
<sessionState
   _ mode="SQLServer"
   _ stateConnectionString="tcpip=127.0.0.1:42424"
   _ sqlConnectionString="data source=127.0.0.1; integrated security=true"
   _ cookieless="false"
   _ timeout="20"
/>

 

               Configure the SQL Server to store Session objects by running a script to create the ASPState database. Version 1.0 of the .NET Framework provides a state database configuration script in %SYSTEMROOT%\Microsoft.NET\Framework\v1.0.3705\InstallSqlState.sql. If you open the file, you will see a statement to create a database called ASPState. This probably adds to the confusion about state being persistent. The ASPState database contains stored procedures that create tables in tempdb. The tables in tempdb are where session state is actually stored. Thus, when the SQL Server is shutdown, all session state is lost. This raises an important question: If the SQL Server is never shutdown, will tempdb eventually become 100 percent full and run out of space? Recall that ASP.NET connections automatically time out and their resources are freed up after the timeout duration is exceeded. The InstallSqlState.sql script creates a job called ASPState_Job_DeleteExpiredSessions to delete expired sessions from tempdb. Recall that ASP.NET does not keep session resources alive indefinitely. To support this feature when a SQL Server is used to maintain state, the SQL Server Agent must be running so that the expired session deletion job runs as needed. By default, the job is scheduled to run every minute. It deletes session state rows with an Expires value less than the current time. The account under which the SQL Server Agent runs must have the privilege to execute the DeleteExpiredSessions stored procedure.

          ASPState database scripts come in pairs. InstallSqlState.sql creates the database and supporting objects. UninstallSqlState.sql drops the database and all supporting objects (e.g., the job to delete expired sessions). You cannot drop a database if it is in use, so if the UninstallSqlState.sql script fails with this error message:


Server: Msg 3702, Level 16, State 4, Line 4
Cannot drop the database 'ASPState' because it is currently in use.


 

Microsoft Knowledge Base article 311209 says to stop the Web server service to overcome this error. An “uninstallation” failure can still occur even if the Web server service is stopped. Additionally, you might not want to stop the Web server service because that will cause all Web applications on the server to stop. Instead, use the SQL Server Enterprise Manager. Find the processes accessing the ASPState database and delete them. If users are still accessing the application and causing new processes to be created faster than you can delete them, go to the IIS console and select the Properties for the Web application. On the Directory tab, click the Remove button. This will prevent access to the Web application and allow you to kill any remaining processes accessing the ASPState database. Once the processes are gone, uninstallation should completely successfully. Be sure to go back to the IIS console and click the Create button to restore the Web application to normal working order if you previously clicked the Remove button.

Version 1.0 of the .NET Framework does not provide a script for creating an ASPState database that maintains state persistently. However, Microsoft Knowledge Base article 311209 does provide a link for downloading InstallPersistentSqlState.sql and UninstallPersistentSqlState.sql. The InstallPersistentSqlState.sql script causes the session state data to be stored in permanent tables in ASPState instead of temporary tables in tempdb.

Version 1.1 of the .NET Framework provides both InstallPersistentSqlState.sql and InstallSqlState.sql. The Framework Version 1.1 scripts are found in the %SYSTEMROOT%\Microsoft.NET\Framework\v1.1.4322 folder. Although the 1.0 and 1.1 versions of InstallPersistentSqlState.sql accomplish the same thing, they are different. For SQL Server 2000 and above, the 1.1 version creates the ASPState stored procedures using GETUTCDATE instead of GETDATE. The 1.0 version always uses GETDATE. You can use the Framework version 1.1 script to create a database for an application using the Framework version 1.0.

If you specify integrated security in the web.config file, you will have to create a server login for the ASPNET user and then make the login a user in the ASPState database. You will also have to grant permissions to the ASPNET user to use database objects. If you do not store state persistently, the ASPNET user must be granted permissions to use state management objects in tempdb. The prudent approach is to grant no more permissions than are absolutely necessary. Here are the permissions I granted after executing the Version 1.0 InstallSqlState.sql script:


USE masterGOEXECUTE sp_grantlogin [DBAZINE\ASPNET]GO USE ASPState GO EXECUTE sp_grantdbaccess [DBAZINE\ASPNET] GRANT EXECUTE on TempGetAppId to [DBAZINE\ASPNET] GRANT EXECUTE on TempGetStateItemExclusive to [DBAZINE\ASPNET] GRANT EXECUTE on TempInsertStateItemShort to [DBAZINE\ASPNET] GO USE tempdb -- remove this if using persistent state GO -- remove this if using persistent state EXECUTE sp_grantdbaccess [DBAZINE\ASPNET] -- remove this if persistent state GRANT SELECT on ASPStateTempApplications to [DBAZINE\ASPNET] GRANT INSERT on ASPStateTempApplications to [DBAZINE\ASPNET] GRANT SELECT on ASPStateTempSessions to [DBAZINE\ASPNET] GRANT INSERT on ASPStateTempSessions to [DBAZINE\ASPNET] GRANT UPDATE on ASPStateTempSessions to [DBAZINE\ASPNET] GO


 

If you use the InstallPersistentSqlState.sql, remove the three lines as indicated above.

Consider the grants shown above as a starting point for creating your own script appropriate for your environment.

Conclusion


ASP.NET offers two simple solutions to session state management in a Web farm. Only SQL Server offers persistent state management. A dedicated session state server does not offer persistent state management, but does not require the creation of a database (one more thing for the DBA to administer). The value of persistent state has to be weighed carefully. Maintaining session state persistently is useful only if the SQL Server can be brought back up within the session state timeout specified in the web.config. For those situations where using a SQL Server as a state server makes sense, ASP.NET makes it easy.

Referenced from this article.

Happy Programming!!!

Thursday, April 19, 2007

Unable to load DLL 'ABCpdfCE6.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

    This is a common error that may occure while you are using ABCPDF to generate PDF in asp.net. If you install the component on your machine and use that in application it works fine. However when you copy that application on a machine on which component is not installed, it throws eception as "Unable to load DLL 'ABCpdfCE6.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)".

     Solution to this issue is mentioned below.

1. Check that you have properly added the reference of "ABCpdf.DLL" in your application.

2. Copy "ABCpdfCE6.dll" in your bin folder. You can found this dll at "C:\Program Files\WebSupergoo\ABCpdf6 .NET\Common\" on machine where you had install the component.

 

Happy Programming !!

Create PDF in ASP.NET

           In my current web application I have to genarate PDF for subcription information and need to attach in email. I was searching a component which can generate PDF from HTML content. ABC PDF is really a cool component to generate PDF and really simple to use in application. You can find the trial version here.

Happy Programming !!

Wednesday, April 18, 2007

Session Management in ASP.NET

ASP.NET Session State: Architectural and Performance Considerations

I recently came across a great post on one of the internal forums describing the strengths and weaknesses of different ASP.NET session state strategies.

As you're probably aware, state management is an important consideration for web developers. The HTTP protocol is connectionless, so any web application that persists data across multiple web page requests needs some mechanism to ensure this session-based data is maintained. Examples of session-based data include shopping carts (on an ecommerce site), the currently logged-on user credentials, and other application-specific data that would normally be held on a client. Various strategies have been utilised over the last few years, including hidden forms, cookies and server-based state engines. Of these choices, the latter is perhaps architecturally most attractive since it reduces the dependence on a client; unfortunately, maintaining session state on the server can be expensive on resources and makes it hard to scale out using web farms or secure pages with HTTPS.

Enter the ASP.NET session state engine, which attempts to make server-side session state a much more viable option. ASP.NET offers three separate choices for session state storage when it's switched on: locally on the server (InProc), remotely in a SQL Server database (SqlServer), or remotely using a session state service (StateServer). I'll go through each of those options and compare the benefits of each.

InProc

The local option is not dissimilar to that provided by ASP, in that it requires all requests to come to the same physical server rather than being randomly split across multiple IIS machines. The upside is that it's very fast (it runs in-process), and it's simple to implement. If you've just got one web server, this is the best choice in most scenarios. The only time when you might want to consider something else in this scenario is when the session data is expensive to rebuild, since any InProc session data is flushed when the ASP.NET worker process or IIS restarts. If, for example, you're maintaining a shopping cart as local session data that gets cleared out, you risk annoying customers sufficiently that they take their business elsewhere.

For multiple servers, InProc is unsuitable unless you can implement some form of server affinity, so that every time a particular client requests a web page they are directed back to that same server. Services such as Network Load Balancing (part of Windows Server 2003 Enterprise Edition) can provide this, although they inevitably add their own overhead.

StateServer

I've come across a few developers who haven't come across this choice. The state server relies on a Windows service which is disabled by default, which perhaps explains why people haven't noticed it - go to Administrative Tools / Services and enable the ASP.NET State Service to get it working. You can run the state service on a dedicated machine or shared with a web server host; the main requirement to make this service work efficiently is plenty of RAM. Because the service is isolated from IIS, you can restart IIS without losing the session data contained within it, and you can point multiple distributed ASP.NET boxes at the same service, thereby removing server affinity issues. However, the session data isn't persisted onto disk, so it can't be backed up and a server reboot will lose the data. On the plus side, you don't need SQL Server or anything beyond a Windows licence to run it, making this option easy to set up and maintain. This option is however signficantly slower than using InProc, due to network latency and roundtrip costs. Keeping the state server on a dedicated private LAN with the other web server boxes will help.

Finally, don't forget that you can run the ASP.NET State Service in a single web server environment - this provides durability against IIS restarts, but at a performance cost due to it running out of process.

SqlServer

This is the high-end option in terms of flexibility and reliability, but is also the most expensive to build and maintain. Rather than storing session data in memory, it is persisted to a SQL Server instance. It's more reliable than any of the other approaches, since the data is persisted in a more durable form (e.g. it will survive a server restart and can be backed up). You can even use SQL Server clustering support to increase session state reliability still further. From a performance point of view, it's generally comparable to the StateServer service when you've got multiple web servers using it for session state. The session state itself is stored as a BLOB in a persisted or temporary table, which can reduce the serialization cost but makes it harder to view the session data itself.

In most cases, integrated Windows authentication is the best choice, preferably utilising Kerberos (NTLM requires an extra roundtrip for authentication). Connection pooling can be used to minimise the initial performance hit.

Happy Programming !!

Session Management in ASP.NET

ASP.NET Session State: Architectural and Performance Considerations

I recently came across a great post on one of the internal forums describing the strengths and weaknesses of different ASP.NET session state strategies. Its author, J.D. Meier, has graciously given me permission to use it as the basis of a blog entry.

As you're probably aware, state management is an important consideration for web developers. The HTTP protocol is connectionless, so any web application that persists data across multiple web page requests needs some mechanism to ensure this session-based data is maintained. Examples of session-based data include shopping carts (on an ecommerce site), the currently logged-on user credentials, and other application-specific data that would normally be held on a client. Various strategies have been utilised over the last few years, including hidden forms, cookies and server-based state engines. Of these choices, the latter is perhaps architecturally most attractive since it reduces the dependence on a client; unfortunately, maintaining session state on the server can be expensive on resources and makes it hard to scale out using web farms or secure pages with HTTPS.

Enter the ASP.NET session state engine, which attempts to make server-side session state a much more viable option. ASP.NET offers three separate choices for session state storage when it's switched on: locally on the server (InProc), remotely in a SQL Server database (SqlServer), or remotely using a session state service (StateServer). I'll go through each of those options and compare the benefits of each.

InProc

The local option is not dissimilar to that provided by ASP, in that it requires all requests to come to the same physical server rather than being randomly split across multiple IIS machines. The upside is that it's very fast (it runs in-process), and it's simple to implement. If you've just got one web server, this is the best choice in most scenarios. The only time when you might want to consider something else in this scenario is when the session data is expensive to rebuild, since any InProc session data is flushed when the ASP.NET worker process or IIS restarts. If, for example, you're maintaining a shopping cart as local session data that gets cleared out, you risk annoying customers sufficiently that they take their business elsewhere.

For multiple servers, InProc is unsuitable unless you can implement some form of server affinity, so that every time a particular client requests a web page they are directed back to that same server. Services such as Network Load Balancing (part of Windows Server 2003 Enterprise Edition) can provide this, although they inevitably add their own overhead.

StateServer

I've come across a few developers who haven't come across this choice. The state server relies on a Windows service which is disabled by default, which perhaps explains why people haven't noticed it - go to Administrative Tools / Services and enable the ASP.NET State Service to get it working. You can run the state service on a dedicated machine or shared with a web server host; the main requirement to make this service work efficiently is plenty of RAM. Because the service is isolated from IIS, you can restart IIS without losing the session data contained within it, and you can point multiple distributed ASP.NET boxes at the same service, thereby removing server affinity issues. However, the session data isn't persisted onto disk, so it can't be backed up and a server reboot will lose the data. On the plus side, you don't need SQL Server or anything beyond a Windows licence to run it, making this option easy to set up and maintain. This option is however signficantly slower than using InProc, due to network latency and roundtrip costs. Keeping the state server on a dedicated private LAN with the other web server boxes will help.

Finally, don't forget that you can run the ASP.NET State Service in a single web server environment - this provides durability against IIS restarts, but at a performance cost due to it running out of process.

SqlServer

This is the high-end option in terms of flexibility and reliability, but is also the most expensive to build and maintain. Rather than storing session data in memory, it is persisted to a SQL Server instance. It's more reliable than any of the other approaches, since the data is persisted in a more durable form (e.g. it will survive a server restart and can be backed up). You can even use SQL Server clustering support to increase session state reliability still further. From a performance point of view, it's generally comparable to the StateServer service when you've got multiple web servers using it for session state. The session state itself is stored as a BLOB in a persisted or temporary table, which can reduce the serialization cost but makes it harder to view the session data itself.

In most cases, integrated Windows authentication is the best choice, preferably utilising Kerberos (NTLM requires an extra roundtrip for authentication). Connection pooling can be used to minimise the initial performance hit.

Happy Programming !!