I was building my nice little web app, you know: grids, buttons, ajax, stuff like that. And of course I had to create CSS classes for my controls, for example a button has the class of butt and the Send button has a class of buttsend. I agree it was not one of the most inspired CSS class name, but look what ajax made out of it:

FxCop is a free Microsoft utility that analyses compiled .Net code and makes suggestion based on rules, may them be design, security, performance of company policy rules.

The first problem is that you can only use it on compiled code. That means executables and DLLs. But what about ASP.Net 2.0? It doesn't build a DLL anymore, like 1.1 did. How can one use it? I have built an application (one that you will have to message me to send to you) that takes the project name as a parameter and then creates an FxCop project file with the DLLs from the site bin folder as reference DLLs and the DLLs from the Asp.Net temporary folder of that project as analysis targets. That means that you can also use it for ASP.Net now.

The second problem is that FxCop is now part of Team System, the overpriced and overhyped version of Visual Studio, and any attempts to use it with the Standard or Professional versions are cumbersome and undocumented. Siderite to the rescue! Here is a quick way to integrate FxCop as an external tool to Visual Studio and use it for either Console and Windows Forms applications or Asp.NET sites.

Step 1. Download FxCop. The latest version is 1.35, but there is also a 1.36 beta available that knows about lambda expressions and stuff like that.
Step 2. Get from me the FxCopAspNet application (completely free and with source), or build your own. Here is a possibly working link for it: at MediaFire.
Step 3. Open Visual Studio, go to Tools/External Tools and add two FxCop entries:
- FxCop [use C:\Program Files\Microsoft FxCop 1.36\fxcop.exe as Command, "$(TargetPath)" as Arguments and C:\Program Files\Microsoft FxCop 1.36 as Initial Directory]
- FxCopAspNet [use C:\Program Files\FxCopAspNet\FxCopAspNet.exe as Command, "$(ProjectFileName)" as arguments and C:\Program Files\FxCopAspNet as Initial Directory]
Step 4. Just open your web site or application in Visual Studio, compile it, then click on the FxCop item that applies.

Now, this is not meant to be a tutorial on FxCop, here are some links that might enlighten people:
Download FxCop 1.36 Beta
Download FxCop 1.35
Open Source FxCop Integration Add-in for Visual Studio 2005
How to copy the necessary files from Team System to Visual Studio 2005 Professional to make integration work
Use FxCop from your own code
A small tutorial
FxCopUnit, FxCop testing unit project
Video on how to create your own FxCop rules

There are a myriad rules included in the default installation of FxCop, some of them are just annoying, like some naming rules or some telling you you shouldn't raise Exceptions just objects inherited from Exception, but some are pretty good. A lot more can be found on the Internet and now, with the integration in VS Team System, I expect a lot more to pop-up.

Maybe it works for other IIS versions as well, but I certainly was looking for a way of turning it on on our Windows 2000 development/test computer. So this is the long story:
HOW TO: Enable ASPX Compression in IIS

and this is the short one:
Step 1: backup your site metabase
Go to the Internet Information Services (IIS) tab and right click on it, go to All Tasks, choose Backup/Restore Configuration and save it.

Step 2: make the change to the metabase
Create a .bat file that has the following content:
net stop iisadmin
cd C:\InetPub\adminscripts
CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/GZIP/HcScriptFileExtensions "asp" "dll" "exe" "aspx"
CSCRIPT.EXE ADSUTIL.VBS SET W3Svc/Filters/Compression/DEFLATE/HcScriptFileExtensions "asp" "dll" "exe" "aspx"
net start w3svc


Make sure to restart the SMTP service or any others that were stopped by the bat. I don't know how to start it from the command line and I pretty much don't care. The batch file will notify you of possible services it will shut down, but will restart in the end only the Web service.

The performance is immediately visible and it also works with Ajax.

