Tag Archives: source code

Two subtle but powerful client-side UI tricks

I thought I would two little tricks that are recent favorites of mine.

I’ve been doing a lot of client-side development with Backbone.js, Twitter Bootstrap, and LESS. Together they are powerful tools for creating a lot of beautiful client-side UI with complex interactions.

The two tricks I want to share are a CSS3 fade-in, and Trello-inspired drag-n-drop LESS mix-in.

Read more »

jQuery.postJSON() method for ASP.NET MVC

Part of the reason I blog is that it serves as a healthy reminder for me of the best ways I’ve found to do things. The Internet is full of information that’s just plain wrong, or only wrong in certain scenarios that don’t always match mine.

So when I have to grapple with the exact same stupid problem for the second time, it’s obviously time to record it, if only for the sanity of Future Me.

Today’s example is posting JSON to an ASP.NET MVC action method. There are a bunch of examples all over the Internet that will tell you to do this:

// THIS IS WRONG!
// Well.....at least for MVC.
$.post('/some/url', data, function(response) {
    // Do something with the request
}, 'json');

This is all well and good and does cause jQuery to submit data encoded as JSON instead of URL-encoded, the problem comes in on the MVC side. This request results in this offending header:

Content-Type: json; charset=UTF-8

Um, that’s not right! “json” is not a valid MIME type! Because of this, even though the payload is JSON, MVC will not deserialize it properly and so any of your action method parameters will be null. Even worse, if you have a non-nullable parameter (an int, for example) then you will get an exception from the model binder.

So this snippet creates the simple postJSON method that jQuery on its own is missing, nicely wrapped within a closure so that it can operate in jQuery’s noConflict mode:

(function ($) {

	$.postJSON = function (url, data) {

		var o = {
			url: url,
			type: "POST",
			dataType: "json",
			contentType: 'application/json; charset=utf-8'
		};

		if (data !== undefined) {
			o.data = JSON.stringify(data);
		}

		return $.ajax(o);
	};

} (jQuery));

This will correctly set the Content-Type header so that MVC can understand it. The function returns a jqXHR object that implements the Promise interface so that you can chain your event handlers on to the end like this:

$.postJSON('/post/url', {param1: "hello", param2: "world"})

	.complete(function () {
		// Optional - fires when the operation completes, regardless of status
	})
	
	.success(function () {
		// Optional - fires when operation completes successfully
	})
	
	.error(function () {
		// Optional - fires when operation completes with error
	});

Enjoy, Future Me!

NServiceBus at Twin Cities Code Camp 13

Today I had a great time presenting Enterprise Service Bus Development with NServiceBus at the Fall 2012 Twin Cities Code Camp. I wasn’t sure before presenting if we would have enough time to get into sagas, and as it turned out, we ran out of time right in the middle!

So as promised, I finished the saga code and pushed it all to GitHub. Here is the link to my Twin Cities Code Camp 13 NServiceBus Example Code. Please feel free to clone it and explore!

Read more »

Perfectionist Routing in ASP.NET MVC

I’m not one to accept /{ControllerName}/{ActionName} for my routes. Like a few members of the Stack Exchange team, I’m far too anal retentive about my routes to let Microsoft just handle it for me.

To this end, I use the excellent Attribute Routing project which is also available on NuGet: just type Install-Package AttributeRouting into the Package Manager and you’re ready to decorate your methods with route attributes like this:

[GET("some-action/{id}")]
public ActionResult SomeActionMethod(int id)
{
	return View();
}

 

A lot more than this is possible; for more details check out the AttributeRouting project wiki. Another nice feature during development time is the additional route “~/routes.axd” which shows you, in order, all the routes registered in your application (not just those registered by attributes) and gives you a lot of information that’s very helpful when debugging a routing problem.

All the benefits of attribute based routing aside, the problem quickly becomes that pesky default route. If you accidentally misspell a controller or action name in an ActionLink or other helper, you will get a URL that uses that default path due to this entry in the routes configuration in the Global.asax.cs:

routes.MapRoute(
	"Default", // Route name
	"{controller}/{action}/{id}", // URL with parameters
	new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

 

I don’t want my ActionLinks to use this default route. If it does, they’re wrong! I want to find out through an exception that I can easily detect during development, not by silently outputting a route that doesn’t work.

Read more »

Loading external resources without killing ASP.NET

If you run an ASP.NET website with any non-trivial amount of traffic, the last thing you want to do is try to load an external resource with a web request. Even if you cache it, you’ve taken on that external source as a dependency to your system, which means that your website is only as reliable as the external source you depend on.

The primary strategy I’ve seen to cope with this is to request the data from the remote service on the first request from the web tier, cache it locally, and then have a background process periodically refresh that cache so that subsequent requests can use locally cached data.

Even with this background-updated cache, eventually the external resource will suffer some sort of issue. The data in the cache grows old and is invalidated, and then the web tier starts requesting the data again, except now, 100 different requests try to open 100 different connections to the remote service to get the exact same data, because either they all fail or none of them can complete quickly enough to store the cache item for the other threads to use. The Thread Pool fills up, and ASP.NET hangs its head and gives up.

The Solution

Let’s assume that we are talking about a current weather tease that is a small part of a very large page, and that all our current weather information for the end-user’s zip code comes to us from an external provider.

So how do we avoid this mess? We can do it quite handily with a little NServiceBus and jQuery.

Read more »

Robust 3rd Party Integrations with NServiceBus

A common question about NServiceBus is how to use it to integrate with an external partner. The requirements usually go something like this:

  • The third party will contact us via a web service, passing us a transaction identifier and a collection of fields.
  • If we successfully receive the message in the web service, we respond with a HTTP 200 OK status code.  If they do not receive the acknowledgement, they will assume a failure and attempt to retry the web service later.
  • Once we receive the message from the third party, we need to distribute (think publish) the contents of the message to more than one internal process, each of which are completely independent of each other.
  • We need to logically receive each message once and only once. In other words, it would be a “Very Bad Thing” for one of the internal subscribing processes to receive the same notification more than once.

This was most recently asked in this StackOverflow question, where it became difficult to explain more within the 600 character comment limit. The best explanation is example code, so here it is.

Read more »

Flexible Reporting with LINQ and C# 4.0 dynamic keyword

It’s commonly very difficult to question business people about reporting requirements.  It’s not really their fault either – they just can’t know exactly what they want until they’re trying to answer a question and can’t easily do it with the reports you’ve given them.

This is why it’s good to make reports as flexible and updateable as possible, but with as little developer required to update the reports as possible.

If you’re operating in an environment where all database access must be via stored procedures, this is a really big problem.  It’s really unlikely that the changes requested by business can be implemented with the same stored procedure you naïvely created for your first attempt.  I’ve seen scenarios where a database has stored procedures with the suffixes GetReport, GetReport2, GetReport3, GetReport4, etc.  Yuck.

Even if you’re using Entity Framework, LINQ to SQL, or some other data layer framework that enables more free-form access to the database, you can’t always ensure that all report queries will result in good execution costs and actually be performant.

This is why it can sometimes be a good idea to perform a very basic database query (via stored procedure if necessary) to get a base set of data, and then perform more conditional operations on it in memory with LINQ.  It’s a pain to do a “Name Contains” filter in a stored procedure (especially if there are a dozen other options) but with LINQ it’s no big deal.

IEnumerable<DataItem> data = GetBaseData();

if (!String.IsNullOrEmpty(nameFilter))
	data = data.Where(d => d.Name.IndexOf(nameFilter, StringComparison.OrdinalIgnoreCase) >= 0);

This is really great for simple filters, but gets difficult when we want to do more complex grouping and aggregating functions, such as grouping by Hourly/Daily/Weekly/Monthly and/or by other data points.

The remainder of this article will show how this can be done with static code, and then how we can drastically increase the maintainability of this same code by employing the dynamic keyword introduced in C# 4.0.

Read more »

Rolling Counter

Sometimes I need a rolling counter, especially in diagnostics-related scenarios. How many requests have occurred in the last hour? It’s not okay for a counter object to drop out of cache every hour, because the value will be meaningless if I happen to observe it at (Cache Drop + 3 minutes).

A real rolling counter is needed in these situations. The counter must increment, and then at some point those hits must drop off.

But especially in these situations, low impact is the key. A Queue where each item contains a timestamp is too unruly. Too many objects are created and too much cleanup is required. Less is more.

Read more »

Injecting NServiceBus into ASP.NET MVC 3

In the past, integrating NServiceBus into a web application typically meant adding the fluent configuration block to the Global.asax file and then keeping a static reference to the IBus property, because ASP.NET has not been very friendly to dependency injection.

In ASP.NET MVC 3, Microsoft has changed that by adding some nice abstractions around dependency resolution.  With a little effort, this allows us to inject NServiceBus (and its dependency injection container) into the dependency resolution pipeline.

In this example, I will show how to add NServiceBus to an MVC 3 web application so that common NServiceBus types (IBus chief among them) are injected into your controller classes.

Note: Karl Nilsson has written a post extending this one, showing how to inject NServiceBus into an ASP.NET MVC4 Web API solution, which requires just a few minor adjustments.

Read more »

Apple iOS Push Notifications with NServiceBus

I’m no big fan of Apple’s Push Notifications API, but the fact is that iOS applications are no passing fad.  As developers providing server-side resources to mobile applications, our job is to do so as efficiently as possible.

For .NET developers able to commit financial resources, third party solutions such as Urban Airship can be the answer.  For developers wishing to control their own destiny, the open-source apns-sharp provides Apple push notifications and feedback services in a C# library.

Considering the ridiculous complexity of the Apple Push Notification format, it would behoove any developer to use apns-sharp instead of trying to re-invent the wheel.  NServiceBus together with apns-sharp would offer the reliability and scalability needed to successfully send push notifications for a high-capacity enterprise system.

Unfortunately, until recently apns-sharp and NServiceBus didn’t work and play well together.  I contributed to the apns-sharp to address these shortcomings.  In this article, I will describe how to use these modifications to apns-sharp to send push notifications with NServiceBus.

Read more »