Sides and Source Code for DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi

This weekend, I participated in an event as a speaker in Izmir, DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi. Sides and Source Code for my sessions are available.
2013-01-08 04:34
Tugberk Ugurlu


This weekend, I participated in an event as a speaker in Izmir. I also had the chance to meet Fatih Boy, İkay İlknur, Umut Erkal and Oğuzhan Yılmaz at the event. There were great sessions throughout the first and second day.

A_2F067CMAA2b2FA_2Gty6CIAAOKnf

A_2oQg4CcAERiYOA_2XVl7CUAEjVF9

I gave two talks during the event and one of them was on Git and GitHub. You can see the slides for that session below:

At the second day, I talked about asynchronous programming for .NET server applications. Slides for that session is also available on my SpeakerDeck page. You can also get the source code for the demos: https://github.com/tugberkugurlu/IzmirDEU201301ServerSideAsync.

JavaScript-Heavy, Maintainable Web Applications by a n00b: 101 - Leveraging Existing Libraries

I decided to dedicate this part of my life to JavaScript for a while and I will write my experience on JavaScript-heavy, maintainable web Applications as a n00b.
2013-01-08 00:07
Tugberk Ugurlu


Nearly every software developer dedicates a part of its time to improve him/herself on a particular area of expertise. Well, I dedicate this part of my life to JavaScript for a while. I have been writing JavaScript for approx. 3 years now but if anybody asks me if I know JavaScript, I tell them that I know JavaScript and I *don’t* know JavaScript at the same time. It’s probably because of the fact that I don’t get to work with it that much. One of the places I struggle most is the idea of maintaining big-ass JavaScript heavy web applications. That idea has been causing me to carry a psychic weight but now, at this very moment, I am committed to throw it away like a piece of garbage! And yes, it starts with a blog post Smile

A few months ago I talked to a brilliant developer about node.js, the platform built on Chrome's JavaScript runtime (V8) for easily building fast, scalable network applications, and asked his opinion about it. He was uncertain at the time but apparently he had more information about node.js than me. So, I expressed that I didn’t understand the need of JavaScript at the server side because it’s hard to maintain such a huge JS codebase. Then, he slapped me in the face with a follow-up sentence: "Well, the node community thinks that a big application codebase needs to be separated into small modules, components to be more maintainable". That was the nudge I needed to believe that the JavaScript codebase can be maintained.

Not long time later from that moment, I then started watching John Papa’s Single Page Apps with HTML5, Web API, Knockout and jQuery and I learnt lots of mind blowing stuff about JavaScript: new (at least new to me) libraries, well-known JavaScript patterns, which I had been aware of but didn’t know how to apply them most of the time, and many more. This was the start of my commitment to learn JavaScript (I mean really learning, going beyond the for loops and if statements) and I pulled out my JavaScript: The Good Parts book which I have bought in last June, but I thought that the best way to learn this stuff is to blog about it. So, here I am Winking smile In this post I am listing a few JavaScript libraries which make a lot of sense to be used in nearly every web applications. I have been working with some of this libraries for a while now and I am going to be working with some of those.

JQuery: The JavaScript framework we all know and fell in love at the time that we have noticed it. JQuery is especially helpful for DOM manipulation and Ajax interactions. If you don’t want to install JQuery, don’t worry; you eventually will have to because I am sure that at least of the libraries you are going to use will have a dependency on it.

KnockoutJS: KnockoutJS is one of the best things that can happen to a web developer. Starting to learn KnockoutJS gives you the equivalent feeling which you would feel at the very moment when you find a cup of hot chocolate in a freezing cold day. It enables your to have two way data-binding between your DOM elements and your view model which means when your data model's state changes, your UI updates automatically and vice versa. Check out its well-arranged documents and live tutorials.

Underscore.js: Underscore.js provides a utility suite which covers lots of useful functions. From the its official page: "Underscore provides 80-odd functions that support both the usual functional suspects:map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map,reduce, filter, every, some and indexOf". Don’t forget to watch this awesome presentation from Elijah Manor on Underscore.js.

RequireJS: I think RequireJS is the essential piece of library which makes it possible to have maintainable, well-designed JavaScript codebase. It’s a modular script loader which enables you to write small pieces of code in separate files and handle their dependencies and load order correctly. RequireJS also has a very nice documentation in its web site; definitely check that out.