Update:
This article was originally talking about Windows XP. Thanks to McHilarant (see comment below) I realized that, even if the changes in the metabase are possible on any IIS5 (Windows XP and Windows 2000), the actual compression will not be possible on XP. I remembered then that the actual modification that I did that time was not on my dev machine, but on our office server, therefore I updated the post accordingly.

Another Update:
Here is a link about a script to enable IIS 6 gzip compression: Script to Enable HTTP Compression (Gzip/Deflate) in IIS 6.

Before Asp.Net Ajax was released I used to work with a library called AjaxPro (formerly Ajax.Net). It also wrapped specially decorated methods and sent them to the Page as javascript functions with a callback javascript function as the last parameter. In this library, by not using a callback you were saying that you want to execute the function synchronously, that you want to wait for a result. After all, that's a functionality included in the XmlHttpRequest object.

I was amazed to see that Asp.Net Ajax does not offer such an option. You NEED a callback function. So... how do you use a WebMethod as a javascript validation function, since the validators only accept a synchronous function?

The first idea I had was the easy way, to cycle inside the function until I had a result. Bad idea: Javascript itself is not really multitask, so it just took the CPU to 100% and that was the end of it: kill task. The second idea was the hard way: redo all code in the XmlHttpRequest wrapper and use the included synchronous functionality. Too complicated, although I found an article about how to do that. So here is the way I did it:
1. Get the validator object
2. Set a property on it to tell if the validator is inside an async call or not
3. Set a property to hold the last value that was validated
4. Set a property to hold the last result returned
5. Set a method of the validator as the call back function
6. If is in async return false
7. If the last value is the same with the current validating value, return last result
8. Execute the async validation function with the validator callback method as a parameter and return false (or "in async")

Now, the callback method just sets the result and clears the async flag and also updates the visual of the validator. By doing this I essentially don't allow postbacks during validation calls, which makes sense. I also had an idea of creating a special "in async" validator that would not allow postback and would display something nice, but the solution I am explaining keeps it local, with ValidationGroups and everything working just fine.

I will show the code in a few seconds, but first be warned that I am using a validator made by myself which expects null or true as valid and a string or false as invalid. If the result is a string, it displays it as the ErrorMessage. So, on with the code:
The function to get a reference to the validator (which in some cases, especially Ajax, is not the same as the span with the same id)
function getValidator(id)
{
if (typeof(Page_Validators)=='object')
for (c=0; c<Page_Validators.length; c++)
if (Page_Validators[c].id==id) return Page_Validators[c];
return false;
}


The preparing function, which can be reused for more validators. I couldn't find a better way to encapsulate this behaviour yet, please feel free to enlighten me with ideas
// parameters are the value to be validated 
// and the validator object
function prepareAsync(value,validator) {
if (!validator) {
validator.doReturn=true;
return 'Error in prepareAsync: validator not found!';
}
// it's validating
if (validator.inAsync) {
validator.doReturn=true;
return 'In async validation';
}
// it has validated this value before
if (validator.prevValue==value) {
validator.doReturn=true;
return validator.result;
}
// create the callBack function as a method
// of the validator object
if (!validator.callBack)
validator.callBack=function(res) {
validator.inAsync=false;
validator.result=res;
if (res==null) {
validator.isvalid=true;
} else
if (typeof(res)=='boolean') {
validator.isvalid=res;
} else {
// setting the validation message is
// as simple as changing the innerHTML
// of the validator span
validator.innerHTML=res;
validator.isvalid=false;
}
// that's an ASP.Net validator function
// since .NET 1.0 upwards
ValidatorUpdateDisplay(validator);
}
validator.inAsync=true;
validator.prevValue=value;
validator.doReturn=false;
}


and now a sample validation function:
// parameters are the value to be validated
// and the id of the validator
function ValidateProdotto(value,id) {
// get the validator object
var validator=getValidator(id);
// reuse this function to all validators in the page
var res=prepareAsync(value,validator);
// doReturn says if it has a result for us
if (validator.doReturn) return res;
// perform the actual validation
PageMethods.ValidateProdotto(value,validator.callBack);
// and return false, since we are in async now
return false;
}


Hope this helps somebody. This applies to short validations, but feel free to enhance my design with cancellations of running async operations in case the value is changed or with an array caching all the values tried and validated.

Yesterday I was trying to guess what the hell is going on with my application. You see, I was moving controls from one panel to the other in case the browser was FireFox and I forgot all about it. In Internet Explorer it would work, in FireFox ASP.Net would crash, with a Server not available error and not any relevant message as to why. In the Application Event Log I would get stuff like:
aspnet_wp.exe (PID: 872) stopped unexpectedly.
and
EventType clr20r3, P1 aspnet_wp.exe, P2 2.0.50727.832, P3 461ef1db, P4 system, P5 2.0.0.0, P6 461ef191, P7 143a, P8 1f, P9 system.stackoverflowexception, P10 NIL.

and no explanations. Google would give me a lot of links that pertained to WebServices and Asynchronous operations and multi threading, but my application is a simple app. What was going on?

It turns out I was doing this:
pnlNoAjax.Controls.Add(UpdatePanel1.ContentTemplateContainer.Controls[0]);
Nothing wrong with it, except the control that I was adding was also pnlNoAjax and so it went round and round chasing its own tail until a stack overflow exception was generated.

So, bottom line: try to see if you don't have a control adding itself to its control collection when you meet this weird error. Or, of course, the problem might be in a WebService or threading operation :)

You have one beautiful page with Ajax.Net, UpdatePanels and the sorts. Then you go test it with FireFox and it doesn't work. Or you have some other reason for not wanting Ajax in certain situations, like for example people with no Javascript. So what do you do? How can you tell the page NOT to do Ajax postbacks?

The solution is to set ScriptManager's EnablePartialRendering to false. I used to do it with a Panel that was outside the UpdatePanel and in the page Init cycle I would move all controls from the update panel to this normal panel. And it worked, too.

Update February 2016: This post discusses a problem in .Net 2.0 that is more than 8 years old. Perhaps you should look elsewhere. That being said, there are several situations here:
  1. The default execution timeout is 90 in ASP.Net, increase it to whatever you like (in seconds) with <system.web>
       <httpRuntime executionTimeout="VALUE" />
    </system.web>
    Also read this: What exactly is Appdomain recycling, since it is likely this applies in a lot more situations where the server decides the app needs to be recycled.
  2. You use a Response.Redirect, Server.Transfer or Response.End directly, which is the method that ultimately throws this exception. Response.Redirect has an optional bool parameter that, when set to false, does not execute Response.End. Response.End itself is obsolete, recommended is the HttpApplication.CompleteRequest method. Read the remarks for Response.End, it is a method exclusively left there as for compatibility with ASP and it is pretty damn awful. See here how to replace Response.End.
  3. The original problem that made me write this post, which was a long running method inside a web service in .Net 2.0, to which I have not found the solution back then. The solution is probably related to AppDomain/Application Pool recycling from the first point and at that time I did not look hard enough at all application pool settings.
  4. Some issues encountered by other readers that were caused by the ASP.Net application writing in its bin folder, causing the automatic recompiling of the app.

Read more about the ThreadAbortException, which is raised when aborting a thread, which in itself is a pretty bad idea. Ultimately, I would say that getting this exception nowadays is a sure sign of bad design.

Now for the original post:

Update: the problem I was facing is still there and with no solution. I must be doing something wrong, but I can't figure out what. It involves a web service in NET 2.0, added with Web Reference in another app. The service has a method that takes a lot of time. If I do it synchronously it works, depending on the Timeout property of the web service proxy and the executionTimeout setting in the web.config. If I do it asynchronously, though, it doesn't work! If it takes too long it just kills the thread. The Timeout property of the web service doesn't even count in async calls. My solution was to call the method synchronously and be done with it. If anyone has an answer for this, please let me know!

(Oh, but if you mean to tell me that an asynchronous operation in a web service should not take long and that it is bad design and so on and so on, don't let me know!)

The single most related article to my problem that I found on the net is this: timeout problem with webservice and suggests a client problem, but no solution other than asynchronously calling the synchronous call to the web service, and no explanation to the underlying problem.

As for the regular solution for Thread being aborted, it actually it's not my solution, it was given in a forum by a guy with the nickname dstefanov, but I stole it with impunity :)

Here it is:
ThreadAbortException happens when the thread serving the request doesn't finish for a long time. The ASP.NET hosting process aborts this thread after certain time. You can adjust that time with:

<system.web>
<httpRuntime executionTimeout="600" />
</system.web>

By default the executionTimeout="90" seconds.


This applies to ASP.Net web apps, including web services, so also to console or windows forms applications that use web services. My own personal favourite is 86400, the number of seconds in a day.

Thanks dstefanov!

I had to rewrite the entire post. It started from a nice article by a guy called Dan Wahlin and it ended with three (at least? :) ) separate links to his articles and his blog entered in my Technorati favourites.

Here are links to what appears to be a series about Asp.Net Ajax, really informative and concise:

Update Panel properties explained: Implement UpdatePanel Properties

Implement visual cues during updates:Inform Users With Customized Visual Feedback

Minimize the load on the server on many subsequent clicks or refresh requests:Coping With Click-Happy Users

Here is a complete list of the links in the same series:
ASP.NET AJAX Articles

It all started with my own library, a dll in which I wanted to include Javascript, CSS and ultimately images or flash files. I did it the only way I could in 1.1, mainly adding the resources to the project, setting them as Embedded Resource, then reading them and either put them in the page or write them in the application directory and link them in the page. As you can imagine, there were a lot of issues related to writing writes and so on.

But then .NET 2.0 and the AjaxControlToolkit arrived. This toolkit had this funny looking Tab thing, and it used images. So where did it get the images? I was surprised to see that the namespace of the TabContainer control was decorated with stuff like this:

[assembly: WebResource("AjaxControlToolkit.Tabs.tab.gif", "image/gif")]

then in the CSS files, stuff like

background-image:url(<%=WebResource("AjaxControlToolkit.Tabs.tab.gif")%>)

Could it be so easy? yes! And for the js files, they had this class called a ScriptControlBase and the only thing you needed to do to insert a javascript file was decorate the implementing class like this:

[ClientScriptResource("AjaxControlToolkit.TabPanel", "AjaxControlToolkit.Tabs.Tabs.js")]

But what was the underlying mechanism? Googling for WebResource.axd you get these informative links:
Using WebResource.axd for embedded resources
Accessing Embedded Resources through a URL using WebResource.axd

Working with Web Resources in ASP.NET 2.0

These three articles pretty much explain the basics, so I won't do anything but emphasize the more important points:
  • When you use the name of the resource, either when decorating the namespace or when getting the reference to it, use the project namespace and the folder in which the file is in, otherwise it will not work. So if you have the namespace MyControls.Web and you have the folder Images in which you embedded an Image.gif file, the name should be MyControls.Web.Images.Image.gif.
  • To programatically get the url for an embedded resource use Page.ClientScript.GetWebResourceUrl(Type type,string resourceName)
  • In order to get the contents of an embedded resource use code like this:
    Assembly assembly = GetType().Assembly;
    arr = assembly.GetManifestResourceNames();
    foreach (string name in arr)
    if (name==resourceName) {
    Stream s = assembly.GetManifestResourceStream(name);
    // do something with the stream
    break;
    }


But what is this WebResource.axd? It's an IHttpHandler, one that you can also implement quite easily. They are used to handle Ajax, file uploads, get access to all kinds of resources. Look it up. Somewhere in the near future I might write an article about these, too.

I was minding my own business, making user controls in a big project we've been working for the last year and I've stumbled upon the "circular file references are not allowed." error. It was annoying not only because I haven't met before and I was certain there was no circular reference, but also because sometimes it compiled the whole site without any errors, only to fail the next build with the same error.

