Just Where Is WebResource.axd?

I stumbled upon and answered a question at Stackoverflow this morning – Where is WebResource.axd? – and thought it might be worth to elaborate a bit on the question and answer here, on my blog.

But first, imagine you are developing a Web control or a library or a framework that requires certain external resources, such as images, JavaScript, and CSS.

When developing your control/library/framework you may have such external content sitting in a particular folder in your application, but when you get ready to package your control/library/framework you want the end product to be a single assembly (that is, a single DLL file), and not an assembly plus a folder for images and a folder for JavaScript files and a folder for CSS files.

In other words, you do not want to require that your users – other web developers – have to add a bunch of folders and images/JavaScript/CSS files to their website to start using your control/library/product; rather, you want everything to work once the developer drops your assembly into their Bin folder.

Such functionality is possible by using embedding resources. An embedded resource is a resource file – like an image, JavaScript, or CSS file – that is embedded within the compiled assembly.

This allows a control/library/framework developer to embed any external resources into the assembly, thereby having the entire application existing in one single file. Consider ASP.NET’s validation controls.

These controls require that certain JavaScript functions be present in order for them to use client-side validation. When using the validation controls you don’t need to add any JavaScript files to your website; instead, the JavaScript used by these controls is embedded in one of the built-in ASP.NET assemblies.

But if the external resources are embedded in the assembly, how do you get it out of the assembly and onto a web page?

The answer is WebResource.axdWebResource.axd is an HTTP Handler that is part of the .NET Framework that does one thing and one thing only – it is tasked with getting an embedded resource out of a DLL and returning its content.

What DLL to go to and what embedded resources to take is specified through the querystring. For instance, a request to www.yoursite.com/WebResource.axd?d=EqSMS…&t=63421… might return a particular snippet of JavaScript embedded in a particular assembly.

The d querystring parameter contains encrypted information that specifies the assembly and resource to return; the t querystring parameter is a timestamp and is used to only allow requests to that resource using that URL for a certain window of time.

To see WebResource.axd in action, create an ASP.NET Web page that includes some validation controls, visit the page in a browser, and then do a View/Source. You will see a number of <script> tags pulling in JavaScript from WebResource.axd like so:

1<script src="/YourSite/WebResource.axd?d=fs7zUa...&amp;t=6342..." type="text/javascript"></script>
2 
3<script src="/YourSite/WebResource.axd?d=EqSMSn...&amp;t=6342..." type="text/javascript"></script>

Here, WebResource.axd is pulling out embedded JavaScript from an assembly and returning that JavaScript to the browser. If you plug in those URLs into your browser’s Address bar you’ll see the precise JavaScript returned.

Ok, so now that we know what WebResource.axd is and what it does the next question is, where is it? Clearly, there’s no file named WebResource.axd in your website – what’s going on here? Here’s my answer from the Stackoverflow question:

.axd files are typically implemented as HTTP Handlers. They don’t exist as an ASP.NET web page, but rather as a class that implements the IHttpHandler interface. If you look in the root Web.config (%WINDIR%\Microsoft.NET\Framework\version\Config\Web.config) you’ll find the following entry:

1<add path="WebResource.axd"
2verb="GET"
3type="System.Web.Handlers.AssemblyResourceLoader"
4validate="True" />

This entry says, “Hey, if a request comes in for WebResource.axd then use the HTTP Handler AssemblyResourceLoader in the System.Web.Handlers namespace.

The code for this class is a bit lengthy, so I can’t post it here, but you can use a disassembler like the free Reflector to view this class’s source code. You could probably get the original source code (with comments) by using the NetMassDownloader tool.

So there you have it. WebResource.axd is an HTTP Handler built into the .NET Framework that retrieves embedded resources from assemblies.

To learn more about WebResource.axd and how to go about embedding resources in an assembly, refer to my article, Accessing Embedded Resources through a URL using WebResource.axd.

Happy Programming!

Returning Dynamic Types from an Ajax Web Service Using C# 4.0

Over at 4Guys, I’m authoring a series of articles showing different techniques for accessing server-side data from client script.

The most recent installment (Part 2) shows how to provide server-side data through the use of an Ajax Web Service and how to consume that data using either a proxy class created by the ASP.NET Ajax Library or by communicating with the Ajax Web Service directly using jQuery.

When returning data from a service it’s not uncommon to create a specialized Data Transfer Object (or DTO), and in Part 2 I create two such DTO classes. Here’s the basic design pattern:

  1. Create a DTO class that has properties that model the data you wan to return. For instance, the following DTO class can be used to transmit CategoryIDCategoryName, and Description information about one or more categories.
  2. In the service, get the data of interest from your object layer. In the demo for this article series I use Linq-To-Sql as my data access layer and object model. Here is code from the Ajax Web Service’s GetCategories method that retrieves information about the categories in the system:
  3. Now the results need to be mapped from the domain object to the DTO. This can be done manually or by using a library like AutoMapper. In the above example, we would iterate through the results to create an array of CategoryDTO objects, which is what would be returned.

