Code Project

Link Unit

Tuesday, December 22, 2009

Bad Request (Invalid Hostname)

While trying to host a site on IIS /windows 2003 devleoped in ASP, we got the following error.
"Http Error 404 - Bad Request (Invalid Hostname)" .
Located the file C:\WINNT\system32\LogFiles\HTTPERR.log to see if the error could be diagnosed with error description. All the other websites were running fine.

Solution: In Web Site Advanced property Host Header value was specified. Removing the "Host Header Value" resulted in operating site.

refer the image as shown below

Wednesday, December 16, 2009

Windows 2003 /DC : Application Server Unavailable

While we were hosting an web application on IIS ,got this error
Application Server Unavailable
The web application you are attempting to access on this web server is currently unavailable.Please hit the "Refresh" button in your web browser to retry your request.

On inspecting further the event log has captured following
aspnet_wp.exe could not be launched because the username and/or password supplied in the processModel section of the config file are invalid.aspnet_wp.exe could not be started.HRESULT for the failure: 80004005

By default, ASP.NET runs its worker process (Aspnet_wp.exe) with a weak account (the local machine account, which is named ASPNET) to provide a more secure environment. On a domain controller or on a backup domain controller, all user accounts are domain accounts and are not local machine accounts. Therefore, Aspnet_wp.exe fails to start because it cannot find a local account named "localmachinename\ASPNET". To provide a valid user account on the domain controller, you must specify an explicit account in the section of the Machine.config file, or you must use the SYSTEM account.

To work around this problem, use one of the following methods:

  • Create a weak account that has the correct permissions, and then configure the section of the Machine.config file to use that account.
  • Set the userName attribute to SYSTEM in the section of the Machine.config file.
  • Configure the section of the Machine.config file to use an administrator account.

One other special value for userName is System, with the password AutoGenerate, which runs the process as an administrative account and allows all ASP.NET user code running under the process to have full administrative privileges.
For deployment on local development environment one can use 2nd option , for deployment on client side 1st option is the best.

System.InvalidOperationException: The control with ID requires a ScriptManager on the page. The ScriptManager must appear before any controls that

System.InvalidOperationException: The control with ID requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it.

We faced this error while working on one of our project's page. The error appear to be very silly as Scriptmanager was declared on the page; page worked fine on it's first load. After postback,it was giving the above error. On inspecting the page further it was found the culprit was "Page.Items.Clear()" . It was clearing all objects including Scriptmanager from Page's object list.
Rule of Thumb : donot use "Page.Items.Clear()" when using Ajax

Friday, October 30, 2009

How to find the current value of a sequence number

This seems to be a simple question , and the following error will appear if we try currval on a sequence.

Select s.currval from dual

ORA-08002: sequence S.CURRVAL is not yet defined in this session

CURRVAL doesn't represent anything global about the sequence number generator. It only represents the value returned to your session (the database session processing the current statements) the last time you called NEXTVAL for that sequence

Solutions :
#1 before using CURRVAL you should call NEXTVAL .
#2 You can get the current value of the Sequence by querying DBA_SEQUENCES , which is Last_number.

An attempt was made to load a program with an incorrect format (Exception from HRESULT:0X800700008)

This problem is for sure of 64bit machine.

If an add-on is set to run on a 64 bit environment ensure it is compiled with a 32 bit operating system. The reason is the current SAPbobsCOM.dll can not run with 64 bit compiled add-ons.

You must compile your add-on and your installation program at 32 bit. You must force it because SAPBouiCom e SAPBobsCom are 32 bit component. A 64-bit program cannot call a 32-bit component.

Solution:When you create your application and when you are creating through your B1 installer. Go to the project properties-->select compile option and in that Advanced compile option-->change your target CPU to x86..rebuild your project again and create your refresh ard using these settings...

After doing above steps we faced following Error: "wrong digital signture for addon instller" Solution:The problem may be that rebuilding add-on project then generate ARD, while the old add-on executable is included in your add-on installer.
You should make sure it is the same executable of your add-on when generate the ARD and Installation. And you're recommended to do this with B1DE, it helps you to generate ARD and Installation once.
Actually, In ARD file it has unique digital signature for the add-on executable. The mismatch of the executable of add-on in ARD and Installer will lead to wrong digital signature error. Reason for Wrong digital signature:
1.You build the add-on project, then add-on executable is generated. e.g. MyAddOn.exe
2.You use this executable in the add-on installer (what ever InstallShield or other)
3.You rebuild the add-on project, then actually it is a different executable generated. Even its name is still MyAddOn.exe
4.You generate ARD on the basis of the second one. Then you will get the Wrong Digital Signature. Again, you should make sure it is the same executable file of your add-on that is used in ARD generation and included in your install shield. Meaning you shouldn't rebuild the add-on project when generate ARD or Installation, make sure ARD and Installer are referring to the same "version" of add-on executable