Google saved me when I found this discussion: http://forums.asp.net/t/922622.aspx. It might be a little long to read and understand so here is the short version:

ASP.Net 2.0 compiles sites by creating a DLL for each folder. Therefore if you have references that are not circular in pages, controls or classes, they can be circular in these DLLs. You have two solutions:

Solution A is to use batch="false" in the compilation tag of the web.config file. This is not really a solution as it forces ASP.Net to compile a DLL for each page and control. It might work, but it slows compilation terribly and it is also not suitable for production builds, only for development.

Solution B is to move all referenced controls in a single directory. In my case there was a Controls directory and one of the controls was outside, referenced both in a control in Controls and in a page in the base directory. Moving my user control to the Controls folder solved the problem!

Bottom line: try to avoid referencing across folders.

I've accidentally stumbled upon a thing called OutputCache. Weird little thing, I thought, how come I didn't hear about it? It seemed such a wonderful concept: just cache the output of ASP.Net pages and controls for a specific amount of time, specify for what parameters or controls or properties the cache is valid for and if it is shared between different users. Then just output the cached version and don't execute the entire thing all the time.

I tested it and it works. Most useful I find it for user controls. One can put a list of unchanging stuff like a list of cities or provinces or even customers in a user control, cache its output and forget about it.

How to use it:
A) declaratively. Put in the page or control something like this:
<%@ OutputCache Duration=100000 Shared="true" VaryByParam="none" %>
Just read the link above for the details.

B) programmatically. Put in the page or control code something like this:
CachePolicy.Cached = true;
CachePolicy.Duration = new TimeSpan(1, 0, 0, 0, 0);
CachePolicy.VaryByParams.IgnoreParams = true;

Update: it has come to my attention that this returns an error with the message "The CachePolicy cannot be used, since the control is not being cached." which is returned when the CachePolicy was not instantiated with a BasePartialCachingControl as a parameter. The solution, it seems, it is to also decorate the user control with the PartialCaching attribute.

ex: [PartialCaching(20)] - set the caching to 20 seconds.

C) One can even validate the cache programmatically after whatever of A or B methods were used like this:
Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(MyCacheValidatorMethod),null );

That's it!

This book is written by a guy that made a small company dedicated to programming with free tools. Thus, it tries to show how to debug ASP.Net assuming that you come from an ASP background and that you don't have Visual Studio .Net. So I don't think I have to tell you how much useless information there is in there. It even covers programmatic code tracing.

That doesn't mean it is a bad book, just useless for me. If you expect some wonderful debugging frameworks or code structure that would allow you to easily debug your applications, then this book is not for you. Not to mention that at the time it was written, Visual Studio 2005 was not out yet.

Bottom line: just a hands on approach and some Google when you meet problems will solve any problems that are solved by this book.

You are trying to use a WebMethod or a web service ScriptMethod in Javascript and you get an InvalidOperationException saying something about a circular reference. It happened to me when trying to read a DataTable in Javascript.

Why. The Javascript serialization of DataSets, DataTables and DataRows was available once in the ASP.Net Ajax web extensions. That's why you probably found a lot of Google results with people that could either only serialize DataSets, but not DataTables, or people that made it work by magic by adding some lines in the converters section of web.config, things that can't possibly work with your setup. Then, the option was removed in the final version of ASP.Net Ajax, only to be readded in the ASP.Net Futures, which is a test playground for future features of the platform.

What. There are several options, one being to reference an older version of ASP.Net Ajax and uses the converters there. But why bother? It's unlikely you use the DataTable or some other object in Javascript with all the options of the C# object. You probably just want to itterate through rows and read properties. So build your own converter.

How. Create a new library project. Add a class named DataTableConverter that inherits from JavaScriptConverter, and implement: IEnumerable<Type> SupportedTypes, IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) and object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer).

You probably won't need to Deserialize anything, you can leave that unimplemented. The list of convertible types is easy enough, all you are left with is the Serialize code, which is actually very easy, too. Then all you need to do is add this in the web.config file:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization >
<converters>
<add name="DataTableAjaxFix" type="AjaxTypeConverters.DataTableConverter"/>
</converters>
</jsonSerialization>