If you are using C# 4.0 you can choose to live in a looser-typed world. Rather than having the Ajax Web Service return a strongly-typed value (namely, an array of CategoryDTO objects) you could instead opt to have a more ethereal return type – dynamic!

Having a return type of dynamic allows you to return an anonymous type, meaning you don’t need to create a DTO nor do you need to map the domain object to the DTO. Instead, you’d just create an anonymous type, like so:

Note the dynamic keyword as the method’s return type. Also note that results is a query that returns an enumeration of anonymous types, each of which has three properties – CategoryIDCategoryName, and Description.

The call to the ToArray method executes the query and returns the array of anonymous types as the method’s output.

Because the anonymous type’s properties. The client-side script calling this method can work with the returned anonymous type using the exact same code as with the strongly-typed return type.

Control Building and ViewState Lesson for the Day

Whenever I am working on a problem and hit a perplexing roadblock that impedes my process, my initial emotional state is calm. “I’ll figure out this problem soon,” I tell myself, as I explore workarounds or examine the code base to try to understand why I can’t do what I know I should be able to do.

If this search goes on for five or more minutes, I start to get a little flustered. Off to Google!” I declare, hoping there has been some other unfortunate soul who has experienced the same problem and has shared his solution.

I usually hit the Google Web search first and, if I have no luck there, I delve into the USENET postings on Google Groups. If 15 minutes have passed with no hits from Google, I start to get angry at myself. “I SHOULD KNOW HOW TO FIX THIS,” I say, as I pour back over the material I examined in the first five minutes, knowing there must be something I overlooked.

What’s interesting is that if this search continues into, say, the half-hour mark, my emotions start to sway from frustration and despair to glee. “Wait until I figure out what went wrong,” I reason, “and I can share it on my blog, and it will help others down the road.” And that’s what keeps me going.

Today’s lesson – which will hopefully save you the 40 minutes it cost me – centers around composite controls, the DropDownList Web control, and ViewState.

Let’s say you want to create a composite control that contains a DropDownList that already is bound to database data (namely, it does not allow the control developer to specify the DropDownList’s DataSource as would normally be the case: for a discussion on the pros and cons of this approach check out Composite Controls That Do Their Own DataBinding by Andy Smith).

If you are at all like me, your composite control’s code would look like this (WARNING: this is wrong):

This, as aforementioned is the WRONG WAY to do it. Why? Well, give the control a whirl by creating an ASP.NET Web page with this control and a Button Web control.

When you visit the page the first time, the DropDownList is displayed, populated with the database data. However, if you click the button and the page posts back, the items in the DropDownList disappear – the DropDownList is not saving its view state.

If you’re like me, the first thing you do is crack open Developing Microsoft ASP.NET Server Controls and Components, thumb through to Chapter 12: Composite Controls, and read the section titled “State and Child Controls.”

The gist of the section says that composite controls don’t need to employ extra effort to save the view state of their children since it’s saved automatically when the page recursively walks the control tree to generate the entire view state.

Opening Reflector, I poured through the Page and Control classes and saw that, yes, the control hierarchy should be walked and the view state saved, so when my composite control’s SaveViewState() method was called, it should save not only its own view state but the view state of its child(ren): namely, the DropDownList. But, evidently, it was not.

This got me to scratching my head. Why isn’t the DropDownList’s view state being saved? EnableViewState for both the Web page, composite control, and DropDownList were all set to True (the default). I looked at the SaveViewState() method for the DropDownList and confirmed that it should be saving its view state. So why wouldn’t the DropDownList be saving its view state?

And then it occurred to me – check to make sure that the DropDownList’s IsTrackingViewState property is True – if it isn’t, then the DropDownList won’t be recording changes to its state, and therefore won’t produce a ViewState.

A control begins tracking its view state when its TrackViewState() method is called, and this is handled after the Initialization stage of the page lifecycle. So, if the DropDownList is being added after that stage, then it wouldn’t be tracking its view state, and therefore its state would be lost on postbacks.

But wait a minute, if you add a child control via the Controls.Add() method, the added child control’s TrackViewState() method is automatically called. But wait! Only those items added to the view state after the view state has started being tracked will be recorded.

So binding the items to the DropDownList prior to adding the DropDownList to the Controls collection causes those additions to not be saved in the view state for the DropDownList.

