Some XSockets and SisoDb fun – Part 1 of 2

This is a two post series that will show you how to use XSockets and SisoDb to create a JavaScript client for SisoDb, that let’s you consume the db directly from JavaScript. Not saying it’s what you should do, just showing what you can do. In this first post we will look at getting started with XSockets and getting our custom handler in place. The next post will show the implementation. The steps in this post are:

  • Step 1 – Setup XSockets
  • Step 2 – Create the SisoDbHandler
  • Step 3 – Create a debuggable server
  • Step 4 – Implement a simple Ping method in our SisoDbHandler
  • Step 5 – Use the SisoDbClient.js to invoke our Ping member

Step 1 – Setup XSockets

First create a new empty ASP.Net MVC 3 project. Then install the NuGet package XSockets. Note! Use the Package Manager console

After the installation is done, some scaffolding templates (located under CodeTemplates) has been installed along with a XSocket-server and some web samples (located under XSockets). There’s also a new project “XSocketHandler” which is empty at the moment. This is where we will put our “SisoDbHandler“.

The development server will represent the server endpoint serving client connections. The client connection could come from e.g a JavaScript client using the XSockets.JsApi package or from .Net code using XSockets.External.

Now, lets start the development server via Windows explorer; and have a look at some of it’s commands. Start it and type: “help“.

The commands, currently available, are:

Try the “handlers” command. It will list the currently available handlers. And per default there’s one serving textual data (e.g JSON) and one serving binary data. And when we are done there will be a “SisoDbHandler“.

The included GenericText and GenericBinary handlers will let you, out of the box, be able to get up an running pushing JSON messages around and stream binary data. Hence you could e.g. create chats etc, right out of the box. Have a look at the included examples to see how easy it is.

Step 2 – Create the SisoDbHandler

A handler could be seen as a controller in ASP.Net MVC; and each handler serves one or many requests. To create a handler, turn back to the Package Manager Console and use the “scaffold” command and select “XSocketHandler“.

Name it: “SisoDbHandler“.

This will scaffold a new XSocketHandler named “SisoDbHandler” in the XSocketHandler project. Compile the solution and use “Show all files” in the MVC project, and you will see that the build events of the XSocketHandler project have copied the “XSocketHandler.dll” to the “XSocketServerPlugins” folder.

Now, start the server again and run the “handlers” command. You should now see the new “SisoDbHandler“.

Step 3 – Create a debuggable server

To be able to easily debug our handler and to manage deployment of dependencies during development, we will create a custom Server and not use the precompiled server under the MVC project.