Sammy.js: Last library I am considering for my every web application is Sammy.js. It gives us a nice way to handle page navigations without refreshing the page at all by providing a nice routing mechanism. Especially, if you are writing a Single Page Applications (SPA), this is the library that you want inside your suite. Don’t skip to check out its intro sample.

There are for sure other great libraries out there (e.g. Moment.js, AmplifyJS, JQuery UI, Breeze) but these are the ones I am in love at the moment. Go check them out and start exploring Winking smile

List of Resources on Asynchronous Programming for .NET Server Applications with C#

I listed some resources on asynchronous programming for .NET server applications with C# which consist of blog posts, presentations and podcasts.
2013-01-05 22:01
Tugberk Ugurlu


I will be participating on an event today in Izmir talking about asynchrony for .NET server applications (mostly ASP.NET) and I thought it would be great to list some reference blog posts, presentations and podcasts on this topic as there are a few distinct resources regarding asynchrony as I listed below.

In my talk, I plan to mix some stuff from previous @StevenSanderson, @DamianEdwards, @LeviBroderick, @bradwilson presentations and blog posts. I have also bunch of demos which I will be sharing online in my GitHub repository. So, enjoy the resources for now Winking smile

Resources for Asynchrony in General

Resources for Asynchrony for Server Applications

DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi

DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi: if you are in Izmir this weekend (5 – 6 January, 2013), don’t miss this event.
2013-01-03 10:43
Tugberk Ugurlu


If you are in Izmir this weekend (5 – 6 January, 2013), don’t miss this event. Me, Fatih Boy, İlkay İlknur and Umut Erkal will be giving talks on several interesting topics.

Facebook event page: http://www.facebook.com/events/189388904534737

A_cVGTvCYAAXvL5

Mapping ASP.NET SignalR Connections to Real Application Users

One of the common questions about SignalR is how to broadcast a message to specific users and the mapping the SignalR connections to your real application users is the key component for this.
2013-01-01 15:32
Tugberk Ugurlu


SignalR; the incredible real-time web framework for .NET. You all probably heard of it, maybe played with it and certainly loved it. If you haven’t, why don’t you start by reading the SignalR docs and @davidfowl’s blog post on Microsoft ASP.NET SignalR? Yes, you heard me right: it’s now officially a Microsoft product, too (and you may see as a bad or good thing).

One of the common questions about SignalR is how to broadcast a message to specific users and the answer depends on what you are really trying to do. If you are working with Hubs, there is this notion of Groups which you can add connections to. Then, you can send messages to particular groups. It’s also very straight forward to work with Groups with the latest SignalR server API:

public class MyHub : Hub
{
    public Task Join()
    {
        return Groups.Add(Context.ConnectionId, "foo");
    }

    public Task Send(string message)
    {
        return Clients.Group("foo").addMessage(message);
    }
}

You also have a chance to exclude some connections within a group for that particular message. However, if you have more specific needs such as broadcasting a message to user x, Groups are not your best bet. There are couple of reasons:

  • SignalR is not aware of any of your business logic. SignalR knows about currently connected connections and their connection ids. That’s all.
  • Assume that you have some sort of authentication on your application (forms authentication, etc.). In this case, your user can have multiple connection ids by consuming the application with multiple ways. So, you cannot just assume that your user has only one connection id.

By considering these factors, mapping the SignalR connections to actual application users is the best way to solve this particular problem here. To demonstrate how we can actually solve this problem with code, I’ve put together a simple chat application and the source code is also available on GitHub.

image

This application obviously not a production ready application and the purpose here is to show how to achieve connection mapping. I didn’t even use a persistent data storage technology for this demo.

The scenarios I needed to the above sample are below ones:

  • A user can log in with his/her username and can access to the chat page. A user also can sign out whenever they want.
  • A user can see other connected users on the right hand side at the screen.
  • A user can send messages to all connected users.
  • A user can send private messages to a particular user.

To achieve the first goal, I have a very simple ASP.NET MVC controller:

public class AccountController : Controller {

    public ViewResult Login() {

        return View();
    }