Every time you create an installer, you should create a new .ard file. This file contains an digital signature of your installer executable, and one digital signature of the main executable of your Add-on. (with digital signature SB1 means some kind of hash/checksum of the file)The notice you've get is because you don't have the correct signature in your .ard file for the Add-on executable. If you are creating it manually, select the correct Add-on Exe Full Path in the Add-On Registration Data Generator.
I hope this will it solved my problem

Monday, September 07, 2009

DataBinding: 'Microsoft.SharePoint.SPListItem' does not contain a property with the name

When trying to bind the 'Extension' column of a custom Sharepoint List to the DropdownList , I was facing the error :

DataBinding: 'Microsoft.SharePoint.SPListItem' does not contain a property with the name 'Extension'

In case I tried the following it ran successfully

using (SPWeb web = site.OpenWeb())
SPList list = web.Lists["Departments"];
cboDepartment.DataSource = list.Items;
cboDepartment.DataValueField = "Title"; // List field holding value
cboDepartment.DataTextField = "Title"; // List field holding name to be displayed on page

So, I believe that whatever it is tryed to bind through DataTextField and DataValueField is supposed to be a property of the object we are binding to. For instance, SPListItem do have Title and ID properties, but it does not have 'Extension' property (in the meaning of the SPListItem class member).

So the following solutions were tried.

Solution #1

SPWeb site = SPContext.Current.Web;
DropDownList cboExtensions = new DropDownList();
SPList list = site.Lists["ImageExtensionList"];
SPListItemCollection lstCollection = list.Items;
cboExtensions.DataSource = lstCollection.GetDataTable();
cboExtensions.DataValueField = "Extension"; // List field holding value
cboExtensions.DataTextField = "Extension"; // List field holding name to be displayed on page

Solution #2

SPWeb site = SPContext.Current.Web;
DropDownList cboExtensions = new DropDownList();
SPList list = site.Lists["ImageExtensionList"];
foreach (SPListItem listRecords in list.Items)
//ListItem tempItem = listRecords["Extension"].ToString();
ListItem tempItem = new ListItem(listRecords["Extension"].ToString(), listRecords["Extension"].ToString());
cboExtensions.Items.Add(tempItem); //ddlFromSPList is the name of the dropdown list

Whenever Title or ID is specified it will work without any issue. When the ListItemCollection is bounded to the DropDownList ,it is expecting Valuefield and TextField to be Properties. "Title" and "ID" are properties of List , hence it worked without any issue.

So the simple solution is to get the DataTable from the ListCollection or Get the items of the list , iterate the list and add the items to DropDownlist.

Hope it Helps
Jatinder Singh

Friday, September 04, 2009

This solution contains two assemblies with the same name, or the SharePoint server already has an assembly with the specified name.

While trying to redeploy the same WebPart ,I was facing this rather silly error. I tried to do the “cleanup” by right clicking the Project and then redeployed same error appeared. Later figured it out by throwing a search in Google

#1 See if the feature that you're trying to add still exists in the "\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES" path. Delete it.

#2 Uninstall the particular Assembly from c:\windows\assembly folder too.

#3 Try to deploy it again.

Design decision to use ascx control in sharepoint webpart versus pure sharepoint webpart

1. Create webusercontrol (.ascx), and then load that user control in the newly created webpart.

2. Create a webpart from scratch, by putting the code to generate each and every control in code.

if you need to create a control with a really advanced user interface, for example many controls and stuff, then a user control could be much easier to create.

I have found that the execution lifecycle (control viewstate, event bubbling, etc.) is a pain when going with Option 2. I choose Option 1 because the viewstate is easily managed in the code. Additionally, I like Option 1 because I can visually design the page using the VS toolbox to drag and drop controls on the design surface as opposed to Option 2 where you have to handle each control manually in code.

The approach 2 may sound difficult because of not very great integration with Galleries , but if you have the luxury of invest the time, you'll be better off in the long run.

The type or namespace name 'Data' does not exist in the namespace 'System' (are you missing an assembly reference?)

This is a common but simple problem to solve , below is explanation and steps to solve.

