Whitepaper: Introduction to Windows Store Apps & WinRT

Windows 8 is big step forward in the evolution of Modern touch friendly User interface – never seen before since Windows 95.

With the release of Windows 8, Microsoft has also released Visual studio 2012 and a new runtime from ground up called WinRT. It presents a significant opportunity for a variety of developers from different backgrounds to take advantage of consistent, easy to use API and ultimately be able to sell their apps on the Windows 8 Store.

I have written a whitepaper on the subject.

Hope you like it.

Advertisements

Getting Started with self-hosting SignalR using PersistentConnection

SignalR is a great library to help build real-time, single/multi user apps.
Although SignalR is very well documented, I wanted to write a compact sample which demonstrates Client and Server using PersistentConnection.

I have specifically chosen not to use Hub for this demo as there are many samples out there already.

Step 1
Create a console project.

Step 2
Add following nuget packages
SignalR.Hosting.Self
SignalR.Client

Step 3
To create instance of server, pass the url in the Server class’s constructor. Map the connection. Please make sure that you provide “/” at the end in the url.

You then call MapConnection method with a name of the path. This means that now your client connection becomes Url+Path.

Note MapConnection takes a type ‘T’ where T: PersistentConnection. Since PersistentConnection is an abstract class, you typically inherit from PersistentConnection and that becomes the entry point where the client calls arrives. See below a class called ‘MyConnection’

Next you create instance of Client.Connection class, Be careful, there is a connection class in the server as well so you may have to qualify it with Client.Connection here.

Client side events

‘Received’ is called when Server calls you back
‘StateChanged’ is called when the Connection state changes

SourceCode_image1

Step 4
To call server, call “Start” method on the client’s connection object which returns a task so check for the task for any problems before proceeding and then call ‘Send’ method which actually calls server. Once the Send method is executed, ‘OnReceivedAsync’ method of ‘MyConnection’ class is called. Here you can call all the client’s back by executing ‘Connection.Broadcast’ (or just use Connection.Send method calls the client that is waiting for specific signal) method

SourceCode_image2

Source code for MyConnection class

SourceCode_image3

When you run this sample, you should see output like following.

console_output

You can download sample from here

ASP.NET Web API BSON Formatter

ASP.NET Web API includes JSON.NET which includes BSON Serializer so to support BSON format it is quite easy.

  1. Create a class called BSONFormatter and inherit from MediaTypeFormatter
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace WebAPI.Common.Formatter
{
     public class BsonFormatter : MediaTypeFormatter
    {
        public BsonFormatter()
        {
            SupportedMediaTypes
             .Add(new MediaTypeHeaderValue("application/bson"));
        }

        public MediaTypeHeaderValue MediaTypeHeaderValue
        {
            get 
           { 
               return new MediaTypeHeaderValue("application/bson"); 
            }
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
         }

2. Make sure you include following namespace

using

3. Override WriteToStreamAsync method, using BsonWriter by passing the stream and using JsonSerializer to serialize.

public override Task WriteToStreamAsync(Type type,
 object value, Stream writeStream, HttpContent content,
            TransportContext transportContext)
        {
            Task task = Task.Factory.StartNew(
                () =>
                    {
                        content.Headers.ContentType = MediaTypeHeaderValue;
                        var serializer = new JsonSerializer();

                        // serialize product to BSON
                        var writer = new BsonWriter(writeStream);
                        serializer.Serialize(writer, value);
                    });

            return task;
        }

4. Plugging it in Web.API pipeline.

  var config = new HttpSelfHostConfiguration("http://localhost:8080");
    ILifetimeScope container = GetContainerLifeTimeScope();
     config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "WebAPI/{controller}/{id}",
                defaults: new {id = RouteParameter.Optional}
                );

      config.Formatters.Add(new BsonFormatter());
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
      using (var server = new HttpSelfHostServer(config))
      {
                server.OpenAsync().Wait();
                Console.WriteLine("Press any key to terminate");
                Console.ReadLine();
        }

5. Bson Request/Response (in fiddler)

BsonRequest BsonResponse