BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

October 2006 - Posts

  • PHP and the FastCGI Module for IIS 7.0

    I've blogged several times in the past about how cool IIS 7.0 is.  Many of my posts have highlighted some of the rich new ASP.NET and .NET developer opportunities it brings (integrated pipeline, unified web.config configuration, integrated admin tool experience, etc).  It is really going to open up huge developer opportunities and provide an immensely customizable web-server for people to use.

    In addition to focusing on .NET developer features, we are also working hard to enable non-.NET development stacks to easily integrate with the web server.  Earlier today Bill Staples (who runs the IIS team) demoed a great new FastCGI module for IIS7 at the ZendCon PHP Conference being held this week:

    We've been working closely with Zend this past fall on improving PHP support on top of IIS, and with this new module PHP developers will be able to get dramatically better performance, scalability and reliability when running on Windows (sometimes as much as 25x faster than the old PHP CGI module for IIS). 

    They'll also be able to easily integrate with the cool new IIS7 features that are coming (for example: take advantage of the new output caching features), as well as integrate nicely with ASP.NET.  For example: You could have ASP.NET provide the membership and role management features for a site, while still writing many pages within it in PHP (since with IIS7 an ASP.NET HttpModule can execute for any request to the web-server, and so the Forms Authentication, Role Management and other features are no longer restricted to urls mapped to ASP.NET).

    To learn more about the IIS 7.0 FastCGI module and how to use it with PHP, make sure to check out Bill's great tutorial walkthrough here.  Rick also has a great blog post about how the module works here.  Also make sure to subscribe to Mike's blog and the www.iis.net blog feed here.

    Hope this helps,

    Scott

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • More Tutorials on Working with the DataList... and More Tutorials in the Pipeline!

    Eight new tutorials have been added to my Working with Data in ASP.NET 2.0 series. This latest batch of tutorials examines how to edit and delete data from the DataList control. These tutorials follow, in scope, the concepts discussed in the earlier edit/insert/delete-related tutorials that focused on the GridView, DetailsView, and FormView controls. These DataList-specific tutorials, however, do include a look at performing batch updates (a topic lacking from the GridView/DetailsView/FormView-specific ones). As always, each tutorial is available in both VB and C#, includes the full working code as a downloadable ZIP, and can be downloaded as a PDF for offline access.

    When I started writing these tutorials I was slated to write 46 in total, and, to date, 43 of the 46 are up at http://www.asp.net/Learn/DataAccess/. (They are also being added to MSDN's website, but at a much more glacial pace.) Anywho, the good news is that I've signed on to author another 29 tutorials over the coming months, which will continue the series and be available at http://www.asp.net/Learn/DataAccess/ as they come online.

    Here is the planned outline. The content to be covered is pretty much solidified, but there may be some slight modifications, reordering of sections/tutorials, and so forth. I've actually completed the “set” of tutorials on the SqlDataSource (the first four), and will start hammering out the next set this week, time permitting.

    1. Accessing Database Data Directly from an ASP.NET Page
      1. Querying Data with the SqlDataSource Control
      2. Using Parameterized Queries with the SqlDataSource 
      3. Inserting, Updating, and Deleting Data with the SqlDataSource Control
      4. Implementing Optimistic Concurrency with the SqlDataSource
    2. Enhancing the GridView
      1. Adding a GridView Column of Radio Buttons
      2. Adding a GridView Column of CheckBoxes
      3. Inserting a New Record from the GridView’s Footer
    3. Working with Batched Data
      1. Batch Updating
      2. Batch Deleting
      3. Generating Multiple Details Records Which Copy Multiple Columns of Data From a Common Master
    4. Working With Binary Files
      1. Uploading Files
      2. Including a File Upload Option When Adding a New Record
      3. Displaying File Information in the Data Web Controls
      4. Changing the Uploaded File for an Existing Record
    5. Caching
      1. Caching Data with the ObjectDataSource
      2. Caching Data at the Business Logic Layer
      3. Using SQL Cache Dependencies
      4. Caching Data at Application Startup
    6. Data and the Site Map Provider
      1. Building a Custom Database-Driven Site Map Provider
    7. Advanced Data Access Layer Scenarios
      1. Having the Typed DataSet Create Your Stored Procedures
      2. Integrating Existing Stored Procedures with the TableAdapter
      3. Techniques for Performing JOINs
      4. Adding Additional DataTable Columns
      5. Working with Computed Columns
      6. Configuring Connection- and Command-Level Settings in the DAL
      7. Wrapping Database Modifications in a Transaction
      8. Debugging Stored Procedures
      9. Protecting connection strings
      10. Creating SQL Functions and Stored Procedures with Managed Code
  • Working MasterPage Samples

    A few people have asked me for a working web site with some of the code from my MasterPage: Tips, Tricks, and Traps article. This download is a web site based on the ASP.NET Personal Web Site Starter Kit and provides a number of the samples from the article.

    Samples include a master page base class, and an HttpModule to assign the MasterPageFile property for .aspx web forms at runtime. There is an example of content page to master page interaction through a strongly typed Master property, and an example of master page to content page interaction via an event.

  • Tip/Trick: Handling Errors with the UpdatePanel control using ASP.NET AJAX

    Luis Abreu is an ASP.NET MVP who has a great blog on the http://msmvps.com blog site.  Earlier today he posted a great tutorial post that describes how to use some of the new features in the ASP.NET AJAX Beta1 release to add more robust error handling into your application.  I highly recommend reading and bookmarking it for future use.

    Error handling in an AJAX world can often be tricky -- especially when AJAX call-backs are taking place and a mixture of client and server code is running within an application.  In its most recent release, the <asp:updatepanel> control that comes with ASP.NET AJAX now has much more robust error handling and reporting features for you to use.  Specifically:

    1) You can now handle the "OnAsyncPostBackError" event on the <asp:scriptmanager> control to catch and/or modify an error message that occurs during the processing of an AJAX postback callback on the server. 

    2) You can now set the "AllowCustomErrors" property on the <asp:scriptmanager> control to enable the standard ASP.NET custom error support to be enabled to redirect a user automatically to an error page when an error occurs (even if it is happening during an AJAX postback).

    3) You can now optionally handle client-side JavaScript events on the page to intercept any error message sent back from the server, and perform custom client-side actions as a result (for example: to output the error message to a nicely formatted <div> section instead of performing a pop-up message). 

    Read all about how to take advantage of the above new features from Luis' great tutorial here.

    Hope this helps,

    Scott

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • Automatically Updating Applications (ClickOnce vs. ClickThrough)

    I am working on a little side project that happens to be a smart client application and I have gotten around to working out how to deploy and update the application. I have used the Application Updater block in the past and it worked out well, but that is supposed to be replaced by ClickOnce in .NET 2.0. So I started looking into ClickOnce but didn’t really like what I found.

    I don’t want to deploy the application directly from the web. I want to have the user download and install an .msi file (or execute it from a CD, etc). This gives me more flexibility into what is installed (I need to switch some resource file settings, etc). More importantly this application is targeted at people who are not very computer savy, so the extra warnings that come with ClickOnce web deployment would scare or confuse them. There are also some limitations around Firefox support (which have been partially alleviated, but still complicate things).

    All I really want is something to perform automatic updates, and as far as I can tell there isn’t a way to use the ClickOnce automatic updates framework without deploying your application using ClickOnce.

    This is where ClickThrough comes to the rescue. ClickThrough is an extension to the WiX toolkit that makes it very easy to update applications on the fly, similar to the Application Updater Block, but actually uses an RSS feed to check for updates! Its part of WiX v3 which means it is still under development, but I am going to give it a shot anyway.

    I haven’t actually gotten it all working yet, but so far it looks very promising.

    -James

  • First Wikipedia Edit

    I just added my first article (well, it’s just a stub right now) to Wikipedia. While doing some vanity googling (still beating Uncle Phil) I read about a sailor named James Avery who received the medal of honor during the Civil War. I couldn’t find much about the rest of his life, but hopefully I will un-cover some stuff while digging through the library and can improve the stub.

    I forgot to add the stub tag, but 2 minutes after I added it someone else did it for me. (A 16–year old from England no less) Wikipedia is a wonderful thing.

    You can check it out here.

    -James

  • CSS Control Adapters Update (Beta3)

    I've blogged in the past about the great CSS Control Adapters that Russ and Heidi have been working on.  These adapters use a new built-in extensibility mechanism in ASP.NET 2.0 called "control adapters" that allow you to plug-in into any ASP.NET server control and override, modify and/or tweak the rendering output logic of that control.

    The control adapters that Russ and Heidi built provide a pure CSS based rendering (no tables) for all of the ASP.NET Data (GridView, DataList, DetailsView, FormView, etc), Navigation (Menu, TreeView), and Login (Login, CreateUserWizard, ChangePassword,  PasswordRecovery, LoginStatus) controls. 

    You can learn more about them and how to use them with your projects from my past tutorial blog post here.

    Beta3 CSS Control Adapters Release

    Earlier this week we published the "Beta3" version of the CSS Control Adapters which incorporates more feedback and suggestions, along with a number of new features.  Here are some shortcuts to a few cool new highlights:

    • Go to the Menu sample. Increase your browser's font size. In Internet Explorer use View > Text Size > Larger.
    • Go to the CreateUserWizard sample. Navigate with accesskeys. If using Windows, press Alt + e to set the focus to the textbox for the Email address. (In Internet Explorer you must also hold down the Shift key to use the accesskey for the password textbox.)
    • Try out the redesigned TreeView sample. Expand several nodes in the tree. Select a node to cause the page to post back. Notice that the tree maintains its expansion, visibly marks the selected node and uses its value to change the page's sample content.
    • Play with cascading checkboxes.
    • Validate that these pages conform to the XHTML 1.1 Strict standard.

    You can learn more and download the free CSS Control Adapters (including both VB and C# versions of the source) from this web-site: http://www.asp.net/cssadapters

    Hope this helps,

    Scott

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • Jobs! Jobs! Jobs!

    I decided to give hiddennetwork.com a try and start hosting a job board and job advertisements on my blog. Job boards seem to be all the rage these days and blogging has helped me find some of the best members of our current team. It’s usually the people reading blogs that are passionate about technology and writing code (which are the type of people I always try to hire).

    Check out the ads to the right if you are looking for a new job, or if you are an employer you should definitely look into posting your job reqs with hiddennetwork.com.

    -James

  • MacBook Pro Pt. 2

    I found a number of folks using a MacBook Pro for .NET Development:

    Visual Studio.NET development on OS X w/ Parallels

    Anyone using Visual Studio in Parallels on a MacBook Pro? (lots of good comments here)

    A few weeks with a MacBook Pro, Parallels, and MSDN Universal

    But in the end I decided I wasn’t ready to make “the switch” just yet for a number of different reasons:

    • I do almost 100% .NET development
    • I don’t want to lose the max power of my hardware while writing code, even though it might be 90% it is still only 90%. (Also it doesn't appear that you can use multiple monitors with Parallels or take advantage of both cores in a dual core)
    • I don’t want to deal with the fact that I am a .NET consultant and would be walking into clients with a Mac. I am sure most wouldn’t care, but there are a number of people in the MS/.NET camp who would hold it against me. (I know that is a chicken-*** reason, but I make my money billing as a .NET consultant so I have to be mindful of it)

    If I start doing more Ruby development, or become focused more on writing or other projects I might pick up a Mac for those purposes, but I won’t be replacing my main .NET development machine anytime soon.

    -James

    -James

  • I'm presenting at the North Dallas .NET User Group on November 2nd

    I'm very excited to have the opportunity to present at the North Dallas .NET User Group on November 2nd (next Thursday). 

    I'm going to speaking for a little over 2 hours on a variety of fun topics.  My plan right now is to spend the first hour doing a brand new ASP.NET Tips and Tricks talk, and then spend the second hour doing a deep dive into the new LINQ technology that we are shipping next year (and which will dramatically improve data productivity).

    The event is totally free to attend.  I hope to see some of you there!

    Scott

    P.S. The following week I'll be presenting 2 keynotes and 2 breakout sessions at the ASP.NET Connections Conference in Las Vegas

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • MacBook Pro

    Now that the Core Duo 2 MacBook Pro is available I am seriously considering picking one up. I was checking out Jim Weirich’s setup at work (yeah, that Jim Weirich) and I was surprised how well XP runs in Parallels. Anybody else out there do some serious development with this kind of setup?

    -James

     

  • What's Wrong With This Code? (#8)

    Joe Developer is working with a simple struct:

    struct Point
    {
        
    public int x;
        
    public int y;
    }

    Joe's tech lead asked him to write a method that will return an array of 10,000 initialized points. Joe wrote following code.

    Point[] CreatePoints()
    {
        
    Point[] points = new Point[10000];

        
    for (int i = 0; i < points.Length; i++)
        {
            pointsIdea =
    new Point();
        }

        
    return points;
    }

    The code doesn't create any runtime errors, but Joe is worried because his tech lead looked at the code and frowned. What could provoke such a reaction?

    Hint: Joe's lead is a performance nut.

  • Even Non-MVPs get Congratulatory Letters from Microsoft

    As noted before I was NOT renewed as an MVP this year, so I was surprised to get a letter today that said the following:

    "On behalf of the East region, we want to say Congratulations! for your recent award as a Microsoft Most Valuable Professional (MVP) in Visual Developer - ASP/ASP.NET . . . ."

    I don't think my status has changed, nor should it, but apparently someone at Microsoft believes differently for some reason.

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • What's In a Workflow Queue Name?

    There is a queuing infrastructure in Windows Workflow that facilitates communications between workflows and the outside world. Event related activities, like the HandleExternalEvent and Delay activities, provide a formalized layer of abstraction over this queuing infrastructure. You might never need to know that a queuing service exists if you can get 100% of the job done with components from the base activity library.

    If you need more flexible messaging, or like Harry, want to work with a low level API, you can use the queuing service to create queues and en-queue messages for your own purposes. Before jumping in, it's worthwhile to study how the built-in activities make use of workflow queues, particularly workflow queue names.

    If we look at the correlated local service example in the Windows SDK, we'll find a Parallel activity with two sequences inside. Both sequences call a CreateTask method and expect a TaskCompleted event to arrive. A local service we've implemented has to raise this TaskCompleted event, but the event isn't delivered directly to the running workflow. Instead, the workflow runtime catches the event. The workflow instance might be unloaded from memory and living as a serialized blob in a database table. The runtime will reload the proper workflow and deliver the event.

    If there are multiple workflow instances active, it's easy for the runtime to find the right instance because of the InstanceId property on all incoming event arguments (local service communications might define event arguments that derive from the ExternalDataEventArgs class).

    But how does the workflow know what activity is waiting for the event? This isn't hard if there is only one activity waiting for an event, but in this sample we have two activities both waiting for the same event from the same service.The secret is in the workflow queue names the individual activities create to wait for the events. If we use GetWorkflowQueueData on the workflow instance, we can inspect the queue names. A queue name in the this SDK sample will look like the following:

    Message Properties
    Interface Type:ITaskService
    Method Name:TaskCompleted
    CorrelationValues:
    001

    What we see is that the workflow queue "name" actually contains all of the information the runtime needs to deliver events to their proper destination. The name includes the interface and event name, as well as correlation values when the associated activities have correlation tokens.

    Queue names in windows Workflow are more than just friendly identifiers. As Harry pointed out, they implement IComparable and are actually a key piece to how Windows Workflow works with data exchange services.

  • Tip/Trick: Cool UI Templating Technique to use with ASP.NET AJAX for non-UpdatePanel scenarios

    I've been having some fun playing around with the ASP.NET AJAX Beta release this weekend. 

    Usually when I integrate AJAX functionality into my code I just end up using the built-in server controls that ASP.NET AJAX provides (UpdatePanel, UpdateProgress, etc) and the cool controls in the ASP.NET AJAX Control Toolkit.  Scott Hanselman had jokingly called using these AJAX controls "cheating" when he interviewed me two weeks ago for his latest podcast - since they don't require that you write any client-JavaScript for most common scenarios.

    This weekend I decided to focus my coding on some of the client JavaScript pieces in the ASP.NET AJAX framework that don't use UpdatePanels at all, and to experiment with alternative ways to use the server to easily generate HTML UI that can be dynamically injected into a page using AJAX.  In the process I created what I think is a pretty useful library that can be used with both ASP.NET AJAX and other AJAX libraries to provide a nice template UI mechanism with ASP.NET, and which doesn't use or require concepts like postbacks or viewstate - while still providing the benefits of control encapsulation and easy re-use.

    First Some Quick Background on the JavaScript Networking Stack in ASP.NET AJAX

    To first provide some background knowledge about the client JavaScript library in ASP.NET AJAX before getting to the template approach I mentioned above, lets first walkthrough building a simple AJAX "hello world" application that allows a user to enter their name, click a button, and then make an AJAX callback to the server using JavaScript on the client to output a message:

    ASP.NET AJAX includes a very flexible JavaScript network library stack with rich serialization support for .NET data-types.  You can define methods on the server to call from JavaScript on the client using either static methods on your ASP.NET Page class, or by adding a web-service into your ASP.NET application that is decorated with the [Microsoft.Web.Script.Services.ScriptService] meta-data attribute and which exposes standard [WebMethod] methods. 

    For example, below is a SimpleService.asmx web-service with a "GetMessage" method that takes a string as an argument:

    using System;
    using 
    System.Web.Services;

    [Microsoft.Web.Script.Services.ScriptService]
    public class SimpleService : WebService {

        [WebMethod]
        
    public string GetMessage(string name) {
            
    return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
        
    }
    }

    ASP.NET AJAX can then automatically create a JavaScript proxy class to use on the client to invoke this method and pass appropriate parameters to/from it.  The easiest way to add this JavaScript proxy class is to add an <asp:ScriptManager> control on the page and point at the web-service end-point (this control also does the work to ensure that each library only ever gets added once to a page). 

    I can then call and invoke the method (passing in a value from a textbox), and setup a callback event handler to fire when the server responds using client-side JavaScript code like below.  Note: I could get fancier with the JavaScript code to eliminate some of the lines - but I'm deliberately trying to keep it clear and simple for now and avoid adding too much magic:

    <html>
    <head id="Head1" runat="server">
        
    <title>Hello World Service</title>
        
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
        
        <
    script language="javascript" type="text/javascript">
            
            
    function callServer() {
                SimpleService.GetMessage( $
    get("Name").value, displayMessageCallback );
            
    }
        
            
    function displayMessageCallback(result) {
                $
    get("message").innerHTML result;
            
    }
        
        
    </script>
                    
    </head>
    <body>
        
    <form id="form1" runat="server">
            
            
    <asp:ScriptManager ID="ScriptManager1" runat="server" >
                
    <Services>
                    
    <asp:ServiceReference Path="~/SimpleService.asmx" />
                </
    Services>
            
    </asp:ScriptManager>
            
            
    <h1>Hello World Example</h1>
            
            
    <div>
                Enter Name: 
    <input id="Name" type="text" />
                
                <
    a href="BLOCKED SCRIPTcallServer()">Call Server</a>

                
    <div id="message"></div>
            
    </div>
            
        
    </form>
    </body>
    </html>

    Now when I run the page and enter a name "Scott", the page will use AJAX to call back and dynamically update the HTML of the page without requiring any postbacks or page refreshes.

    A cleaner approach to generate HTML using templates

    As you can see from the example above, I can easily return HTML markup from the server and inject it into the page on the client.  The downside with the approach I am taking above, though, is that I am embedding the HTML generation logic directly within my server web method.  This is bad because: 1) it intermixes UI and logic, and 2) it becomes hard to maintain and write as the UI gets richer.

    What I wanted was an easy way to perform my logic within my web service method, retrieve some data, and then pass the data off to some template/view class to generate the returned HTML UI result.  For example, consider generating a Customer/Order Manager application which uses AJAX to generate a UI list of customers like this:

    I want to write server code like below from within my WebService to lookup the customers by country and return the appropriate html list UI.  Note below how the ViewManager.RenderView method allows me to pass in a data object to bind the UI against.  All UI generation is encapsulated within my View and out of my controller webmethod: 

        [WebMethod]
        
    public string GetCustomersByCountry(string country)
        {
            CustomerCollection customers
    DataContext.GetCustomersByCountry(country);

            if 
    (customers.Count > 0)
                
    return ViewManager.RenderView("customers.ascx", customers);
            else
                return 
    ViewManager.RenderView("nocustomersfound.ascx");
        
    }

    It turns out this wasn't too hard to enable and only required ~20 lines of code to implement the ViewManager class and RenderView methods used above.  You can download my simple implementation of it here.

    My implementation allows you to define a template to render using the standard ASP.NET User Control (.ascx file) model - which means you get full VS designer support, intellisense, and compilation checking of it.  It does not require that you host the usercontrol template on a page - instead my RenderView implementation dynamically cooks up a dummy Page object to host the UserControl while it renders, and captures and returns the output as a string.

    For example, here is the Customer.ascx template I could write to generate the customer list output like the screen-shot above which generates a list of customer names that have links to drill into their order history:

    <%@ Control Language="C#" CodeFile="Customers.ascx.cs" Inherits="Customers" %>

    <div class="customers">

        
    <asp:Repeater ID="Repeater1" runat="server">
            
    <ItemTemplate>
            
                
    <div>    
                    
    <a href="BLOCKED SCRIPTCustomerService.GetOrdersByCustomer('<%# Eval("CustomerID") %>', displayOrders)">
                        
    <%# Eval("CompanyName") %>
                    
    </a>
                
    </div>

            
    </ItemTemplate>
        
    </asp:Repeater>

    </div>

    And its associated code-behind file then looks like this (note: I could add view-specific formatting methods into this if I wanted to):

    using System;

    public 
    partial class Customers : System.Web.UI.UserControl
    {
        
    public object Data;

        void 
    Page_Load(object sender, EventArgs e)
        {
            Repeater1.DataSource 
    Data;
            
    Repeater1.DataBind();
        
    }
    }

    For passing in the data to the template (for example: the customers collection above), I initially required that the UserControl implement an IViewTemplate interface that I used to associate the data with.  After playing with it for awhile, though, I instead decided to go with a simpler user model and just have the UserControl expose a public "Data" property on itself (like above).  The ViewManager.RenderView method then does the magic of associating the data object passed in to the RenderView method with the UserControl instance via Reflection, at which point the UserControl just acts and renders like normal. 

    The end result is a pretty powerful and easy way to generate any type of HTML response you want, and cleanly encapsulate it using .ascx templates.

    Finishing it Up

    You can download the complete sample I ended up building here.  Just for fun, I added to the above customer list example by adding support for users to click on any of the customer names (after they search by country) to pop-up a listing of their orders (along with the dates they placed the order).  This is also done fully with AJAX using the approach I outlined above:

    The entire application is about 8 lines of JavaScript code on the client and a total of about 15 lines of code on the server (that includes all data access).  All HTML UI generation is then encapsulated within 4 nicely encapsulated .ascx template files that I can load and databind my data to from my webmethods on demand:

    Click here to download the ViewManager.RenderView implementation if you want to check it out and try it yourself.

    Hope this helps,

    Scott

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • Splash Screens in Windows Forms

    I had the requirement to create a splash screen recently and did some quick searching to see what the recommended method was in .NET and Windows Forms. I found a number of large code samples, controls you can download, but everything seemed too complicated. It shouldn’t be that hard. Then I ran across Eric Gunnerson’s blog post which recommends simply loading the screen in the constructor of your form and then closing it in the Activated event. It’s incredibly simple and works perfectly.

    -James

  • Refactoring: Using object constructors in HQL with NHibernate

    We are using NHibernate on a big project at work and one of the optimizations we often find ourselves making is creating a “lighter” object and returning that instead of our full objects for searches and other operations where we return a large number of the same object. This also applies to searches that display fields from a hand-full of objects, for instance you might show a Customer’s first name, last name,  their primary address line 1, address zip code, and the date of their last order. You wouldn’t want to return all of these objects and display just the pertinent information, you want to just get the information you are going to show. Especially on search screens that are heavily used throughout the system.

    The other day I noticed that in many of our data access calls we were doing something like this: (mocked up code)

        1 public List<CustomerResult> GetCustomerSearchResults(CustomerCriteria cc)

        2 {

        3     using (Repository repository = new Repository())

        4     {

        5         StringBuilder hql = new StringBuilder();

        6         hql.Append("SELECT c.Name, c.Phone,

                      c.PrimaryAddress.Line1, c.LastOrderDate ");

        7         hql.Append("FROM Customer AS c");

        8 

        9         IList result = repository.Session.CreateQuery(hql.ToString())

       10             .List();

       11 

       12         List<CustomerResult> results = new List<CustomerResult>();

       13         foreach (object[] row in tempList)

       14         {

       15             CustomerResult result = new CustomerResult();

       16             result.Name = row[0].ToString();

       17             result.Phone = row[1].ToString();

       18             result.Line1 = row[2].ToString();

       19             result.LastOrderDate = row[3].ToString();

       20             results.Add(result);

       21         }

       22     }

       23 

       24     return results;

       25 }

    Technically there isn’t anything wrong with this code (I have omitted null checks, etc for brevity) but it could be much more elegant. A little known feature of HQL is the ability to construct and return a new object as part of the statement, the above HQL becomes “Select new CustomerResult(c.Name, c.Phone, c.PrimaryAddress.Line1, c.LastOrderDate)”. The only requirements for this are:

    1) The CustomerResult object needs to have a constructor that matches what is contained in your HQL.

    2) If the class you are creating is un-mapped (like our CustomerResult object would be) then you need to Import the class in one of your mapping files. I created a ImportClasses.hbm.xml file for all of these imports:

        1 <?xml version="1.0" encoding="utf-8" ?>

        2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">

        3   <import class="CustomerResult, MyAssembly"/>

        4 </hibernate-mapping>

    My above code can now be refactored to the following:

        1 public List<CustomerResult> GetCustomerSearchResults(CustomerCriteria cc)

        2 {

        3     using (Repository repository = new Repository())

        4     {

        5         StringBuilder hql = new StringBuilder();

        6         hql.Append("SELECT new CustomerResult(c.Name, c.Phone,

                     c.PrimaryAddress.Line1, c.LastOrderDate) ");

        7         hql.Append("FROM Customer AS c");

        8 

        9         IList result = repository.Session.CreateQuery(hql.ToString())

       10             .List();

       11 

       12         return ConvertToGenericList(result);

       13     }

       14 }

    Sure some of the code has just been moved to the constructor, but I find it much more readable and maintainable.

    -James

  • ASP.NET AJAX Beta 1 Released

    Last month I posted about the official new name for “Atlas,” and discussed the roadmap plan for shipping a free, fully-supported, v1.0 release that works on top of ASP.NET 2.0 and Visual Studio 2005.

    Today I am very pleased to announce the first official Beta release of Microsoft ASP.NET AJAX v1.0. You can download it now from the http://ajax.asp.net site. Available on the site are three download options:

    1) The ASP.NET AJAX v1.0 “Core” download. This redist contains the features that will be fully supported by Microsoft Product Support, and which will have a standard 10 year Microsoft support license (24 hours a day, 7 days a week, 365 days a year). The download includes support for the core AJAX type-system, networking stack, component model, extender base classes, and the server-side functionality to integrate within ASP.NET (including the super-popular ScriptManager, UpdatePanel, and Timer controls).

    2) The ASP.NET AJAX “Value-Add” CTP download. This redist contains the additional higher-level features that were in previous CTPs of “Atlas,” but which won’t be in the fully-supported 1.0 “core” redist. These features will continue to be community supported as we refine them further and incorporate more feedback. Over time we’ll continue to move features into the “core” download as we finalize features in this value-add package more.

    3) The ASP.NET AJAX Control Toolkit. This project contains 28 free, really cool, AJAX-enabled controls that are built on top of the ASP.NET AJAX 1.0 “Core” download. The project is collaborative shared source and built by a combination of Microsoft and non-Microsoft developers, and you can join the community or just download it on CodePlex today.

    Some of the Changes with the Beta

    There are a number of changes that the team has made with this beta release. A few of the significant changes include:

    Performance and Download Size Optimizations

    Previous ASP.NET AJAX CTPs relied on the browser downloading a single large, JavaScript file to the browser that contained all of the features. With this Beta release we have spent a lot of time on factoring out features into multiple files (so you don’t have to download them unless you use them), and in optimizing the bandwidth size of the overall library. The ASP.NET AJAX “Core” download now includes two JavaScript libraries that are used to support all of its features:

    a) The MicrosoftAjax.js.gz script file contains the core JavaScript type-system, component/control model, JSON networking/serialization stack, and application-serviceas features (Profile + Authentication). It is now 14.8k in size.

    b) The MicrosoftAjaxWebForms.js.gz script file then adds the support to enable UpdatePanel scenarios and partial page rendering. It is 6.4k in size.

    These files are only downloaded by a browser once when visiting a site -- they are then cached on the client and reused across all pages and repeat visits. The new size targets should ensure a snappy and speedy experience the first time you hit a site.

    In addition to optimizing the initial download size of the JavaScript libraries, we have spent time optimizing the network traffic size of client JavaScript callbacks to the server. Controls like the UpdatePanel, UpdateProgress, and Control Toolkit controls no longer emit xml-script by default, and instead just emit 1-2 lines of JavaScript (which can help significantly reduce the network traffic size on the wire).

    We have also moved from using JavaScript closure-based classes to using prototype-defined classes in the core type system, which we’ve found reduces memory usage for most common application scenarios.

    Safari Browser Support

    Previous ASP.NET AJAX CTPs didn’t have great support for Safari (UpdatePanel didn’t work at all). With this Beta we have added Safari as a fully tested and supported browser.  We are currently working on adding Opera support as well – although we aren’t ready yet to call it supported with this build (stay tuned for updates).

    Significantly Better Debugging Support

    As anyone who has spent a lot of time doing it can attest, debugging JavaScript is often not a lot of fun. We’ve made two significant changes with this Beta that will help improve the debugging experience with the Microsoft AJAX Library considerably:

    1) By moving our JavaScript class definitions from being closure-based to prototype-based, you can now use the existing Visual Studio 2005 script debugger (and/or other existing JavaScript debuggers) to better inspect and step through JavaScript objects. Closures previously hid a lot of inspection information.

    2) We invested a lot of time putting together an automated JavaScript build environment that enables us to produce two versions of all of our JavaScript files: a retail version that is optimized for performance and download size, and a fully instrumented debug version that is optimized for helping you catch issues with your code during development. Every function within the debug version of our script files now includes parameter and argument validation code that verifies that the function is being passed the correct arguments before running, and that will assert with stack trace information if not. This can help to more easily pinpoint errors with your JavaScript code early, and hopefully significantly improve JavaScript debugging.

    Note: By default, the decision to use the retail vs. debug versions of the AJAX script libraries is driven by the <compilation debug=”true|false” /> setting within your web.config file. Because this client-side parameter validation code significantly increases the size and performance overhead of the client-libraries, make sure you set debug=”false” before deploying any application (for more reasons on why you should always set debug=”false” when deploying ASP.NET applications, please read this past post of mine).

    Another Note: Our plan is to have the next version of Visual Studio use the same argument validation metadata that we use at runtime with debug scripts to also drive IntelliSense and syntax checking of JavaScript within the IDE. You can add this metadata to your code to improve validation, error checking, and eventually IntelliSense of your own JavaScript libraries as well.

    UpdatePanel Improvements

    The UpdatePanel control have been updated significantly with this Beta release to incorporate customer feedback. In addition to adding Safari browser support, the UpdatePanel control now has new support with this Beta for:

    a) Client-side script event hooks to let you write client-side JavaScript to more easily participate in callbacks.

    b) The ability to contain controls within an UpdatePanel that trigger both partial-page postbacks as well as normal postbacks (you now get to choose depending on your scenario). You can also now disabled child controls from causing UpdatePanel postbacks at all.

    c) The ability to use ASP.NET validation and Wizard controls within UpdatePanel controls (there were some bugs that prevented this before).

    d) The ability to dynamically create and add UpdatePanel controls into a page, rather than having to statically define them. This is particularly useful for control developers who can now instantiate and use UpdatePanel controls within their composite controls.

    e) The ability to have multiple UpdateProgress and Animation controls on a page that can run conditionally based on which UpdatePanel callback is occurring.

    f) The ability to declaratively specify how long to wait before an UpdateProgress control should become visible. This enables you to avoid showing progress status for quick UpdatePanel callbacks.

    g) Support for screen readers and other accessibility tools with UpdatePanel scenarios to better implement Section 508 standards.

    Important Beta Note: the UpdateProgress control with the Beta is currently shipping in the "Value-Add" download, so you will need to add this to your site in order to use it.  With the next beta refresh it will be moved to the "core" download, and will be a fully supported scenario. 

    Lots of Improvements in the Client Script Library Stack

    We’ve incorporated a lot of customer feedback and cleaned up, simplified, and enhanced a lot of the client-side JavaScript library APIs. In addition to moving from closures to prototypes, a number of other API cleanup changes have been made including:

    a) Simpler client JavaScript event model. It is now easier to define and attach events on the client. Object events are also now created on demand to reduce startup time and the size of the working set.

    b) Simpler Component, Behavior, and Control types. APIs can now be used without first needing to instantiate their related objects, and on-demand semantics have been added to improve performance.

    c) Client networking improvements. Default callback functions and method-name semantics provide a much easier way to perform common asynchronous callbacks.

    d) Membership and Profile APIs. Simpler APIs for interacting with the Membership and Profile APIs from client-side JavaScript are now supported.

    Better Compatibility with other AJAX Libraries

    One challenge with JavaScript is that collisions between different client-side JavaScript libraries can be ugly. Previous ASP.NET AJAX CTPs defined a global helper function named $( ) that conflicted with other common JavaScript libraries (including Prototype and Scriptaculus).

    With this Beta we have renamed our $( ) function to $get( ) and made a few other naming changes to help enable multiple independent AJAX libraries to play nicely together on the same page.

    Source Modification License

    One common request we have received is the ability for developers to make source modifications to the core Microsoft AJAX JavaScript library (to add a small feature, tweak an implementation, or make a tactical bug fix).

    We are going to provide a license to explicitly allow custom modification of the libraries, and the ScriptManager API that ships with this Beta now allows you to provide alternative implementations/tweaks of the built-in JavaScript libraries. In addition to allowing you to tweak the libraries for your own applications, the license will also grant redistribution rights so that you can ship them with your own components and extensions. (The one requirement for redistributing your own custom version is that you need to change the namespace to avoid conflicts.)

    We think the combination of having both full enterprise-level support (with 10-year support services), along with modification redistribution rights is a really powerful offereing that will provide developers with a ton of flexibility regardless of their project type, size, or target audience.

    Next Steps

    As you probably noticed from the paragraphs above, there are a number of new features and changes with this Beta. Existing ASP.NET AJAX code will need to be updated to reflect these changes.

    If you have been using server-side ASP.NET AJAX features, you should find the updates relatively straightforward. These will mostly involve renaming the control prefix from <atlas:> to <asp:>, modifying the trigger syntax for UpdatePanel controls, and making small syntax changes to how extender controls in the Control Toolkit are declared.  You can read a migration guide with the details on how to-do this here.

    If you have created your own JavaScript class types and, or if you interact with the component model directly, you will need to make more significant changes. What we’ve found when updating samples is that the JavaScript changes are not too complicated by themselves – what is frustrating is that JavaScript’s type-less flexibility prevents tool compilation checking, and forces you to update things iteratively to find and fix each change, which can be tedious and annoying. To help with migration from the CTP to the Beta, the ASP.NET AJAX Team has published a detailed document listing the specific changes that have been made and which includes code samples that show before and after versions of common patterns and APIs usages. We will be publishing this document shortly here.

    The ASP.NET AJAX team will also be monitoring the forums closely over the next few weeks to help people with migration questions and any issues they find. Please post in the forums to get help if you run into any issues, find any bugs, or need any help.

    We are really looking forward to having lots of people use the Beta and to getting more feedback. We believe the API definitions for the features currently in the ASP.NET AJAX v1.0 Core download are now pretty close to being final, and our plan for the rest of this year will be to keep taking feedback and bug reports, and stabilize and lock down the release. Our plan is to release a beta refresh in a few weeks that incorporates customer feedback, then ship a RC release after that, and then ship it as a fully supported 1.0 release once people feel it is ready.

    Thanks,

    Scott

    Share this post: Email it! | bookmark it! | digg it! | reddit!
  • The Fall Tour

    I spent the summer as a hermit. Here are some events where I'll be presenting over the next three months.

    VSLive! Boston (Oct 24 - Oct 27). On Wednesday afternoon, I'll show you how to bend master pages to do your bidding. There is some great ASP.NET 2.0 content in this show with the likes of Fritz Onion, Miguel Castro, Chris Kinsman, and more.

    VSLive! Dallas (Nov 14 - Nov 17). One presentation on master pages, and one presentation to help make sense of web site projects, web application projects, and web deployment projects.

    Central Penn Code Camp (Dec 2). I'll probably do one talk on an ASP.NET topic, and one introduction to Windows Workflow.

    CMAP User Group (Dec 5). Every December, the central Maryland user group has a tips and tricks show. Different presenters each take 20 minutes and show you tools and time saving techniques you'll find useful in everyday development. Free pizza and door prizes, too!

    BaltoMSDN User Group (Dec 18). If you are in Baltimore or Northern Maryland, come out and support the newest user group in the area. Topic TBA.

  • Screwturn Wiki

    On Dave’s recommendation I installed this new Wiki and was thoroughly, and I do mean thoroughly, impressed. I have been using FlexWiki for sometime and I have to say that Screwturn really blows it away. It has built in security, one-click backup, its extremely customizable, and much more.

    If you are looking for a wiki (and who isn't?!?!) then check it out.

    -James