using Directives at the top of code files just allows you to use types in a namespace without having to fully qualify them.
e.g. using System.Data directive allows you to declare a DataColumn as following:

DataColumn dc = new DataColumn();

instead of:

System.Data.DataColumn dc = new System.Data.DataColumn();

using statements define scope, but you still need a reference to the Library so that the project will build.

Do you see System.Data listed under it?
Open your solution explorer and Expand References:
More than likely not, hence the complaint from the Compiler.

What to do/ how to Solve??

Right click on References, and from the Context Menu, select "Add Reference"
The Add Reference view will default to the .NET tab, scroll down until you find the System.Data, select it and click the OK button.

Build your app.

Hope it Helps

Wednesday, September 02, 2009

The feature name WebPart1 already exists in SharePoint. You need to rename the feature before solution deployment can succeed

While working in Visual Studio 2008 , we were able to create new WebParts and deploy them easily . Off late we started facing the following problem.

“The feature name WebPart1 already exists in SharePoint. You need to rename the feature before solution deployment can succeed.”

The error may seem stupid , the solution to it is simple.

A simple method to avoid the above error is as follows
  1. Immediately after creating a new webpart project, remove the Webpart1 folder completely.

  2. Add new web part to the project by right clicking on the project and selecting new item from the context menu.

  3. In the Add new item dialog box select Sharepoint from categories and Select Web Part from templates.

  4. Give a name for your webpart and click Add button.

Friday, August 28, 2009

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a

If you add a reference to Microsoft Excel and then try to use it within your ASP.NET application you may receive the following errors.

Server Error in '/excel' Application. 

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a.

We referred this link for the DCOMCNFG settings required on Windows 2003 server   . Even after the settings the problem was  not resolved and following error started to appear

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.

Make some changes also in ASP.Net Site’s web.config file.

Given below is the settings for web.config file.

<identity impersonate="true" userName="DomainName\administrator" password="password"/>

            <authentication mode="Windows">           </authentication>


Tuesday, August 25, 2009

Four Little Known, Helpful Methods, Properties, and Features for ASP.NET Developers

The .NET Framework is big. Really big. The System.Web assembly, which contains the guts of ASP.NET, is comprised of nearly 2,000 types, over 23,000 methods, and more than 12,500 properties. And that's not counting any of the functionality added to ASP.NET since version 2.0. ASP.NET AJAX, the ListView control, Dynamic Data, URL routing, and other features add hundreds of new types and thousands of new methods and properties.

Given the size and scope of the .NET Framework and ASP.NET even there are certain to be dark corners for even the most experienced developers. There are certain classes, methods, and properties in the .NET Framework that every ASP.NET developer is intimately familiar with: the Request.QueryString collection; the Session object; Pageobject properties like IsValid and IsPostBack. Yet even in these familiar classes there are very useful and very helpful properties, methods, and features that are less widely known. Heck, I've been building ASP.NET applications and writing about ASP.NET functionality and features full time since 2001, and once or twice a month I still stumble across an unknown feature or a helpful property or method buried in some dark corner of the framework.

This article lists four helpful methods, properties, and features in the .NET Framework that, in my experience, are not widely known to ASP.NET developers. Read here

Auto Refresh in Chrome

I work with all type of Browser including the new entrant Chrome. Other browsers have some plugin or addon which help to auto refresh the page. So I tried to figure out Does Chrome have an auto-reload option (per tab) ?? 
The answer was google search away.

Just create a bookmark with the following code as the URL:

timeout=prompt("Set timeout [s]");
function reload(){

Click the bookmark with the tab you want to auto-reload active.
Set the time interval (in seconds) or set it to zero to cancel auto-reload.

Hope it Helps
Jatinder Singh

Sunday, July 05, 2009

System.IO.DirectoryNotFoundException: Could not find a part of the path

In one of our project ,I was using a file upload control within to upload a file to Web Server and then do some processing on it.

When the file was uploaded to the server following error occurred:

System.IO.DirectoryNotFoundException: Could not find a part of the path C:\TMP\A.csv

In code I'm using postedfile.filename to get the filename and path. But it returns local path. I think the problem is that the fileupload control gets the path from the local machine, "C:\TMP" or whatever which is a local drive and same path / file might not exist at server side.

string strCSVFile = fUCSVFile.PostedFile.FileName.ToString(); // This returns path of the posted file ; i.e client path

System.IO.StreamReader reader = new System.IO.StreamReader(strCSVFile);
// Add the values in the DataTable By choosing the values which are separated by Comma
while (reader.Peek() > 0)
string words = reader.ReadLine();
/* Processing */


On local machine the code was working fine because sever and client are on SAME system.Hence it worked.

After changing the code like below, it started working fine on remote server too.

strCSVFile =Server.MapPath("~") + "\\" + System.Guid.NewGuid().ToString().Replace("-", "");
fUCSVFile.PostedFile.SaveAs(strCSVFile); // File is stored on the Server.

System.IO.StreamReader reader = new System.IO.StreamReader(strCSVFile);
// Add the values in the DataTable By choosing the values which are separated by Comma
while (reader.Peek() > 0)
string words = reader.ReadLine();
/* Processing */


One should not use "PostedFile.FileName" for accessing the file; though it could be used for getting the filename.The problem of using "PostedFile.FileName" would be difficult to trace if the localpath exists on the server also.

The file should be saved by using "PostedFile.SaveAs(....)" and then accessed.

Hope it Helps.

Monday, May 25, 2009

FileHelpers : Strong type your flat file

We were working on a project, where it required to read a pipe separated values from the file. This is how we were doing it earlier




          StreamReader sr = new StreamReader(lstrFilePath);

          while ((lstrReadLine = sr.ReadLine()) != null)


                    string[] lstrsplit = lstrReadLine.Split(new Char[] { '|' });

                    string lstrCOMP_NAME = lstrsplit[1];

                    string lstrFULL_NAME = lstrsplit[2];

                    string lstrFATHER_NAME = lstrsplit[3];

                    string lstrDESIGNATION = lstrsplit[4];


                    rowInsert["COMP_NAME"] = lstrCOMP_NAME;

                    rowInsert["FULL_NAME"] = lstrFULL_NAME;

                    rowInsert["FATHER_NAME"] = lstrFATHER_NAME;

                    rowInsert["DESIGNATION"] = lstrDESIGNATION;






catch(Exception e)



// Error Logging





// Will always be called

 if (sr != null) // This check can be ignored though




We started looking for a class (Helper Class), which can import/export flat files into DataTable/Array.

Then came across this useful dll FileHelpers. We converted our previous code to the one written below


Step 1) Created a class in .cs file and specify deliminator , which was | (pipe) in our case


 public class Anxeure  


     public string COMP_NAME;  


     public string FULL_NAME;  


     public string FATHER_NAME;  


     public string DESIGNATION;  


     //..... and other columns in the sequence they will come in file.





 Step 2) Create an instance of FileHelperEngine and read the file.


 FileHelperEngine engine = new FileHelperEngine(typeof(Anxeure));  


 // To Read Use:  

 Anxeure[] res = engine.ReadFile("FileIn.txt") as Anxeure[];  


//We could also export the data thus created after doing some manipulation

engine.WriteFile("FileOut.txt", res);  


It is amazing how by writing two statements we could achieve a strongly typed output. Great


Hope it helps




Tuesday, May 19, 2009

Tip to optimize C# Refactoring in Web Projects

I usally do the refactoring of the web application code developed over period of time to make it more managable. But most of the time VS take too long that it becomes better to do refactoring on your own.Later I decided to read some blog posts to see whether someone has work on Optimising Refactor. After googling around for a while, I found the solution.

Scott has posted a great tip for speeding up refactoring performance with Web Projects in VS 2005.


  1. Click Start->Run in Windows and run "regedit"
  2. Navigate to this registry location: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\CSharp\Options\Editor
  3. Right-click on the Editor node and choose "New DWORD value"
  4. Name the value "OpenAllVenusFilesOnRefactor" and leave the value as 0

Then, when you restart VS 2005 and perform a re-factoring - you should find performance very fast.


This hack basically turns off the refactoring functionality beyond the current page and so it's pretty fast. It looks like this has been fixed in Visual Studio 2008 thankfully.

Hope it Helps

Monday, May 11, 2009

JavaScript : Convert Ok/Cancel into Yes/No

Just came across a post, brilliant way to change the confirm box from ok n cancel to yes n no


Found the info on the link


Here is the code:


<script language=javascript>


/*@cc_on @*/

/*@if (@_win32 && @_jscript_version>=5)


function window.confirm(str)


    execScript('n = msgbox("'+str+'","4132")', "vbscript");

    return(n == 6);



@end @*/



Hope visitors find it useful.

Tuesday, April 28, 2009

