Tag Archives: asp.net

WebForms – How do I Unit Test Thee?

I’m a huge fan of unit testing… its my safety net, allowing me to make changes to an application without fear that I’ve broken core functionality. With my favorite web development framework, ASP.NET, its been very difficult to build unit tests for the server-side code that you write for the Web Forms UI framework.

I decided to do some research and start doing something about that.

Continue reading

Where Did My ASP.NET Bundles Go in ASP.NET 5?

Stuffed BagEdit: There is now a screencast version of this post available.

Since ASP.NET 4.5 in 2012, developers have had access to a pair of tools in their ASP.NET toolbox called “bundling and minification”.  This feature would direct the webserver to combine together CSS or JavaScript files into one extra-large file and then apply a minification algorithm to shrink the size of the file for delivery.  In ASP.NET 5 however, this feature is no longer available.  In this article, I’ll review where bundles were configured and how you can migrate them to the recommended deployment model for ASP.NET 5

Continue reading

That Annoying ASP.NET Issue with Postback

Stop me if you’ve heard this before:

I’m working through an ASP.NET project and suddenly Postback stops working.  I know!  This is the simplest of interactions with an ASP.NET web forms application, and its not WORKING!!  What the heck is wrong with this stupid website?  I mean, I didn’t change anything.. I just want my default.aspx form to be able to have a button click button handler.  Is that so DIFFICULT?  Get your act together FRITZ!1!!

I did some digging and digging on this one.  Did I bring in an add-in or library to my project that was preventing the postback from capturing the click event?  I broke out Fiddler and analyzed the traffic, to ensure that the form content was indeed being submitted properly back to the server.  Everything looked good there.

My next analysis step was to take a look at the Request.Form collection.  I should see the __EVENTARGUMENT being populated.  When I opened the Immediate Window and inspected Request.Form, this is what I found:

How is the Request.Form collection empty?  What’s the deal with THAT?

I started thinking about the ASP.NET pipeline, and it hit me:  FriendlyUrls.

There’s this interesting thing that happens when web forms attempt to post back to pages managed by FriendlyUrls and lack a filename.  This could be any of the following pages in your site:

  • /
  • /Products/
  • /Orders/

You get the idea.  These pages for some reason don’t handle postback properly.  With that in mind, I set forth to drop a quick and dirty change to enable this throughout the website.  Fortunately, I can make that change through a URL Rewrite operation.  I added the following event handler to my global.asax.cs file:

    void Application_BeginRequest(object sender, EventArgs e)
    {
      var app = (HttpApplication)sender;
      if (app.Context.Request.Url.LocalPath.EndsWith("/"))
      {
        app.Context.RewritePath(
                 string.Concat(app.Context.Request.Url.LocalPath, "default"));
      }
    }

With that, my pages started posting back properly… all was right in the world.

Please note:  you will have this problem with the default ASP.NET project with web forms when FriendlyUrls are enabled.

The Truth About HttpHandlers and WebApi

In 2012 when Microsoft introduced the ASP.Net WebAPI, I initially became confused about yet another way to generate and transmit content across a HttpRequest.  After spending some time thinking about WebAPI over the past week or two and writing a few blocks of sample code, I think I finally have some clarity around my confusion and these are those lessons I learned the hard way.

Old School API – SOAP and ASMX

When ASP.Net launched, the only framework to create and publish content that was available was WebForms.  Everybody used it, and it worked well.  If you wanted to create an interface for machine-to-machine communications you would create a SOAP service in an ASMX file.  You could (and still can) add web references to projects that reference these services.  The web reference gives you a first class object with a complete API in your project that you can interact with.

Over time, it became less compelling to build the SOAP services as they transmitted a significant amount of wrapper content around the actual payload you wanted to work with.  This extra content was messy, and other programming languages didn’t have the tooling support to manage them well.  Developers started looking for less complicated alternatives to communicate with connected clients.  It turns out that there was another option available that was overlooked by many: HttpHandlers.

HttpHandlers in ASP.Net

HttpHandlers are the backbone of ASP.Net.  An HttpHandler is any class that implements the IHttpHandler interface, handles an incoming request, and provides a response to webserver communications.  IHttpHandler is a trivial interface with the following signature:

 

    public class TestHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // TODO: Implement this method
            throw new NotImplementedException();
        }

        public bool IsReusable
        {
            get
            {
                // TODO: Implement this property getter
                throw new NotImplementedException();
            }
        }
    }

Listing 1 – Simple IHttpHandler interface implementation

The ProcessRequest method is where we can insert our code to handle all data being requested of the handler and all data to respond from the handler.  The IsReusable property is often misunderstood, but has a simple definition: Should an instance of this handler be re-used for other requests to the webserver?  If the return value is false, a new version of the handler class will be instantiated for each request to the server.  If IsReusable returns true, then the same instance will be used for all requests to the server.  A simple implementation that outputs some of my favorite sports teams in XML format might look like this:

public class MyHandler : IHttpHandler
    {


        public readonly static IEnumerable MyTeams = new List
        {
            new Team { City = "Philadelphia", Name = "Phillies" },
            new Team { City = "Boston", Name = "Red Sox" },
            new Team { City = "Cleveland", Name = "Browns" },
            new Team { City = "Houston", Name = "Astros" },
            new Team { City = "San Diego", Name = "Chargers" }
        };

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";

            context.Response.Write("");

            foreach (var t in MyData.MyTeams)
            {
                context.Response.Write("");
                context.Response.Write("");
                context.Response.Write(t.City);
                context.Response.Write("");
                context.Response.Write("");
                context.Response.Write(t.Name);
                context.Response.Write("");
                context.Response.Write("");
            }

            context.Response.Write("");

        }

        #endregion
    }

Listing 2 – A Sample XML Generating HttpHandler

Some developers get confused about the difference between a class that implements IHttpHandler and an ASHX file.  These are very similar things, but different with their own advantages.  An ASHX file is an IHttpHandler whose end-point is defined by the name of the ASHX file.  If you create foo.ashx you can trigger the ProcessRequest method by navigating to http://localhost/foo.ashx  Conversely, a class that implements IHttpHandler needs to be registered in web.config with a path and file-extension end-point to answer to.  The format of this registration lies within the system.webServer section of web.config:


    

        

    
  

Listing 3 – Web.Config entries for an HttpHandler

Further instructions on how to configure the HttpHandler is available on MSDN

Both of these types of HttpHandlers are easy to implement, and put you right on the metal.  You are handed and HttpContext and you can do anything you want to handle the incoming request and respond to it.  If you are working with some low-level operations such as inspecting HttpHeaders for responses, you may choose to go this route.

ASP.Net WebAPI in a nutshell

Scott Guthrie describes ASP.Net WebAPI as a technology that allows developers to build powerful web based APIs that have the following 9 core capabilities:

  • Modern HTTP Programming Model – Directly access the HTTP requests and responses using a strongly typed HTTP object model
  • Content Negotiation – Built in support for content negotiation, which allows the client and server to work together to determine to correct data format to return from an API
  • Query Composition – Easily supports OData URL conventions when you return a type of IQueryable<T> from a method
  • Model Binding and Validation – Supports the same model binding available in WebForms and MVC
  • Routes – You know ’em, you love ’em… they’re all over ASP.Net.  Why WOULDN’T you expect them in WebAPI?
  • Filters – You can apply similar filters to those that you create for MVC
  • Improved Testability – WebAPI uses two new objects called HttpRequestMessage and HttpResponseMessage to make unit testing significantly easier.  
  • IoC Support – The same service locator pattern implemented in ASP.Net MVC is available to inject dependencies into your API implementations
  • Flexible Hosting – Web APIs can be hosted within any type of ASP.Net application.  You can also host it within any process if you don’t want to engage IIS to host your API.

The quick and dirty summary of this list is that WebAPI functions, looks, and feels like developing with ASP.Net MVC.  There are a few simple differences between them, but once you learn them, its very easy to progress quickly.

The Super-Duper Happy Sample

To implement a simple service that outputs a collection of values when a GET is called with no arguments (eg: http://localhost/api/Values ) you need to add very little to get started.  First, add a WebAPI controller to your website by selecting the appropriate item in the Add Item dialog box:

The default implementation delivered looks like the following:

    public class ValuesController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }

Listing 4 – Default API Controller implementation

With this simple implementation you can navigate your browser to http://localhost/api/values and get the two values “value1” and “value2” returned in XML format.  If you programatically request that address and change your “accept” header to “text/json” you will receive JSON in the response stream.  You can PUT, POST, and DELETE content to this controller and the appropriate action methods will be triggered based on the HTTP action executed.  

The Truth

WebAPI is just another HttpHandler, one that has been wrapped around all sorts of helpful content management and negotiation technologies as Scott Guthrie suggested.  You certainly could cut out all of those other technologies and benefits and code directly “on the metal” with an HttpHandler, and that was the only choice you had until 2012 and ASP.Net 4.  In today’s web community, its best to use RESTful methods and use a standard format like XML or JSON to transfer data.  HttpHandlers had their place, but going forward, I’m going to use WebAPI whenever I need to transmit data over HTTP to browsers or any other connected client.

Adding SignalR to an ASP.Net WebForms Project

In this post, I want to demonstrate how you can add real-time interactivity to a website that is written with ASP.Net WebForms.  I’m going to show you how easily and quickly you can have SignalR update the content of a standard ListView webcontrol to show a ‘live’ log of events on your webserver.

UPDATE Jan 28, 2013: I have uploaded the source to this post to my GitHub account.  Go get some sample code!

Project Setup

For this sample, I’m going to start up a standard ASP.Net WebForms application with .Net 4.5  Once the project is created, I’m going to clear out the default content on the home page and insert my ListView control as shown in Code Listing 1:

<asp:content runat="server" id="BodyContent" contentplaceholderid="MainContent">

    
    <h3>Log Items</h3>
    <asp:listview id="logListView" runat="server" itemplaceholderid="itemPlaceHolder" clientidmode="Static" enableviewstate="false">
        <layouttemplate>
            <ul id="logUl">
                <li runat="server" id="itemPlaceHolder"></li>
            </ul>
        </layouttemplate>
        <itemtemplate>
            <li><span class="logItem"><%#Container.DataItem.ToString() %></span></li>
        </itemtemplate>
    </asp:listview>