    [HttpPost]
    [ActionName("Login")]
    public ActionResult PostLogin(LoginModel loginModel) {

        if (ModelState.IsValid) {

            FormsAuthentication.SetAuthCookie(loginModel.Name, true);
            return RedirectToAction("index", "home");
        }

        return View(loginModel);
    }

    [HttpPost]
    [ActionName("SignOut")]
    public ActionResult PostSignOut() {

        FormsAuthentication.SignOut();
        return RedirectToAction("index", "home");
    }
}

When you hit the home page as an unauthenticated user, you will get redirected to login page to log yourself in. As you can see from the PostLogin action method, everybody can authenticate themselves by simply entering their name which is obviously not what you would want in a real world application.

As I am hosting my SignalR application under the same process with my ASP.NET MVC application, the authenticated users will flow through the SignalR pipeline, too. So, I protected my Hub and its methods with the Microsoft.AspNet.SignalR.Hubs.AuthorizeAttribute.

[Authorize]
public class ChatHub : Hub { 

    //...
}

As we are done with the authorization and authentication pieces, we can now move on and implement our Hub. What I want to do first is to keep track of connected users with a static dictionary. Now, keep in mind again here that you would not want to use a static dictionary on a real world application, especially when you have a web farm scenario. You would want to keep track of the connected users with a persistent storage system such as MongoDB, RavenDB, SQL Server, etc. However, for our demo purposes, a static dictionary will just work fine.

public class User {

    public string Name { get; set; }
    public HashSet<string> ConnectionIds { get; set; }
}

[Authorize]
public class ChatHub : Hub {

    private static readonly ConcurrentDictionary<string, User> Users 
        = new ConcurrentDictionary<string, User>();
        
    // ...
}

Each user will have a name and associated connection ids. Now the question is how to add and remove values to this dictionary. SignalR raises three particular events on your hub: OnConnected, OnDisconnected, OnReconnected and the purposes of these events are very obvious.

During OnConnected event, we need to add the current connection id to the user’s connection id collection (we need to create the User object first if it doesn’t exist inside the dictionary). We also want to broadcast this information to all clients so that they can update their connected users list. Here is how I implemented the OnConnected method:

[Authorize]
public class ChatHub : Hub {

    private static readonly ConcurrentDictionary<string, User> Users 
        = new ConcurrentDictionary<string, User>();
        
    public override Task OnConnected() {

        string userName = Context.User.Identity.Name;
        string connectionId = Context.ConnectionId;

        var user = Users.GetOrAdd(userName, _ => new User {
            Name = userName,
            ConnectionIds = new HashSet<string>()
        });

        lock (user.ConnectionIds) {

            user.ConnectionIds.Add(connectionId);
            
            // TODO: Broadcast the connected user
        }

        return base.OnConnected();
    }
}

First of all, we have gathered the currently authenticated user name and connected user’s connection id. Then, we look inside the dictionary to get the user based on the user name. If it doesn’t exist inside the dictionary, we create one and set it to the local variable named user. Lastly, we add the connection id and updated the dictionary.

Notice that we have a TODO comment at the end telling that we need to broadcast the connected user’s name. Obviously, we don’t want to broadcast this information to the caller itself. However, we still have two options here and which one you would choose may depend on your case. As the user might have multiple connections, broadcasting this information over Clients.Others API is not a way to follow. Instead, we can use Clients.AllExcept method which takes a list of connection ids as parameter to exclude. So, we can pass the all connection ids of the user and we are good to go.

public override Task OnConnected() {

    // Lines omitted for brevity
    
    Clients.AllExcept(user.ConnectionIds.ToArray()).userConnected(userName);

    return base.OnConnected();
}

This is a fine approach if we want to broadcast each connection of the user to every client other than the user itself. However, we may only want to broadcast the first connection. Doing so is very straight forward, too. We just need to inspect the count of the connection ids and if it equals to one, we can broadcast the information. This approach is the one that I ended up taking for this demo.

public override Task OnConnected() {

    // Lines omitted for brevity

    lock (user.ConnectionIds) {

        // Lines omitted for brevity
        
        if (user.ConnectionIds.Count == 1) {

            Clients.Others.userConnected(userName);
        }
    }

    return base.OnConnected();
}

