Monday, July 30, 2007

Debugging JavaScript in MAC Safari / Tool to debug JavaScript in Safari

      Safari has inbuilt debug menu for java script. By default it is hidden. Safari's "Debug" menu allows you to turn on the logging of JavaScript errors. To display the debug menu in Mac OS X, open a Terminal window and type:

            defaults write com.apple.Safari IncludeDebugMenu 1

      To display the debug menu in Safari 3.0 for Windows, use a text editor to add the following to the Preferences.plist file located at C:\Documents and Settings\USERNAME\Application Data\Apple Computer\Safari\Preferences.plist :

            <key>IncludeDebugMenu</key> <true/>

        Safari 1.3 and above supports explicit logging of arbitrary information - similar to Objective-C NSLog() - function by using window.console.log() in your JavaScript. All messages are routed to the JavaScript Console window and show up nicely in a dark green, to easily differentiate themselves from JavaScript exceptions.

            if(window.console)
           {
                window.console.log("I think therefore I code!"); 
           } 
           else
           { 
                alert("I think therefore I code!");
           }

        WebKit crew has released a JavaScript debugger tool Drosera to debug javascript in safari.

Happy Programming !!

Saturday, July 28, 2007

Session.SessionID is not unique

    I have seen many forums in which users are asking that Session.SessionID is not unique. You also have seen forums saying that "I am getting different value for SessionID on every page or in each post back." Yes they are correct !!!! "This is not possible. How can it be?", I know this is your reaction. We have read in all the books and seen practically that SessionID is unique, until user logs off or close the browser. This is also correct. Now you will say then why am I writing the story?

   Here is the actual fundamentals that I have observe practically. The session changes in each request (either post back or redirecting from one page to another page) until user has not insert any value in Session collection. This means server treats each request from new session if user has not entered any value in session. You can check this practically!!!

  Create a web application with two pages Default.aspx and Default2.aspx. Add one button and two lables on Default.aspx page. On page load of Default.aspx in if(!Page.IsPostBack) set any one lable's text to Session.SessionID. Now in click event of button set second lable's text to Session.SessionID. You can see that every time when post back occurs you have new value of SessionID. Amazing !!!!!!! You can check by redirecting to Default2.aspx page and print SessionID.

    Now, on Default.aspx page in if(!Page.IsPostBack) set Session["test"] = "1" or set any name value collection. Once you do this run the page. Click on button any number of time and you see that now SessionID is unique.

   Really Amazing!!!!

 

Happy Programming !!

Tuesday, July 24, 2007

Dispose and Finalize in Dot Net OR Maemory Management using Dispose and Finalize

       You can find article here

Happy Programming !!

Monday, July 23, 2007

Delete single row from duplicate rows in SQL Server 2005 and 2000

        Lets assume that you are using SQL Server 2005 for your current project. You found that you have few rows which have duplicate data in all the columns. Lets consider that you have table name "Example" which has two columns ID and Name.

CREATE TABLE [dbo].[Example]
(
[ID] [int] NOT NULL,
[Name] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
ON [PRIMARY]

Fig - (1) Create Statement for Table     

INSERT INTO [Example] ([ID],[Name]) VALUES (1,Chirag)
INSERT INTO [Example] ([ID],[Name]) VALUES (1,Chirag)
INSERT INTO [Example] ([ID],[Name]) VALUES (2,'Shailesh')
INSERT INTO [Example] ([ID],[Name]) VALUES (3,'Dipak')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Mihir')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Mihir')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Piyush')

Fig - (2) Insert Script.

          You can see that first two and last three rows are duplicate rows. All the values in these rows are same.  Here is the insert script, if you want to do this practically in your local database.

       Now you want to delete duplicate rows in such a way that only one row will be exist after delete statement. First let me write the query which will give return all the duplicate rows from table.

SELECT
        [ID],[NAME],COUNT([ID])
FROM
        [Example]
GROUP BY
        [ID],[NAME]
HAVING
        COUNT([ID]) > 1

Fig - (3) Query to identify duplicate rows in table.

       Here I have used COUNT([ID]) in select statement as ID is not null filed. You can use any column which is not NULL. If all the columns in your table allows NULL value than you can use COUNT(*). The Difference between COUNT(Column Name) and COUNT(*) is, if your column allows null value and in table you have 5 records with 2 null values in ColumnA. If you use COUNT(ColumnA) it will returns 3 and if you use COUNT(*) it will returns 5. So COUNT(Column Name) ignores NULL value. Lets get back to our query. I have used all the column in SELECT and GROUP BY clause. You also have to write all the columns of your table in SELECT and GROUP BY clause. This way you can identify all the duplicates row from table.

        Lets assume that you have to delete the row which has value (1, 'Chirag') so that only one row remains. Here is the query, (Note: This will work only in SQL Sever 2005)

      DELETE TOP(1) FROM [Example] WHERE [ID] = 1

Fig - (3) Delete single row from duplicate rows.

          Here I have used TOP(1) , If you have n rows which has all the values same than you have to use TOP(n-1) so that only 1 row will be remain after delete statement. To delete all the duplicate rows you need to write a cursor as shown below,

