WinRT app @ Labdays

Installed win8 on my work laptop not too long ago so I decided to create my first winrt app during lab days at work. Due to lack of imagination I created a simple dashboard app for our product SAFE (really ugly page on saabgroup btw).

Started of by looking at some sessions on channel9 and googled design patterns, frameworks and ended up with the following:

I ended up writing a custom navigation service that I bootstrapped on application startup to make the IOC container from MVVM Light play nicely together with the AlternativeFrame from WinRT Xaml Toolkit. If you pay attention to the navigation between pages you can notice the nice dissolve transition which is done in AppShell.xaml in only 4 lines of markup.
Once I got the basic architecture in place I noticed that the panorama control from windows phone was missing for winrt. One google search later I found a blog post that addressed this issue so I ended up copying some code since I didn’t want to install the entire nuget package win8nl. What it basically does is to add a panorama behvior to the FlipView control. The sad thing though is that you can’t flick the screen if you don’t have a touch screen, which is extremely frustrating!
As for what goes for component arts data viz library I really think it’s not worth to pay for (trial is free), in the short time I played around with it I stumbled upon several bugs. An ugly work around for the PieChart control can be seen in the code behind file MainPage.xaml.cs. When data binding to an observable collection the control goes bananas as items are added to the collection, I needed to reset the DataSource for each added item for it to work properly.
All and all I’m pretty satisfied with the choice to use MVVM Light together with WinRT Xaml toolkit and the custom navigation service, I will definitely reuse that part for other projects.
Anyways the result can be seen in the vid below, you can get the source code here, if you’re interested in how I hooked up the components and architecture. You will probably not be able to run the application since it requires our back-end and I didn’t spend too much time on exception handling.

 

Merry x-mas everybody and a happy new year, I’m off for two whole weeks!

 

Performance measurement ASP.NET MVC vs. WebAPI

I’ve been playing around with WebAPI for a couple of days now and I’m quite pleased with most of it so far. At work we have a stripped down a MVC3 site (threw away the M and the V) for ur public REST interface. Except for the ugly ActionResults in the controllers we are satisfied with it so far. I’ve read some articles on how the web api pipeline is supposed to be more optimized so I thought I’d put it up for a test before trying to sell in the platform upgrade to our product owners, also it would result in our first major version bump so we need to be sure that we can benefit from it and not just do it for the sake of fun (for me :-)).

The server side is a simple controller with 4 actions, 1 get, 1 post, 1 put and 1 delete method that only returns a status code, no I/O or business logic we just want to compare the pipelines. The test will run a five parallel threads executing 100 000 requests all together. The MVC site is hosted on a IIS 8 Express server and the WebAPI is both self hosted and hosted on a IIS8 Express server. The test was performed on my developer laptop running on Intel Core i7 CPU @ 2.67 (dual core with two threads on each CPU), 8GB RAM and 64 bit Win7 operating system.

  Avg. request time (ms) Total run time (s) Requests per second
MVC (IIS) 0.42 41.83 2391
WebAPI (IIS) 0.35 35.06 2852
WebAPI (Self Hosted) 0.12 11.67 8567

 

The results don’t say much since the average request time is very fast in all three cases but a relative comparison shows that MVC vs. WebAPI on IIS is ~20% and the self hosted console application is a whole ~260% faster. Although this pure pipeline time will be negligible when adding business logic with I/O operations or even a single WCF call (~50ms perhaps?).

There’s a whole lot more I could write about asp.net webapi but I’ll save it for future blog posts and leave you with the performance measure for now. 

The code for the test is available for download here, please don’t contact me about translating it to VB ;-)

Peace!

Dell 5530 HSPA Driver for Windows 7 on E6410

So after a couple of hours of struggling I finally managed to get it working!

What I basically needed to do was to remove the machine check for the Dell 5530 Windows 7 driver installer for E6400 http://downloads.dell.com/comm/R251153.exe.

I’ve uploaded the modified msi here, hope it saves somebody a headache.

EDIT:

Noticed that my modified msi will make the OS crasch when recovering from sleep or hibernation. A better solution is to uninstall the old driver, download the enterprise client cab and update the drivers for the unknown devices from the device manager. Just browse the top level of the unpacked cab (E6410-win7-A09-9TW7N\E6410\x64) and check the “Include subfolders” checkbox. After a reboot new unknown devices appeared, just did the same thing and violá it worked, works on my win8 machine as well!

Peace!

Building real-time web app with SignalR

We just recently had lab days at work which for me basically means that I can play around with some new tech to keep myself up to date. Anywho, one of the things I tried out was SignalR which is a .net library for building real-time, multi-user interactive web applications.

To goal was to build a simple chat, textbook example, shouldn’t be any fuzz, right? I started out with an asp.net mvc 3 empty project and installed the EntityFramework, SignalR and knockoutjs nuget packages. Lately I’ve been using knockoutjs pretty much in all my web projects, I’m a big fan!

PM> Install-Package EntityFramework
PM> Install-Package knockoutjs
PM> Install-Package SignalR

I’m not a big fan of entity framework code first but it was enough for my throw-it-away-when-you’re-done requirements. The basic idea is to just create POCOs and decorate the properties with attributes and the db will be generated for you.

The only entity I want to store is a chat message:

public class Message
{
    [Key]
    public int MessageId { get; set; }

    [Required, MaxLength(200)]
    public string Text { get; set; }
}

and the actual database context as

public class DatabaseContext : DbContext
{
    public DbSet<Message> Messages { get; set; }
}

keeping it really simple, no relations at all. And let’s not forget to register the initializer in Application_Start.

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DatabaseContext>());

Now to the fun part, SignalR. We simply create a Hub that runs on the server that will be able to invoke methods on our clients.

public class Messages : Hub
{
    public void GetAll() { ... }
    public bool Add(Message newMessage) { ... Clients.messageAdded(message); ... }
}

and on our page we only need to 1) create a proxy on the fly, 2) declare a function on the hub so the server can invoke it, 3) call on the add method on the server.

$(function () {
    // proxy created
    this.hub = $.connection.messages;

    // method invoked by the server when a message is added
    this.hub.messageAdded = function (m) { ... };

    // how we send a message to the server
    this.sendMessage = function () { ... this.hub.add(m); ... };
});

The server-side code is telling all the clients to call the messageAdded() JavaScript function. Mind blowing? We are actually calling the client back from the server by sending the name of the client method to call from the server via our connection. SignalR handles all the connection stuff on both client and server and makes sure the channel stays open and alive.

Screenshot of desktop browser and windows phone emulator browser:

signalr_wp_browser

 

Download the code (793,9KB) for full example.

 

ASP.NET MVC 4 Mobile Features

I read about mvc 4 and decided to try out some of the new cool mobile features, so I went ahead and installed it, it installs side-by-side with mvc 3 so that’s nice. It comes with a new mobile application project template that uses jquery mobile which looks pretty good but since I want to build a web application for both desktop and mobile devices I’m going to start off from the internet application project template.

The default template uses CSS media queries which is an extension to CSS for media types, it allows you to override the default css rules for different agents. CSS rules defined inside