And here is the complete C# code of my DataTableConverter, but you can easily adapt it to anything:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

namespace AjaxTypeConverters
{
public class DataTableConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] {typeof (DataTable)}; }
}

public override object Deserialize(IDictionary<string, object> dictionary, Type type,JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
DataTable listType = obj as DataTable;

if (listType != null)
{
// Create the representation.
Dictionary<string, object> result = new Dictionary<string, object>();
ArrayList itemsList = new ArrayList();
foreach (DataRow row in listType.Rows)
{
//Add each entry to the dictionary.
Dictionary<string, object> listDict = new Dictionary<string, object>();
foreach (DataColumn dc in listType.Columns)
{
listDict.Add(dc.ColumnName, row[dc]);
}
itemsList.Add(listDict);
}
result["Rows"] = itemsList;

return result;
}
return new Dictionary<string, object>();
}
}
}

Yesterday I was trying desperately to understand why my web site was crashing without any error, the only information I could get being that the connection to the server has been reset. I've spent hours trying to determine what was wrong. Apparently I needed a break, because today it took me a few minutes to realize what it was.

First of all, duh! If there are issues with the connection server, look into the Windows Application Event Log. But we'll get there.

The "error" appeared at any postback after I loaded a certain page, but only if that page displayed a minimum of data. Above that threshold I would get the server reset thing that you can see both in IE7 and FireFox2 in the animated GIF. Basically the error messages were:
FireFox
The connection was reset
The connection to the server was reset while the page was loading.

Internet Explorer
Internet Explorer cannot display the webpage
Internet connectivity has been lost.
The website is temporarily unavailable.
The Domain Name Server (DNS) is not reachable.

Ajax UpdatePanel
Server returned error 12031

So, today I realised I should look in the Application Event Log and this Web Event Warning was displayed (shortened it a bit):
Event code: 3004
Event message: Post size exceeded allowed limits.

Process information:
Process name: aspnet_wp.exe

Exception information:
Exception type: HttpException
Exception message: Maximum request length exceeded.

Stack trace: at System.Web.HttpRequest.GetEntireRawContent()
at System.Web.HttpRequest.FillInFormCollection()
at System.Web.HttpRequest.get_Form()
at System.Web.HttpRequest.get_HasForm()
at System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull)
at System.Web.UI.Page.DeterminePostBackMode()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)


It turns out I was putting a lot of data into the ViewState, which, as you know, is saved as a HiddenField (a.k.a. hidden html input) and the size of it exceeded the set up maximum POST size.

Solutions:
A. Add this code to your page: (NET 2.0)
 protected override PageStatePersister PageStatePersister
{
get
{
//return base.PageStatePersister;
return new SessionPageStatePersister(this);
}
}


This should put your ViewState into the Session, rather than in the page. This solves some other issues as well, obviously.

B. Increase the maximum Request limit (default is 4Mb)
- In the Machine.config file, change the maxRequestLength attribute of the <httpRuntime> configuration section to a larger value. This change affects the whole computer.
- In the Web.config file, override the value of maxRequestLength for the application. For example, the following entry in Web.config allows files that are less than or equal to 8 megabytes (MB) to be uploaded:
<httpRuntime maxRequestLength="8192" />

This is an exact quote from the Microsoft support page.

That's it, folks!

Update:

The maxRequestLength maximum value is 2097151, that is less than 2.1Gb. No file that exceeds this size can be uploaded through the default upload mechanism.

Yes, the situation is fairly simple, you do a parentControl.FindControl("someOtherControl") in ASP.Net and you get controls that are not in parentControl. Why?

Because apparently, FindControl wants a NamingContainer in which to search. If the parentControl is not an INamingContainer, it will look into the parentControl's NamingContainer.

Sollution? Create your own FindControl method, one that recursively goes through the child controls and looks for the specific ID.