Rather, we need to first add the DropDownList to the Controls collection and then bind the database data to the list. The order matters because we don’t want to bind the data to the DropDownList until after we’ve started tracking view state.

Determining an ASP.NET Page’s View State Footprint

ASP.NET view state is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks.

The view state of a page is, by default, placed in a hidden form field named __VIEWSTATE, and can easily get very large.

Not only does the __VIEWSTATE form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.

Because view state is buried in a hidden form field and because as a developer we typically test locally, the effect of view state bloat on the user experience requires preemptive action. Steps must be taken to measure the view state’s size and to take steps in trimming down view state if it begins to negatively affect the user experience.

There are a variety of techniques for measuring the view state size on a given page. Perhaps the simplest is to turn on page tracing.

With page tracing enabled you can see the estimated view state of each control in the control hierarchy. For instance, the screen show below shows that two Labels on my page consume (roughly) 120 bytes of view state each.

There’s also a free add-on for Firefox that reports view state size directly in your browser window: Viewstate Size. When installed, this add-on will show a little icon in your browser’s lower right corner reporting the view state size for a given page.

It’s also possible to determine the view state size programmatically. Today I was working on a demo for an article and wanted to have the view state size displayed on every page.

After reading an article I wrote back in 2004 – Understanding ASP.NET View State – I came up with the following code snippet to compute and display the view state size for a given page.

This technique uses the “old school” way of doing it, relying on objects that have been around since ASP.NET’s inception. Consequently, the below code will work in any ASP.NET application.

The approach overrides the SavePageStateToPersistenceMedium method, which is what is invoked when the page is ready to persist its view state.

In ASP.NET 1.x you would override this method to store view state to an alternative store, such as to a file on the web server, rather than in a hidden input field on the form. Starting with ASP.NET 2.0 you could use the PageStatePersister class.

However, here I just want to compute the size of the serialized view state string. Consequently, I start by calling the base class’s SavePageStateToPersistenceMedium method.

Next, I replicate the default logic that the ASP.NET Page class uses to serialize view state – namely, I create a LosFormatter object and serialize the content to a StringWriter.

Once I’ve done this I can determine the size of the persisted view state by getting the StringWriter‘s contents and determining how many characters are included.

The above code can be placed directly in a code-behind class or, better yet, in a custom base Page class.

The above programmatic approach is relatively easy to implement and works in all versions of ASP.NET. However, it won’t produce the precise view state size for ASP.NET 2.0 applications and beyond.

This is because the LosFormatter class was replaced with a new formatting type, ObjectStateFormatter, starting in ASP.NET 2.0. (You can certainly use the LosFormatter code above in ASP.NET 2.0 and beyond applications, as the class remains in the framework for backwards compatibility.

Granted, the reported view state size and actual size will differ slightly, but in analyzing whether a page contains too much view state or not, precise numbers aren’t required – a close estimate will usually suffice.)

To get precise measurements we can use the ASP.NET 2.0+ by doing the following:

  1. Create a class that extends the HiddenFieldPageStatePersister class. This is the class that is used by ASP.NET (by default) to persist view state and other information to hidden form fields. We want to extend this class to include a property that reports the size of the persisted state, and
  2. Override the Page class’s PageStatePersister property and return the custom persister class created in step 1.
  3. Override the Page class’s SavePageStateToPersistenceMedium method and read the value of the view state size from the class created in step 1.

Here’s the code for the class that extends HiddenFieldPageStatePersister, which I’ve named MyHiddenFieldPageStatePersister (please don’t mock me for my lack of naming creativity).

This class is pretty simple: it defines a property named StateSize, overrides the Save method, and then sets the StateSize property from this method using the same code/logic as used internally by the HiddenFieldPageStatePersister class.

The code snippet below takes advantage of some language features that you might not have at your disposal if you’re using an older version of C# or VB (for example, the use of automatic properties).

Links to Scott Guthrie’s Using LINQ to SQL Tutorials

Back when Visual Studio 2008 came out, Scott Guthrie wrote an excellent series of blog posts on using LINQ to SQL.

Unfortunately, the various installments are not easy to follow when starting from Part 1 and going onward, so I’ve decided to gather and organize the links here for me and for anyone else interested in his tutorial.

Using LINQ to SQL

Also, there was (at one time) a single PDF containing all of these tutorials, but the website where it was hosted appears to be offline. Does anyone have a copy of that PDF they’d care to send me to host?

UPDATE: Some time ago a developer by the name of Kadir Pekel compiled all nine tutorials into a single PDF and hosted them on his website, http://it-box.blogturk.net, but that website no longer is around.

Helpful reader Milan had a copy of said PDF and sent it to me (thank you!), which you can download here, if interested: http://www.datawebcontrols.com/classes/LINQToSql.zip