@media only screen and (max-width: 850px) {

will be applied if the browser window is 850 pixels wide or less. That combined with the viewport meta tag

<meta name="viewport" content="width=device-width">

makes the default project template render pretty nice in both desktop and mobile browsers as seen below.

aspnetmvc4_mobile_responsive

So what should I do if that isn’t enough? I want to completely customize the views for mobile agents but still use the same controllers. This is easily done! MVC4 introduces a mechanism to override views, layouts and partial views by naming conventions. For instance to get a mobile specific index page I simply add Index.Mobile.cshtml, same goes for the layout i.e. Shared\_Layout.Mobile.cshtml.

Having that said, let’s customize the mobile views, for that I’d like to use the jQuery mobile library that works on all the major mobile browsers. Installing the jQuery.Mobile.MVC NuGet package will get us on our way.

PM> Install-Package jQuery.Mobile.MVC

The package will setup the scripts and reference them and create a _Layout.Mobile.cshtml which links in the jquery mobile css, I needed to manually change the referenced jQuery version in _Layout.cshtml from 1.6.3 (default) to 1.6.4. A neat detail with this package is that a view switcher controller is added which enables us to easily switch between the desktop and mobile version.

I created the corresponding mobile views in /Home and threw in the following code into _Layout.Mobile.cshtml

<ul data-role="listview"&gt;
	<li data-role="list-divider">Navigation</li>
	<li>@Html.ActionLink("Home", "Index", "Home")</li>
	<li>@Html.ActionLink("About", "About", "Home")</li>
	<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

and simple as that I now had a mobile customized site.

aspnetmvc4_mobile_custom_mobile

Doesn’t get much easier than that!

Code available here (4,4MB), haven’t done much though! ;-)

/A

 

What about WCF 4.5 and the async/await pattern?

From what I’ve heard it should be pretty smooth to produce asynchronous server/client code with .net 4.5, so let’s try it out! Defining async methods on the service contract is now a lot cleaner :

[ServiceContract]
public interface IPeopleService
{
	[OperationContract]
	Task<IList<Person>> GetPeople();
}

instead of the wcf 4.0 way which would look something like this :

[ServiceContract]
public interface IPeopleService
{
	[OperationContract(AsyncPattern=true)]
	IAsyncResult BeginGetPeople(AsyncCallback cb, object state);

	[OperationContract]
	IList<Person> GetPeople();

	[OperationContract]
	IList<Person> EndGetPeople(IAsyncResult ar);
}

the server side implementation of the operation when returning a task is straightforward :

public async Task<IList<Person>> GetPeople()
{
	Task t1 = Task.Delay(500);
	Task t2 = Task.Delay(500);
	await Task.WhenAll(t1, t2);

	return await Task.Factory.StartNew(() => people);
}

If you don’t want to await something in the method you can skip the async keyword and still return a Task as shown below, async on a method simply tells the compiler that “I’m going to await something in this method”.

public Task<IList<Person>> GetPeople()
{
	return Task.FromResult(people);
}

Anyways it’s really nice to skip the non-implemented begin/end methods on the server which was simply boiler plating in .net 4.0. For the sake of simplicity the service will be hosted in a console application and for consuming the service I’ve implemented a simple proxy that inherits ClientBase<TChannel> and implements the contract. See the code if this confuses you (which probably means that you’re a noob ;-)). The client code when working with tasks is clean and straightforward as well :

var serviceProxy = new PeopleServiceProxy("PeopleServiceEndpoint");

Task<IList<Person>> people = serviceProxy.GetPeople();
people.ContinueWith(
	x =>
		{
			foreach (Person person in x.Result)
			{
				Console.WriteLine(
					"{0} {1} born {2}",
					person.FirstName,
					person.LastName,
					person.BirthDate.ToShortDateString());
			}
		});

We can control on which thread we will continue by passing in a TaskScheduler. So far so good, so what about testing? I’m using Nunit which integrates really well with VS when using resharper. I want to write an integration test (not unit) to make sure everything works well including the WCF part since unit testing my simple service is too easy ;-) I’ll host the service in the Setup method and take it down in the teardown. A simple test then looks like :

[Test]
public void ShallBeAbleToGetDateTimeFromService()
{
	IPeopleService serviceProxy = new PeopleServiceProxy("PeopleServiceEndpoint");

	Task<IList<Person>> getPeopleTask = serviceProxy.GetPeople();
	getPeopleTask.Wait();

	IList<Person> result = getPeopleTask.Result;

	Assert.IsNotNull(result);
	Assert.AreEqual(2, result.Count);

	(serviceProxy as IDisposable).Dispose();
}

Obviously we’d use facades to call on services in a real application but the principle is the same. It doesn’t get much cleaner than this imo.

/A

Get the code here! (67KB)

This is a post with post format of type Link

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus.

This is a standard post format with preview Picture

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi.

Read more