DECLARE @ID int
DECLARE @NAME NVARCHAR(50)
DECLARE @COUNT int

DECLARE CUR_DELETE CURSOR FOR
SELECT [ID],[NAME],COUNT([ID]) FROM [Example] GROUP BY [ID],[NAME] HAVING COUNT([ID]) > 1

OPEN CUR_DELETE

FETCH NEXT FROM CUR_DELETE INTO @ID,@NAME,@COUNT
/* Loop through cursor for remaining ID */
WHILE @@FETCH_STATUS = 0
BEGIN

DELETE TOP(@COUNT -1) FROM [Example] WHERE ID = @ID

FETCH NEXT FROM CUR_DELETE INTO @ID,@NAME,@COUNT
END

CLOSE CUR_DELETE
DEALLOCATE CUR_DELETE

Fig - (4) Cursor to delete all duplicate  records

         This is all about deleting duplicate rows in SQL Server 2005.

       Now to do the same in SQL server 2000.  There is function called ROWCOUNT in SQL.  I have used same [Example] table. You can do this by,

SET ROWCOUNT 1
DELETE FROM [Example] WHERE [ID] = 1

Fig - (5) Delete duplicate row in SQL Server 2000

      ROWCOUNT function specify that how many rows will be affected by the statement which is immediately written below.  Here also you have to write  ROWCOUNT (n -1) to delete n duplicate rows such that only  1 row will remain in database.

Happy Programming !!

Tuesday, July 03, 2007

Anonymous Type in C#

          Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.
           Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ.

            C# "Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations. 

             A common misperception that people often have when first seeing the new var keyword is to think that it is a late-bound or un-typed variable reference (for example: a reference of type Object or a late-bound object like in JavaScript).  This is incorrect -- the var keyword always generates a strongly typed variable reference.  Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.

            The var keyword can be used to reference any type in C# (meaning it can be used with both anonymous types and explicitly declared types).  In fact, the easiest way to understand the var keyword is to look at a few examples of it using common explicit types.  For example, I could use the var keyword like below to declare three variables:

var a = 5;
var b = "5"
var c = 5.555;
var d = new Class();
var e = a;

int f = 6;
string g = "6"
double h = 6.666;

Fig - (1) Use of anonymous variable in code.

              You can look in to the IL code and found that IL is treating anonymous variables same as normal variable depending on their initialization. You can see the IL code below,

.method private hidebysig instance void UseOfAnonymousTypes() cil managed
{
// Code size 50 (0x32)
.maxstack 1
.locals init ([0] int32 a,
[1] string b,
[2] float64 c,
[3] class LearnLINQ.SimpleExamples d,
[4] int32 e,
[5] int32 f,
[6] string g,
[7] float64 h)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldstr "5"
IL_0008: stloc.1
IL_0009: ldc.r8 5.5549999999999997
IL_0012: stloc.2
IL_0013: newobj instance void LearnLINQ.SimpleExamples::.ctor()
IL_0018: stloc.3
IL_0019: ldloc.0
IL_001a: stloc.s e
IL_001c: ldc.i4.6
IL_001d: stloc.s f
IL_001f: ldstr "6"
IL_0024: stloc.s g
IL_0026: ldc.r8 6.6660000000000004
IL_002f: stloc.s h
IL_0031: ret
} // end of method Class1::UseOfAnonymousTypes

 Fig - (2) IL generated for Anonymous Type

          As you can see that we have assigned 5 to "a". IL treats "a" as int32. Same is the case for remaining all. From this you can say that IL detects type of anonymous variable from their initialization. So you can declare anonymous variable without initializing it. Second rule for anonymous type is that you can not use Anonymous variable as a member of class, sturct or interface. So below line will not complile.

class LearnAnonymousType
{
       // Below line will give error
       var a = 5;
}

Fig - (3) Defining Anonymous variable as member field in class

    Third rule is that you can not pass or used for Anonymous type as a method argument. See below,

class LearnAnonymousType
{
       // Below line will give error
       function void sum(var Argument)
      {
      }
}

Fig - (4) Passing anonymous type as argument to function

     Fourth rule is, anonymous type can not be static.

      I hope this article has helped you in understanding the concept. Now lets have a simple quiz.

Quiz

Which of the following code fragments compile and which don't (and why)? Have fun!

Fragment 1

using System;
class Lti
{
   public static void Main()
   {
      var a;
      a = 123;
   }
}

Fragment 2

using System;
class Lti
{
   public static void Main()
   {
          int a = 123;
          var b = a;
   }
}

Fragment 3

using System;
using System.Collections.Generic;
class Lti
{
   public static void Main()
   {
              IEnumerable<string> l = new List<string>();
              var m = l;
              int i = m.Count;
   }
}

Fragment 4

using System;
using System.Collections.Generic;
class Lti
{
   private var a = 123;
   private const var b = 123;
   private static var c = 123;
   public static void Main()
   {
   }
}

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!!