How to Solve Method Error 500 - Maximum Length Exceeded with AJAX web service call

At client side I've been assigned a bug concerning
a combo box. When the combo box is changed by the
user, a secondary combo box has its values reloaded.
This is done by calling a web service. The bug is
that "Method Error 500" is displayed as the only
item on occasion. I checked and cross checked the
problem with my own post  ,
but could not sort the error , search on google lead to
the following solution.
After some rooting around, it turns out that this is
caused by too much data being returned in the SQL query
behind the web service call, so the web service returns
an error. A simple change to the web.config file can
increase the size limit of data returned:
       <jsonSerialization maxJsonLength="5000000" />
First off, the serialization process will fail if the
number of nested objects is greater than that defined
within the RecursionLimit property , which is 100.
The serialization process will also fail if the length
of the serialized text is greater than that of the
MaxJsonLength property; again, note the default value
of 2,097,152 base ten.

Hope visitor find it useful.

Wednesday, April 15, 2009

string.Empty Example and Issues in C# written by Sam Allen

string.Empty Example and Issues in C# written by Sam Allen

Problem. You are wondering how to use string.Empty and how it is different from an empty string literal constant "". There is a subtle different, and it can be significant in some scenarios, in that it changes the meaning of your program. Solution. Here we see how to use string.Empty, and then look into its implementation, finally seeing an example of how it can produce less effective code.

For more information click here

Tuesday, April 14, 2009

Crystal Reports Toolbar Images Displaying as Red X

Recently we developed reports for our web application in crystal report, but we faced the problem of toolbar images displaying as red X. On development machine it worked perfectly but on Production Server it failed to display.


Copy aspnet_client folder from your PC and paste it in application folder on server ,then refresh the IIS default website and its done. It solved the problem for me I hope it help visitors too.

Sunday, March 29, 2009

Provider error '8007000e' , Not enough storage is available to complete this operation

Problem :
I was facing "Provider error '8007000e' , Not enough storage is available to
complete this operation." error in vbscript of an classic asp application.

code was as below-

set rsGetEnquiryInfo = server.CreateObject("Adodb.Recordset")
rsGetEnquiryInfo.Open strSql,conn,3,1
dim intFieldCount, intCounter
if not((rsGetEnquiryInfo.BOF) and (rsGetEnquiryInfo.EOF)) then
intFieldCount = rsGetEnquiryInfo.GetRows() '--- getting error at this line
end if

MDAC version should be 2.8 +
The version information is found in the following key:
To check the registry, follow these steps:
• On the Start menu, click Run.
• In the Open text box, type regedit and then click OK; this starts Registry Editor.
In the Navigation pane, drill-down to the following path:
• In the Details pane, look in the Name column for FullInstallVer and Version. Each of these keys will have corresponding version information in the Data column.
• When finished, click Exit on the Registry menu to close Registry Editor.

Setting the rsGetEnquiryInfo object to nothing should solve the error.

Wednesday, March 11, 2009

ValidationSummary displayed multiple times in UpdatePanel

While working on a ASP.Net Web Application , we faced a peculiar situation where the validationsummary is displayed many times. Googled around a bit for the solution and this is what I found , I hope this help visitors also. comes is really good with the Validation Controls. For example the RequiredFieldValidator is perfectly suited because it displays a little error message for the control it validates.

All is fine until you have 40-50 fields that have to be filled out. In this case it's of good practice to use the ValidatioSummary control which summarises all the error messages from the ValidationGroup and shows them either in text on the page or as a Javascript alert().

All is fine until you use the ValidationSummary inside an UpdatePanel, where something rather interesting happens. The alert box is displayed multiple times. When I got this behaviour it was even more interesting that the number of times the alert box is displayed was not constant.

But there is a correlation between the number of times the alert is displayed and the number of asynchronous postbacks in that UpdatePanel. The ValidationSummary alert() is displayed exactly the number of asychronous postbacks times plus one.
0 postbacks --> 1 alert
2 postbacks ---> 3 alerts

To avoid this behaviour you only have to place the ValidationSummary outside the UpdatePanel, this will prevent it from reregistering itself for validation on each asynchronous postback.

Thursday, February 19, 2009

ObjectDataSource: could not find a non-generic method '...'

I found this can help:

But in most of my cases the following helped

A “Bind” was added accidently to a hidden Field, and it started showing as input parameter to the Insert /Update Method because of 2 way Binding. I went to the aspx and changed those "extra" fields to say "Eval" instead of "Bind" and it all started working again.