Archives

Archives / 2005 / March
  • ObjectHierarchicalDataSource sample code

    <my:ObjectHierarchicalDataSource runat=server ID=ObjectInstance1 TypeName="Categories">
      <SelectMethods>
        <my:SelectMethod TypeName="CatsCategory" Method="GetCats" />
        <my:SelectMethod TypeName="Cat" PropertyNames="Color,Gender" />
      </SelectMethods>
    </my:ObjectHierarchicalDataSource>

    <asp:TreeView Runat=Server ID=categoryTree DataSourceID=ObjectInstance1
       
    ExpandDepth=0 PopulateNodesFromClient=true>
      <DataBindings>
        <asp:TreeNodeBinding TextField="#" ValueField="#" ToolTipField="#" PopulateOnDemand=true />
        <asp:TreeNodeBinding DataMember="CatsCategory" TextField="Name" ValueField="Name"
         
    ToolTipField="Name" PopulateOnDemand=true />
        <asp:TreeNodeBinding DataMember="Cat" TextField="Name" ValueField="Name"
         
    ToolTipField="Description" PopulateOnDemand=true />
        <asp:TreeNodeBinding DataMember="Color" FormatString="Color: {0}" PopulateOnDemand="true"
          SelectAction="None" TextField="Name" ValueField="Name" ToolTipField="#" />
        <asp:TreeNodeBinding DataMember="Gender" PopulateOnDemand="true" SelectAction="None"
          TextField="#" ValueField="#" ToolTipField="#" />
      </DataBindings>
    </asp:TreeView>

  • World safe from mad scientists

    After all, we may be safe from the mad scientists at CERN (just kidding: some of these guys are not yet entirely mad) producing low-velocity black holes that could have swallowed the Earth if Hawking radiation just happened not to work after all. Well, the mad scientists at RHIC may have just created black holes (or more correctly objects that act like black holes but may be supersymmetric dual objects to black holes (no, I don't really understand what I'm writing here, just pretending)) and observed them evaporate through Hawking radiation.
    If this is confirmed, it means three different things:
    • Black holes have been produced in a laboratory. Scary, but they are very small ones.
    • Hawking radiation works
    • Superstring effects have been observed
    An of course, the Earth is safe from destruction by artificial black holes. So we're back to worrying about nuclear holocaust, climate changes, pollution, strangelets, massive epidemies, ateroids hitting the Earth. Ew, that was a close one.
     
    Source:
    through Julien Ellie.

  • How do I reduce this ViewState thing?

    ViewState is a hugely useful feature of ASP.NET, but it's easy to misuse. It's also a little difficult to apprehend for ASP.NET beginners as it's working behind the scenes. The only thing you see at first is this huge blob on your page source.
    If you don't know how ViewState works or what it's for, and even if you do, you should read this MSDN article. In a nutshell, ViewState is a state bag that's maintained from postback to postback. It materializes one of the scopes you can use to maintain state in your application:
    • Context: local to the request (equivalent in scope to a page property).
    • ViewState: local to the page, survives postbacks (but if you open two browsers on the same page, they have separate versions of the ViewState).
    • Session: local to the remote user session (if you open two browsers using CTRL+N, they share the same session, but if you open two completely different instances of the browser, they don't), has a finite lifespan (20 minutes idle time by default), does not survive the browser closing. The Session can be shared across servers in a Web Farm.
    • Cookies: local to the remote user account, can survive the browser closing, has a finite lifespan.
    • Cache: local to the web application, shared by all users, not shared in a farm, expires based on a lifespan or arbitrary dependancies.
    • Application: local to the Web application, shared by all users, not shared in a farm, doesn't expire except if the application is recycled.
    • Static variables: shared by the whole application domain. Don't use that in a web application. Use Application variables instead (unles you really really know what you're doing).
    The way it works is by tracking all changes from the moment TrackViewState is called, which happens normally between Init and Load. This means that any change you make after Init will be persisted to ViewState.
    So the first thing you can do to reduce the viewstate is to do all initialization work during... yes, Init.
    The data that you do want to persist across postbacks must be loaded during... you guessed it, Load.
    The way it persists from postback to postback is by serializing all changes since tracking began into the __VIEWSTATE hidden HTML field. This is the big blob you see in your page. To avoid tampering, it is by default MAC-hashed.
    There are a few reasons why you could want to completely disable ViewState (which is done by setting EnableViewState to false in the page directive or on any Control):
    1. Your page won't post back: pure contents pages, for example.
    2. Your page will post back, but the data will be completely different for every postback: a search results page where you handle the pagination logic using lazy loading, for example.
    3. Your page will post back, but you chose to rebind the data on every postback.
    4. The control does not handle postback data.
    5. The control does not persist any data.
    6. The control rebinds the data on every postback.
    The third and sixth ones are particularly interesting because it's a decision you have to make in the context of your particular application. If the bandwidth the ViewState is eating costs you more than querying the database, then disable ViewState. Otherwise, keep it on but don't bloat it unnecessarily (by moving initialization code to Init and keeping persisted data loading in Load).
    If you choose to requery the data on every postback, consider doing it in Init. This way, you can keep the data out of ViewState and still use the ViewState for other properties: you get finer granularity.
    Another problem you may hit on ASP.NET 1.1 is that some controls do not like to have their ViewState disabled. DataGrid is one example of a control that more or less ceases to function properly without ViewState. That's why we introduced the concept of ControlState in ASP.NET 2.0. The ControlState is a part of ViewState that can't be disabled. It is used for these very few properties on each control that are absolutely necessary for the control to function. It could be the page number for a pagination control, for example. So in ASP.NET 2.0, you can safely disable ViewState on any of the new controls without them breaking down. GridView, which replaces DataGrid, is one of these controls.

  • Develop a HttpHandler with full IntelliSense

    Ashx files have a bad reputation. There is little documentation about them in v1, and no support for them in Visual Studio 2003. With ASP.NET 2.0 and Visual Studio 2005, this changes, and it becomes as easy to develop an ashx file as any other class.
    But what is an ashx file, you may ask? It's an HttpHandler, a class that handles an http request. An ASP.NET page can be considered a kind of elaborate HttpHandler, for example. There are cases where you won't need all the Page infrastructure, WebControls, events and all that. Let's say that you want to stream a thumbnail image to the client, for example. All you need is a reference to the context (to be able to get some information from the QueryString, send data to the response, etc.). That's no more and no less than what the HttpHandler infrastructure gives you.
    So when you need raw treatment of a http request, use a handler instead of a page.
    I've made a few screen copies while developing a very simple handler, so that you can see how easy it becomes to develop an ashx file in Visual Studio 2005 (click on the images to get them at full resolution):
     
    Step 1
    Step 1: Adding a new item to the project. I'm choosing "generic handler", which will create the ashx file with the code structure already there.
     
    Step 2
    Step 2: This is the code structure that Visual Studio provides. I did not write a single character at this point.
     
    Step 3
    Step 3: I have full IntelliSense and code coloring on my code. Everything works exactly the same as in any other code file.
     
    Step 4
    Step 4: I also have access to refactoring, immediate squiggly red lines under my syntax errors, etc.
     
    Step 5
    Step 5: I can build the page, the whole web site or the whole solution (or even just save and let the server auto-compile on the first request).
     
    Step 6
    Step 6: I can see build errors (I made stupid errors on purpose here, in real life I know how to initialize an array) and click on them to get to the faulty source code.
     
    Step 7
    Step 7: I'm almost done. The handler compiles.
     
    Step 8
    Step 8: And it works perfectly!
     
    Update: Scott Hanselman has a great HttpHandler template to get you started.

  • Clean Office automation on the server... at last!

    One of the very common requests we see on the ASP.NET forums is how to generate Excel or Word documents on the server? There are currently three approaches to answer this need:
    1. Output HTML or XML and just change the mimetype so that the relevant Office application opens the stream. All Office applications being quite HTML and XML friendly, chances are you'll get a pretty good result while leaving server resources reasonably untapped. But it's hacky to say the least, and what you get is not a real Office document, just some HTML or XML document open in Office. This means that you won't be able to use most of the features of the Office application (like formulas in Excel, which is quite a large drawback). If you're brave, you may generate a proper Office XML format (the keywords here are WordprocessingML and SpreadsheetML), but you may want to fall back on 2:
    2. Use a third party server library that generates well-formed Office documents. There are quite a few floating around. Google MSN Search is your friend.
    3. Install Office on the server, spawn one of the Office applications and automate it from the server. You shouldn't do this if you can avoid it, as this KB article explains. The problems (apart from licensing) are due to Office applications being built to be desktop applications, not scalable server components. Read the KB article for more details, but in a nutshell, you'll have to deal with singletons, queues, cleanup procedures, etc. and even if you do it relatively cleanly, it will perform poorly. It just does not seem worth the trouble. The Office Web Components are also client-side objects that won't give good results server-side.
    Starting with Visual Studio Tools for Office (VSTO) 2005, server-side objects are provided that solve this problem. It's like option 2., only it's done by Microsoft.
     
    Check out the article here: