Thursday, May 31, 2012

One library every MVC project should not be without


One tool that I’ve found particularly useful in an MVC project is AutoMapper.

“A convention-based object-object mapper. 100% organic and gluten-free. Takes out all of the fuss of mapping one object to another.” AutoMapper

In my experience, in almost every get action method, a view model representation of the domain object needs to be constructed to be displayed in the view. With AutoMapper this is done automatically for you.

Thursday, May 24, 2012

Jazz up your web with JQuery

Introduction:

JQuery focuses on retrieving elements from HTML pages and performing operations upon them. Very similarly to CSS, the power of selectors that describe groups of elements by their type, attributes or placement within a document, JQuery is able to use this knowledge and degree of power to vastly simplify Javascript.

JQuery places a high priority on ensuring code works consistently across all major browsers. JQuery has a simple but powerful built-in method for extending its functionality via plugins.

Microsoft’s HomeOS

Microsoft is looking to unify electrical appliances within the home and establish itself in the upcoming “smart home” market with the development of HomeOS. Essentially a lightweight “smart home” operating system that aims to make it easy for users to manage their home networks and ease the creation of applications by third party developers, HomeOS is designed to provide a central hub through which various household devices can be controlled.

Rock out with Razor


The first glimpse we had at the Razor view engine was seen in the release of MVC 3 and the first thing anyone will notice is how easy programming becomes on a simple HTML page or rather CSHTML which is the Razor view extension.

Wednesday, May 23, 2012

JavaScript unit testing with QUnit

All developers will agree that web development goes hand in hand with client side coding to be able to provide a rich user interface to their users which is prettier, more responsive and impressive. Having that said it should be equally important that we not only unit test our server side code but also client side as well. 

ITIL: Monitoring and organising available Services in a Working environment


ITIL consists of 5 books that make up the lifecycle management.
The 5 books go hand-in-hand with each other and they support each other through the life cycle.
The ITIL lifecycle is a recursive circle for each process and even for each system until the system has been retired.

KnockedUp: Customizing the use of KnockoutJs

I blogged previously about a nifty little library called KnockoutJs.

To bring you up to speed, here is a typical example on the original usage of KnockoutJs:


Note that you have to specify all your bindings for an element in the data-bind attribute.

This got me thinking...

Doing all these bindings in one attribute may become untidy and unreadable. On the HTML, I wanted a way to explicitly define my bindings as attributes on a specific element.



...then KnockedUp was born

I created a library (dependent on JQuery & KnockoutJs) that gives you the same result as KnockoutJs and called it KnockedUp :) .

KnockedUp allows you to specify your data-bindings explicitly as normal attributes and not as in line values of the "data-bind" attribute. What this library does, is converting the KnockedUp syntax to proper KnockoutJs syntax.

These attribute-based bindings must start with an identifier, in my case "ko-". You can then have your HTML as:

Choose a ticket class:
<select ko-options="tickets"
        ko-optionsText="'name'"
        ko-optionsCaption="'Choose...'"
        ko-value="chosenTicket"></select>
<button ko-enable="chosenTicket"
        ko-click="resetTicket">Clear</button>

<p ko-with="chosenTicket">
You have chosen
<b ko-text = "name"></b>
($ <span ko-text = "price"></span>)
</p>

KnockedUp will scan the body for elements that contain attributes starting with "ko-" and add these attributes as values to the applicable data-bind attribute of the applicable element, then KnockoutJs will kick in and perform its magic.

Usage

Simply add the reference to KnockedUp and just before calling the "ko.applyBindings(...)" function of KnockoutJs, just call KnockedUp's function - "ku.applyMappings()":

ku.applyMappings();

ko.applyBindings(new TicketsViewModel());


You can download the plug-in here - It's only about 800 bytes!



Disclaimer: Please note that this is currently only in beta phase as its only a concept for now.

Tweet me @FanieReynders for any questions!

Cheers

Tuesday, May 22, 2012

(RX) Reactive Extensions A Different Flavour

Overview


The Reactive Extensions (Rx) Library is a set of extensions for the IObservable<T> and IObserver<T> interfaces that were added in .NET 4.0. The extensions allow for the use of LINQ to query IObservable<T> collections as if they were IEnumerable collections. In addition Rx also greatly simplifies the orchestration and composition of asynchronous functions and events.


With the Reactive Framework, the paradigm of Enumeration and pulling for more results is flipped upside down. Instead of pulling for the next record, the Reactive Framework “Reacts” to events as they are pushed through the event pipeline. Instead of calling MoveNext as we do with IEnumerable, we react to OnNext events.

With Rx, you can easily compose multiple async operations together.

The IObservable and IObserver interfaces are involved and rather than enumerate over existing sequences, you write queries against sequences of future events.


When would you use the Reactive Framework?

  • Essentially, you can use it anywhere you are responding to events or work with continuous streams
  • Handling UI Events (Mouse clicks, Touch gestures)
  • Working with Asynchronous Web requests (Web services) 
  • Analysing sensor data from Manufacturing, Health care, etc. devices in real time
  • Processing data from continuous data streams (Log files, Stock feeds, etc.)

Basic Example


Firstly, fire up Visual Studio 2010 and create a new project, in my case I created a windows form application.
Use your trusted package manager "Nuget" and install the RXX nuget package.

 

Below I created a class called FileSystemObservable.

In this class I use a FileSystemWatcher that is used to listens to the file system change notifications and raises events when a directory, or file in a directory, changes.

I also have a CreatedFiles property this is an observable of Type FileSystemEventArgs

In the constructor I create a new instance of the FileSystemWatcher, thereafter with a bit of RX Magic I set the CreatedFiles property to the Event that I want to monitor, which happens to be when a file is created.
public class FileSystemObservable
    {
        private readonly FileSystemWatcher _fileSystemWatcher;

        public IObservable<FileSystemEventArgs> CreatedFiles { get; private set; }

        public FileSystemObservable(string directory,string filter, bool includeSubdirectories)
        {
            _fileSystemWatcher = new FileSystemWatcher(directory, filter)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = includeSubdirectories,
            };

            CreatedFiles = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>
              (h => h.Invoke,
               h => _fileSystemWatcher.Created += h,
               h => _fileSystemWatcher.Created -= h)
              .Select(x => x.EventArgs);
        }
    }



  

Below is how you would use the FileSystemObservable. Firstly as the code reads I create a new instance of the FileSystemObservable specifying that I want to monitor the entire C drive and sub directories for all file and directory changes.

I specify that I want to monitor only events when files are created, thereafter using RX I subscribe to the event. When the event gets triggered a message box will be shown with the file details and the fact that it was created.




var createdfilewatcher = new FileSystemObservable(@"c:\", "*.*", true).CreatedFiles
            .Subscribe(x =>
            {
                MessageBox.Show(x.Name + " Created");
            });

 

More info

 

For more info I would recommend having a look at http://rxx.codeplex.com/ and http://channel9.msdn.com/Tags/reactive+extensions

Sunday, May 20, 2012

SignalR: Build real-time, multi-user interactive web apps

Some History

A while back I was involved in developing an online-bidding app. This may not sound too exciting nor complicated, but because this kind of application was web-based, it introduced a whole new set of challenges.

One of the core requirements of this app was to be critically up-to-date with real-time results. As a user bids on something, the action needs to be broadcast to the rest of the players bidding. The main challenge was achieving this on the web.

The way web applications work, is the client sends a request to the server for certain information then the server sends back the response which contains the information. In our case where the client needed to be aware of certain server-side changes, the most obvious way was to poll the server periodically.

"Polling is a common example of hammering a screw. Trying to make a chat program? Poll every 5 seconds. Got a really long running transaction? Throw up an animated GIF and poll until eternity, my friend!" - Scott Hanselman

Another way to achieve this is a concept called Long Polling. Basically, open a connection and keep it open forcing the client to wait, pretending it's taking a long time to return. If you have enough control on your server-side programming model, this can allow you to return data as you like over this "open connection." If the connection breaks, it's transparently re-opened and the break is hidden from both sides. In the future things like WebSockets will be another way to solve this problem when it's baked.

Then SignalR came along

Doing this kind of persistent connection in an app (like our bidding site) hasn't been easy in ASP.NET because there hasn't been a decent abstraction for this on the server or client library to talk to it.

SignalR is an asynchronous signaling library to build real-time interactive multi-user web applications.

Easy elegant implementation

I'm not going into too much detail on this, the only thing I want to show is how easy we implement something as simple as a basic chat app.

In your web-app project - hopefully its MVC :) - install the SignalR NuGet package. You can also do this using the Package Manager Console:

Setup

Install-Package SignalR

Server

Create a class that derives from Hub, then add a function "Send" that expects a message as string. We will then use the Clients property and call a dynamic function "addMessage":
public class Chat : Hub 
  {
      public void Send(string message) 
      {
          
          Clients.addMessage(message);
      }
  }

Client

Add references to JQuery, SignalR & the virtual path "/signalr/hubs"
<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.0.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
The HTML:
<input type="text" id="msg" />
  <input type="button" id="broadcast" value="broadcast" />

  <ul id="messages">
  </ul>
Next, we instantiate our server class as a proxy on the client-side:
<script type="text/javascript">
  $(function () {
      var chat = $.connection.chat;




...



 });

</script>


      
Keep in mind that the connection.chat directly translates to our Chat class (which derives from Hub). Next, we declare a function on the chat hub so the server can invoke it:
chat.addMessage = function(message) {
          $('#messages').append('<li>' + message + '</li>');
      };
When we click the 'broadcast' button, we want to call the server-side "Send" function:
$("#broadcast").click(function () {
          chat.send($('#msg').val());
      });
And last (but not least) we start the connection:
$.connection.hub.start();
This is not a lot of code, but yet again you probably can make it shorter and sexier using KnockoutJs (I blogged about it recently). SignalR will work really well with KnockoutJs.

Demo

There is a small chat application running on Azure at http://jabbr.net that was built with this technology. Feel free to check it out and give it a try.

I hope someone finds this useful.

Thanks! Until next time...







Monday, May 14, 2012

MVVM for the Web using Knockout.js

Ever since the explosion of web-oriented apps, the need for doing complex things simpler becomes more obvious. Creating richer & more sophisticated UI's usually involves using JavaScript API's like JQuery.

What?

Knockout.js is an open-source JavaScript library (yep, not Microsoft - licensed under the MIT) that helps you create rich, responsive display & editor user interfaces with a clean underlying data model.

Any time you have sections of your UI that update automatically, Knockout.js can help you implement it in a simpler, more maintainable fashion.

Why?

The problem with designing for the web is that rich user interactivity is fairly hard to do. Even when using a JavaScript library (like JQuery) it can become quite cumbersome. Before you know it, you have a mess of inter-related event handlers that all pretty much do the same thing.

Now, with Knockout, we can say hello to more structured code based on true object orientation & declarative bindings. This means that Knockout brings the MVVM pattern comes to the web.

Like any other good JavaScript library, Knockout also supports a wide variety of browsers like IE 6+, FireFox 2+, Chrome, Safari & Opera.

Knockout can be added on top of your existing web application without requiring major architectural changes.

Developers familiar with Ruby on Rails, ASP.NET MVC, or other MV* technologies may see MVVM as a real-time form of MVC with declarative syntax. In another sense, you can think of KO as a general way to make UIs for editing JSON data… whatever works for you :)

How?

The best way of explaining Knockout.js is to actually show you. In order to keep this post short & sweet and on to the point - here's a link to the interactive tutorials found on the website - knockoutjs.com

Also - I've uploaded an simple example based on my demo on SkyDrive here

Enjoy experimenting & happy knocking!

@FanieReynders