Add a new console project. Name it “Server” and remove client profile for it (I wrote a quick post about how to get rid of it for-ever in about 5minutes.

Now, copy everything inside the folder “$MVCApp$\XSockets\DevelopmentServer” to “$Solution$\XSockets” and rename “XSocketServerPlugins” to “Plugins“. Clean it up so that it looks like this:

Add a reference to the “XSockets.Core.dll” above in the Server project.

Now, add an App.Config to the newly created Server-project. Copy the contents of “$MVCApp$\\XSockets\DevelopmentServer\XSockets.DevelopmentServer.Console.exe.config” to your newly created App.config file.

Locate the app-setting “XSocketServerPluginCatalog” and make it look like this:

<add key="XSocketServerPluginCatalog" value="..\..\..\XSockets\Plugins\" />

Go to the XSocketHandler project and open properties for it. Adjust the Pre- and Post- build events so that the dll gets copied to the Server-project instead.

Pre-build event

IF NOT EXIST "$(SolutionDir)XSockets\Plugins\" mkdir "$(SolutionDir)XSockets\Plugins\"

Post-build event

copy "$(TargetDir)$(TargetName).dll", "$(SolutionDir)XSockets\Plugins\"
copy "$(TargetDir)$(TargetName).pdb", "$(SolutionDir)XSockets\Plugins\"

Create a class Named “Start” under the Server-project. Copy the content from “MVC-Project\XSockets\devservercode.txt” to this newly created class. Fix namespaces and add reference to the “Server\XSockets\XSockets.Core.dll“. You will also need to add references to “System.Componentmodel.Composition“. The namespaces and using statements should look like this:

using System;
using System.ComponentModel.Composition;
using System.Configuration;
using XSockets.Core.Plugin.MEF;
using XSockets.Core.XSocket.Interface;

namespace Server
{
    public class Start : Composable
    {
        //... ... ...
    }
}

It’s time for the final adjustment. Now lets fix Program.cs. In $MVCApp$\XSockets\DevelopmentServer\HOW_DO_I_DEBUG_MY_HANDLERS.txt you can find a snippet around step 7 in that file. Make the Main method look something like this:

static void Main(string[] args)
{
    try
    {
        new Start();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        if (ex.InnerException != null)
            Console.WriteLine(ex.InnerException.Message);
        Console.ReadLine();
    }
}

It should now be ready to serve our client requests. Fire up the Server and run the “handlers” command and ensure that the “SisoDbHandler” is located in there.

Step 4 – Implement a simple Ping method in our SisoDbHandler

Before wrapping this up, let’s add a simple Ping action in our handler. Again, a handler could be seen as a controller in Asp.Net MVC; and it’s members serving socket calls; could be seen as actions in Asp.Net MVC.

Create a new folder/namespace, and call it “Commands“. Add a class called “PingCommand“. This will serve as our model in.

public interface ICommand {}

public class PingCommand : ICommand
{
    public string Message { get; set; }
}

Create a new folder/namespace, and call it “Results“. Add a class called “PingResult“. This will serve as our model out.

public interface IResult {}

public class PingResult : IResult
{
    public string Message { get; set; }
}

Now, add a member in our SisoDbHandler, and make it look like this:

[HandlerEvent("Ping")]
public void Ping(PingCommand command)
{
    this.AsyncSend(new PingResult { Message = command.Message }, "OnPinged");
}

If you now start the Server and run the “handlers” command, you will see that the SisoDbHandler now accepts calls to a member called “Ping“.

Step 5 – Use the SisoDbClient.js to invoke our Ping member

Now, lets use the added Ping member. Create a simple html-page in the root of our MVC-app. Name it “demo.html“. We need script references to jQuery, XSockets and the SisoDbClient.js libs.

<!DOCTYPE html>
<html>
<head>
	<title>Demo - SisoDb-XSockets</title>
	<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
	<script src="Scripts/JXSockets-1.0.4.beta.js" type="text/javascript"></script>
	<script src="http://cloud.github.com/downloads/danielwertheim/SisoDb-XSockets/sisodbclient-debug-v0.1.0.js" type="text/javascript"></script>
	
	<script type="text/javascript">
		var my = {};

		$(function () {
			//Hook up client
			my.client = new SisoDbClient("ws://127.0.0.1:4502/SisoDbHandler");
			my.client.logger.enabled = true;
			my.client.connect();

			//Hookup listeners
			my.client.onPinged(function (data) {
				$("<li>").text(data.Message).prependTo("ul:first");
			});

			//Hookup UI to consume client
			$("#ping").on("click", function () {
				my.client.ping($("#pingMessage").val());
			});
		});
	</script>
	<link href="Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<fieldset>
		<legend>Ping</legend>
		<label for="pingMessage">Message</label>
		<input type="text" id="pingMessage"/>
		<button id="ping">Ping</button>
	</fieldset>
	
	<ul></ul>
</body>
</html>

Now, start the server and start the MVC-app and browse to the Html-page. Run the command “status” in the server and you should see something like this:

Lets invoke our UI and just send the text: “Test“. If you have the console running, the SisoDbClient.Js will output some logging. You can turn this off by changing this line:

my.client.logger.enabled = false;

That’s it! The next time we will implement a simple model and the CRUD operations.

//Daniel

One thought on “Some XSockets and SisoDb fun – Part 1 of 2

  1. Pingback: Some XSockets and SisoDb fun – Part 2 of 2 « Daniel Wertheim

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s