When the disconnect event is fired, OnDisconnected method will be called and we need to remove the current connection id from the users dictionary. Similar to what we have done inside the OnConnected method, we need to handle the fact that user can have multiple connections and if there is no connection left, we want to remove the user from Users dictionary completely. As we did when a user connection arrives, we need to broadcast the disconnected users, too and we have the same two options here as well. I added both to the below code and commented out the one that we don’t need for our demo.

[Authorize]
public class ChatHub : Hub {

    private static readonly ConcurrentDictionary<string, User> Users 
        = new ConcurrentDictionary<string, User>();

    public override Task OnDisconnected() {

        string userName = Context.User.Identity.Name;
        string connectionId = Context.ConnectionId;
        
        User user;
        Users.TryGetValue(userName, out user);
        
        if (user != null) {

            lock (user.ConnectionIds) {

                user.ConnectionIds.RemoveWhere(cid => cid.Equals(connectionId));

                if (!user.ConnectionIds.Any()) {

                    User removedUser;
                    Users.TryRemove(userName, out removedUser);

                    // You might want to only broadcast this info if this 
                    // is the last connection of the user and the user actual is 
                    // now disconnected from all connections.
                    Clients.Others.userDisconnected(userName);
                }
            }
        }

        return base.OnDisconnected();
    }
}

When the OnReconnected method is invoked, we don’t need to perform any special logic here as the connection id will be the same. With these implementations, we are now keeping track of the connected users and we have mapped the connections to real application users.

Going back to our scenarios list above, we have the 4th requirement: a user sending private messages to a particular user. This is where we actually need the connection mapping functionality. As an high level explanation, the client will send the name of the user that s/he wants to send the message to privately. So, server needs to make sure that it is only sending the message to the designated user. I am not going to go through all the client code (as you can check them out from the source code and they are not that much related to the topic here) but the piece of JavaScript code that actually decides whether to send a public or private message is as below:

$sendBtn.click(function (e) {

    var msgValue = $msgTxt.val();
    if (msgValue !== null && msgValue.length > 0) {

        if (viewModel.isInPrivateChat()) {

            chatHub.server.send(msgValue, viewModel.privateChatUser()).fail(function (err) {
                console.log('Send method failed: ' + err);
            });
        }
        else {
            chatHub.server.send(msgValue).fail(function (err) {
                console.log('Send method failed: ' + err);
            });
        }
    }
    e.preventDefault();
});

The above code inspects the KnockoutJS view model to see if the sender is at the private chat mode. If s/he is, it invokes the send hub method on the sever with two parameters which means that this will be a private message. If the sender is not at the private chat mode, we will just invoke the send hub method by passing only one parameter for the message. Let’s first look at Send Hub method that takes one parameter:

public void Send(string message) {

    string sender = Context.User.Identity.Name;

    Clients.All.received(new { 
        sender = sender, 
        message = message, 
        isPrivate = false 
    });
}

Inside the send method above, we first retrieved the sender's name through the authenticated user principal. Then, we are broadcasting the message to all clients with a few more information such as the sender name and the privacy state of the message. Let’s now look at the second Send method inside the Hub whose job is to send private messages:

public void Send(string message, string to) {

    User receiver;
    if (Users.TryGetValue(to, out receiver)) {

        User sender = GetUser(Context.User.Identity.Name);

        IEnumerable<string> allReceivers;
        lock (receiver.ConnectionIds) {
            lock (sender.ConnectionIds) {

                allReceivers = receiver.ConnectionIds.Concat(
                    sender.ConnectionIds);
            }
        }

        foreach (var cid in allReceivers) {
        
            Clients.Client(cid).received(new { 
                sender = sender.Name, 
                message = message, 
                isPrivate = true 
            });
        }
    }
}

private User GetUser(string username) {

    User user;
    Users.TryGetValue(username, out user);

    return user;
}

Here, we are first trying to get the receiver based on the to parameter that we have received. If we find one, we are also retrieving the sender based on the his/her name. Now, we have the sender and the receiver in our hands. What we want is to broadcast this message to the receiver and the sender. So, we are putting the sender’s and the receiver’s connection ids together first. Finally, we are looping through that connection ids list to send the message to each connection by using the Clients.Client method which takes the connection id as a parameter.

When we try this out, we should see it working as below:

image

Grab the solution and try it yourself, too. I hope this post helped you to solve your problem Smile

References