</asp:content>

Code Listing 1 – Initial layout of the ListView

With this block configured, I can write a small snippet in the code-behind default.aspx.cs file to load some log information from some other datastore.  For this example, I’m just going to bind to a List of strings to demonstrate the mix of server rendered content and dynamically added content:

        protected void Page_Load(object sender, EventArgs e)
        {

            var myLog = new List();
            myLog.Add(string.Format("{0} - Logging Started", DateTime.UtcNow));

            logListView.DataSource = myLog;
            logListView.DataBind();

        }

Code Listing 2 – Code behind to load some rendered data

I should now be able to start my application and see a simple pair of lines added to the default page that appear something like this:

Figure 1 – Static Log Content

Adding SignalR to the mix

At this point, we need to add SignalR to our project through the NuGet package manager.  I prefer to use the ‘Manage NuGet Packages’ dialog window to add these packages, so I add the packages for SignalR by searching for and adding the “Microsoft ASP.Net SignalR JS” package and the “Microsoft ASP.Net SignalR SystemWeb” packages.  At the time of this article’s writing, these packages are available in the ‘Pre-Release’ state only.

When you craft code for SignalR, you need to write client-side and server-side code.  The server-side code in this sample will be housed in a SignalR Hub.  

A hub is a structure that facilitates simple communications to a collection of client systems that are listening for commands to execute.  

In this project, we will create a LogHub class in c-sharp that will allow log messages to be communicated to all listening client browsers.  To simulate the repeated creation of log messages, I will use a timer to periodically transmit messages.  The code for the LogHub.cs file appears below:

    public class LogHub : Hub
    {

        public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();

        static LogHub()
        {
            _Timer.Interval = 2000;
            _Timer.Elapsed += TimerElapsed;
            _Timer.Start();
        }

        static void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            var hub = GlobalHost.ConnectionManager.GetHubContext();
            hub.Clients.All.logMessage(string.Format("{0} - Still running", DateTime.UtcNow));
        }

    }

Code Listing 3 – LogHub source code

This hub contains 1 static event handler to listen for the timer’s elapsed event.  The first statement of this method gets a reference to the singleton LogHub that is running in our web server.  The next statement issues a message to all clients using the “hub.Clients.All” structure.  This is an interesting piece of code, as the “All” property of “hub.Clients” is a dynamic object.  The “All” property is a proxy for the objects and their methods that are available to be called over the SignalR pipeline.  

The object that is called over the SignalR pipeline by “All” from Code Listing 3, will be constructed in JavaScript and exposed to our hub in the following script block:

<script src="Scripts/jquery.signalR-1.0.0-rc1.min.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
    
    $(function() {

        var logger = $.connection.logHub;

        logger.client.logMessage = function(msg) {

            $("#logUl").append("<li><span class="logItem">" + msg + "</span></li>");

        };

        $.connection.hub.start();

    });

</script>

Code Listing 4 – JavaScript to log messages

There are a few pre-requisites here that I need to discuss first.  In my sample project, there is a reference to the jQuery library in my layout page, if you do not have that reference available, I recommend you add it to simplify the volume of JavaScript code you will be writing.  Next, I have added script references to the “jquery.signalR” library to give us access to the SignalR functionality.  The second reference is to a “magic URL” at /signalr/hubs.  This is a virtual location that exposes the methods that the hub classes have in public scope.  These methods can be called from the browser, through the plumbing established in this file.

The JavaScript in this listing is a normal jQuery enclosure, to ensure its contents do not get executed until after jQuery is loaded.  The first line gets a reference to the LogHub object that we created in listing 3.  We then connect a function to our client’s “logMessage” property.  This is the same function that is referenced in listing 3’s dynamic “All” object.  Thankfully, since we marked our ListView object with a static ClientIDMode and disabled ViewState, there are no hoops for us to go through to get a reference to the DOM objects that were created.  In this case, we’re simply going to append a list item (LI) to the unordered list (UL) with the message submitted to the function.  The last line of this enclosure is very important.  The start() method must always be called in order for SignalR to know to start listening for invocations from the server.

Before we can run our sample, we need to add one last piece of plumbing.  We need to tell the server to expose that magic URL at “/signalr/hubs”.  This is accomplished by adding a line to the Application_Start event handler in global.asax.cs:

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterOpenAuth();

    RouteTable.Routes.MapHubs("~/signalr");

}

Code Listing 5 – Mapping the Hubs Route

Once this line is added, we can start our application.  You should see a result screen similar to the following:

Figure 2 – Static and Live Log Content

Summary

With a few simple settings on our WebForms project and the controls I wanted to modify for this sample, I was able to dramatically simplify the SignalR interactions with WebForms.  In this case, I didn’t run into any issues with the parts of WebForms that developers try to avoid like PostBack, Page Lifecycle, ViewState, and ClientID rendering.  Next time, we’ll confront those issues head on as I’ll show you how to interact between SignalR and controls that post back to the server.