On Mystery Meat Navigation and Unusability

This article was originally posted here at Programmer’s Ranch on 12th September 2013. It has been updated since a lot of the original examples are no longer available.

Hello folks! ūüôā

Today I’m going to talk about¬†Mystery Meat Navigation¬†(MMN). This term was invented 15 years ago by Vincent Flanders of¬†Web Pages That Suck. It refers to a horrible practice of filling a website’s navigation with meaningless icons. When a user moves his mouse over one of these icons, the icon changes or pops up some text, revealing what it really does.

A classic analogy of mystery meat navigation (which seems to have mostly disappeared from the web) is a road sign that initially looks completely blank, but changes to indicate where you’re going just as you drive past it.

Even now, 15 years later, MMN is still used on the web. Even reputable web design companies here in Malta have fallen in the MMN trap. Alert eBusiness, for instance, used to have the following navigation bar:

alert-mmn

Right, so what do those icons mean? The last one seems pretty clear: a shopping cart. Mousing over it reveals it stands for Alert Payment Gateway, which is close enough. But what about the rest? The first one is a mouse, for instance. Would it ever cross your mind that it actually means “Web Design”?

Another example: Pcionix (now defunct):

pcionix-mmn

The home icon is pretty obvious, so that can be forgiven. But a pie chart that stands for SEO – seriously?

But this, from design.com.mt, is even worse:

design-mmn

This has got to be the worst of them all. Whereas you might be able to somehow guess what the icons in the other sites mean, the navigation here is hidden behind meaningless numbers that you again have to mouse over to understand.

It gets worse: there are videos on YouTube of sites with iconic navigation that actually floats around, so you actually have to find out where that “About Us” cube thingy moved to (examples:¬†Mandarina Duck,¬†Qualcomm).

So why is MMN bad? In case it isn’t obvious, it is very annoying for users to have to click on stuff to figure out what the page offers. A website should give a clear indication of how it is structured, without the user needing to interact with it just to get an idea. Imagine you’re driving and need to interact with a bunch of direction signs (such as¬†these) one by one to get an idea of the places in the area. Then, after sifting through a dozen, you forget what you saw earlier and have to go back and interact with them again. Sorry, the “just a click away” idea is not an excuse when it comes to navigation, which is really a website’s backbone.

Another great example comes from feedback that Vincent Flanders received, and illustrates how MMN would be if applied to a business’s answering machine:

“You’ve reached XYZ Corporation. To find out what option #1 is, press 1. To find out what option #2 is, press 2. (Etc….) If you’d like to continue doing business with our company after we’ve slapped you around and wasted your valuable time, press 9”

MMN is a slap in the face of usability. It shows meaningless icons in the place of important navigational information. What could possibly worse?

The only thing worse than showing meaningless icons is not showing any icons at all! That’s pretty much the direction taken by Windows 8’s notorious alternate UI, formerly known as Metro. One of its¬†design principles is “Do more with less” which includes “Put content before chrome”. In this case the “chrome” refers to the stuff that makes the application – menus, the ‘X’ button at the top-right, toolbars, etc. So basically you end up with something like this:

ubuntu-pdf-metro

That’s the default PDF viewer on Windows 8 – one full screen Windows 8 Style (the new name for Metro) app with the PDF content and nothing else, not even an ‘X’ to close it. In fact Windows 8 users are somehow expected to know beforehand (“by osmosis”, as this Windows 8.1 review¬†puts it)¬†that to close a Windows 8 Style app you have to grab it from the top and drag downwards with your mouse. Contrast this with the same PDF viewed on Windows 7:

ubuntu-pdf-win7

Needless to say, everything that you can do with a PDF is immediately accessible either from the toolbars or via the menus. There is no hidden stuff, no needing to drag your mouse into a corner to open some Start Screen or Charms Bar. See, the program actually shows you what it can do, and for new users that’s important. The “Content before Chrome” idea is wrong precisely because when you use a program, you want to do¬†stuff, not just see¬†stuff.

So it’s no wonder that Microsoft seems to have made a¬†U-turn on its Windows 8 Style design stuff. If MMN is an example of bad usability, this Windows 8 abomination is an example of… unusability.

XML Serialization in C#

This article was originally posted here at Programmer’s Ranch on 6th November 2013.

Hi guys and gals! ūüôā

In this article, we’re going to see how to do XML serialization, which is really just a fancy way of saying we want to load and save objects as files in XML format.

So you see, I’ve been a big fan of Warcraft 2 for a long time… probably about 15 years. In this game, you command different units (e.g. peasants, knights, etc), and each of them has different attributes such as Damage, Speed, etc. For instance, this is the mage:

csxmlser-war2-mage

Don’t mess with that guy – he can turn you into a sheep! And here’s the knight… not exactly a mild-mannered fellow, either:

csxmlser-war2-knight

If we represent those units and their attributes in XML, we might end up with something like this (I took out some of the extra crap that appears at the beginning when you actually save a file using XML serialization):

<UnitDatabase>
  <units>
    <Unit>
      <Name>Mage</Name>
      <Armor>0</Armor>
      <MinDamage>5</MinDamage>
      <MaxDamage>9</MaxDamage>
      <Range>2</Range>
      <Sight>9</Sight>
      <Speed>8</Speed>
    </Unit>
    <Unit>
      <Name>Knight</Name>
      <Armor>4</Armor>
      <MinDamage>2</MinDamage>
      <MaxDamage>12</MaxDamage>
      <Range>1</Range>
      <Sight>4</Sight>
      <Speed>13</Speed>
    </Unit>
  </units>
</UnitDatabase>

So, let’s see how we can actually read and write a file like this in C#. Create a new Console Application in your favourite IDE.

We first need to create a class to represent our units with their attributes. Create a class and call it Unit. For convenience, we can implement the attributes as auto-implemented properties as follows:

public String Name { get; set; }
public int Armor { get; set; }
public int MinDamage { get; set; }
public int MaxDamage { get; set; }
public int Range { get; set; }
public int Sight { get; set; }
public int Speed { get; set; }

This is just a quick alternative to declaring a member variable and a corresponding read-write property (available from .NET 3.0 onwards). For example, the Name¬†property above is more or less equivalent to the following (just for demonstration – don’t actually add it to your code):

private String name;

public String Name
{
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}

Next, add a constructor to set the attributes, so we can easily create Unit instances from our main program code:

public Unit(String name, int armor, int minDamage, int maxDamage,
    int range, int sight, int speed)
{
    this.Name = name;
    this.Armor = armor;
    this.MinDamage = minDamage;
    this.MaxDamage = maxDamage;
    this.Range = range;
    this.Sight = sight;
    this.Speed = speed;
}

Now we need to create another class to hold an array of these units. Create a new class and call it UnitDatabase¬†(admittedly a bit of a poor choice of a name, since it’s not actually a database, but anyway). Give it a Units¬†property as follows:

public Unit[] Units { get; set; }

A constructor to assign this directly can also be pretty convenient. Add the following:

public UnitDatabase(Unit[] units)
{
    this.Units = units;
}

Now we can implement our loading and saving code in UnitDatabase itself. Start by adding the code to save the UnitDatabase to a file:

public void Save(String filename)
{
    XmlSerializer ser = new XmlSerializer(typeof(UnitDatabase));

    using (StreamWriter sw = File.CreateText(filename))
        ser.Serialize(sw, this);
}

You can see that we’re making use of the¬†XmlSerializer¬†class. The file is saved by using its¬†Serialize()¬†method, which takes a TextWriter¬†and the object to serialize. The StreamWriter¬†returned by File.CreateText() quite conveniently is a subclass of TextWriter, so we can pass it as the first parameter to Serialize(). The second parameter is¬†this: the UnitDatabase itself.

To get this code to compile, you’ll have to add the following¬†using¬†statements at the top:

using System.Xml.Serialization;
using System.IO;

Loading an XML file as a UnitDatabase¬†is just as easy. In this case we make the method static since it isn’t tied to any particular UnitDatabase¬†instance:

public static UnitDatabase Load(String filename)
{
    XmlSerializer ser = new XmlSerializer(typeof(UnitDatabase));
    
    using (StreamReader sr = File.OpenText(filename))
        return ser.Deserialize(sr) as UnitDatabase;
}

You can see that we’re still using the XmlSerializer, but this time we use the¬†Deserialize()¬†method to read the file from disk and create a UnitDatabase¬†from it. Deserialize() takes a TextReader, which again is a base class of the StreamReader¬†that we get by calling File.OpenText(), so everything fits like magic. Deserialize() returns an Object, so as a last touch we cast this to a UnitDatabase¬†using the¬†as¬†keyword. It’s just the same as writing it like this:

return (UnitDatabase) ser.Deserialize(sr);

That’s all we need! Now, let’s add some functionality to make it easy to write our units to the console output. All classes inherit from Object, and Object¬†defines this ToString()¬†method which we can use to return a string representation of our objects. This is very convenient in our case, so we can implement Unit‘s ToString() method as follows:

public override string ToString()
{
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("Name:      {0}", this.Name);
    sb.AppendLine();
    sb.AppendFormat("Armor:     {0}", this.Armor);
    sb.AppendLine();
    sb.AppendFormat("MinDamage: {0}", this.MinDamage);
    sb.AppendLine();
    sb.AppendFormat("MaxDamage: {0}", this.MaxDamage);
    sb.AppendLine();
    sb.AppendFormat("Range:     {0}", this.Range);
    sb.AppendLine();
    sb.AppendFormat("Sight:     {0}", this.Sight);
    sb.AppendLine();
    sb.AppendFormat("Speed:     {0}", this.Speed);
    sb.AppendLine();
    
    return sb.ToString();
}

Note the¬†override¬†keyword in the method’s signature. This means that we are replacing ToString()‘s default functionality (which usually just returns the name of the class) with our own, in this case showing the unit’s name and attributes.

Let’s do the same for UnitDatabase. In this case we return a concatenation of all the units’ string representations:

public override string ToString()
{
    StringBuilder sb = new StringBuilder();
    foreach (Unit unit in this.Units)
        sb.AppendLine(unit.ToString());
    return sb.ToString();
}

To compile this code, you’ll need to add the following line at the top of both files (because of the StringBuilder):

using System.Text;

Now all we have left to do is write code in Main() that actually uses these classes. We can start by creating our two units:

Unit mage = new Unit("Mage", 0, 5, 9, 2, 9, 8);
Unit knight = new Unit("Knight", 4, 2, 12, 1, 4, 13);

We can then combine these into an array using collection initializer syntax¬†(see “C# Basics: Morse Code Converter Using Dictionaries” if you forgot what that is):

Unit[] units = new Unit[] { mage, knight };

Then, we create a UnitDatabase out of this array:

UnitDatabase db = new UnitDatabase(units);

…and finally save it to a file called units.xml:

db.Save("units.xml");

You can now press F5 to run the program and see that it works. If you’re using Visual Studio, you might have run into this error:

csxmlser-ctor-error

That’s because XML serialization needs classes to have an empty constructor. SharpDevelop creates one for you when you create a new class, but Visual Studio does not. So if you’re missing those, add them in. One for Unit:

public Unit()
{

}

…and one for UnitDatabase:

public UnitDatabase()
{

}

Good. Now press F5 to run the program, and then go to the project’s bin\Debug folder to check that the units.xml¬†file has been created. When you open it, it should look like this:

<?xml version="1.0" encoding="utf-8"?>
<UnitDatabase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Units>
    <Unit>
      <Name>Mage</Name>
      <Armor>0</Armor>
      <MinDamage>5</MinDamage>
      <MaxDamage>9</MaxDamage>
      <Range>2</Range>
      <Sight>9</Sight>
      <Speed>8</Speed>
    </Unit>
    <Unit>
      <Name>Knight</Name>
      <Armor>4</Armor>
      <MinDamage>2</MinDamage>
      <MaxDamage>12</MaxDamage>
      <Range>1</Range>
      <Sight>4</Sight>
      <Speed>13</Speed>
    </Unit>
  </Units>
</UnitDatabase>

It’s got some more stuff in the first two lines than I showed you at the beginning, but that’s just added there to make it a valid XML document and you can just ignore it.

At the end of Main(), let us now add code to load the file and display the unit data:

UnitDatabase loadedDb = UnitDatabase.Load("units.xml");
Console.WriteLine(loadedDb.ToString());
Console.ReadLine();

Press F5 to see the result:

csxmlser-result

If you omit the ToString() as follows:

Console.WriteLine(loadedDb);

…then the program works all the same, because Console.WriteLine() uses the¬†ToString() method of the objects it is meant to write.

Great! ūüôā In this article, we have seen how we can very easily save (serialize) objects as XML files, and load (deserialize) them back from XML files. To do this we need classes that match the XML structure, as well as the handy XmlSerializer class. Classes to be serialized must have a parameterless constructor. It is possible to do a lot more with XML serialization – there are several attributes that allow you to control the actual XML nodes and attributes that are written to the file.

We have also seen other aspects of C#, such as the ToString() method available in every object; how to override inherited methods; the as keyword which is an elegant alias for type casting; and auto-implemented properties.

Thanks for reading, and come visit Programmer’s Ranch Gigi Labs again in future! ūüôā

To Always Use Braces for Conditionals and Loops… or not

This article was originally posted here at Programmer’s Ranch on 25th September 2013. The original article mentions Jesse Liberty as “one of many who suggest always using braces” with conditional statements. However, Jesse Liberty changed his view after reading the article (as you can see in the comments of the original article). As such, the article presented here has been slightly edited to remove this statement.

Hi everyone! ūüôā

While following a number of¬†Pluralsight courses by Jesse Liberty¬†(which I highly recommend), I was reminded of the long-running¬†debate about whether one should always use braces¬†when control flow statements (conditionals and loops) are involved. So let’s say we have the following conditional:

if (x == 0)
    Console.WriteLine("x is zero");
else if (x < 0)
    Console.WriteLine("x is negative");
else if (x > 0)
    Console.WriteLine("x is positive");

The proponents of the always-use-braces camp would have us write them like this:

if (x == 0)
{
    Console.WriteLine("x is zero");
}
else if (x < 0)
{
    Console.WriteLine("x is negative");
}
else if (x > 0)
{
    Console.WriteLine("x is positive");
}

In this article, I’m going to discuss the advantages and disadvantages of this approach, as well as my personal opinion based on my experience. I want to say from the beginning that this article is subjective and not completely factual or objective – so take it for what it is. There is no general consensus on this matter precisely because it is a matter of personal taste.

Brace styles

Braces (or curly brackets) are a feature in just about any programming language that uses the C-style syntax, including C, C++, Java, C#, JavaScript, PHP, and many others. They define a scoped block that can be executed as a single statement as part of control flow (conditionals and loops). There are many different styles in which they can be used.

The Java folks seem to like this kind of style:

if (x == 0) {
    Console.WriteLine("x is zero");
}

The .NET camp, on the other hand, seems to prefer aligning braces vertically:

if (x == 0)
{
    Console.WriteLine("x is zero");
}

If you have just one statement, you can technically leave out the braces, so you can write your code like this:

if (x == 0)
    Console.WriteLine("x is zero");

…or like this.

if (x == 0) Console.WriteLine("x is zero");

Personally, I think the first and last options aren’t the best in terms of readability (especially when code becomes complex) so I’ll focus on the second and third. I normally use the second option (with braces) when I have multiple statements, and the third option (no braces) when I have just one. Many people recommend always using braces, and dismiss the third option as bad practice. Let’s take a look at the reasons why.

If you need to add statements, you’ll find the braces ready

So let’s take the same example as before, where you have this statement:

if (x == 0)
    Console.WriteLine("x is zero");

If you need to add additional statements to be executed as part of the conditional, the braces will have to be added anyway. Some people recommend always using braces¬†so that you’ll find them ready¬†when you need to add additional statements.

In that case, I suppose, we shouldn’t use empty element syntax in XML:

<RowDefinition Height="30" />

…and instead always write our tags in full:

<RowDefinition Height="30"></RowDefinition>

…simply because we might need to add something inside the element at some point. I think this is a very weak argument, because it disregards a language feature that may be very convenient, and at the same time bloats code with something that adds no meaning to the code. Take a look at the first two code snippets in this article – the one that uses braces is twice as long (in terms of lines) as the other one. And for what? Because people are too lazy to type in the braces when they are eventually needed? Wat.

Adding statements can be error-prone

Another reason why omitting braces is considered bad practice is that it may be easy to introduce logical errors when maintaining such code (see¬†this question on Programmers StackExchange¬†and this¬†other one on Stack Overflow). Let’s say you have this:

if (x == 0)
    Console.WriteLine("x is zero");

Then, you add an additional statement intended to be within the conditional, and you do it like this:

if (x == 0)
    Console.WriteLine("x is zero");
    Console.WriteLine(" which means it's neither positive nor negative");

Oops! The second Console.WriteLine() isn’t actually part of the conditional, so it always gets executed, no matter what. This is a valid argument. But let’s dissect it a little further.

First, let’s start again from our simple single-line conditional:

if (x == 0)
    Console.WriteLine("x is zero");

Now, if you want to add code at this point, you have two courses of action. If you want to add statements as part of the conditional, you know¬†that there’s just one statement and no braces, so adding them should be a pretty automatic response:

if (x == 0)
{
    Console.WriteLine("x is zero");
    Console.WriteLine(" which means it's neither positive nor negative");
}

On the other hand, if you want to add a statement that is not a part of the conditional, you add it at the same level as the if statement:

if (x == 0)
    Console.WriteLine("x is zero");
Console.WriteLine(" which means it's neither positive nor negative");

Even in absence of braces, the indentation shows clearly that one statement belongs to the conditional and the other does not. So actually, when seeing this kind of code:

if (x == 0)
    Console.WriteLine("x is zero");
    Console.WriteLine(" which means it's neither positive nor negative");

…I can’t help but think that the readability problem (which results in incorrect control flow) is one of indentation, not of whether to use braces or not.

I can certainly imagine beginning programmers making this kind of mistake, but I find it hard to believe that more seasoned programmers find it hard to read basic conditionals. As one of the answers to this question states:

“I even find it implausible that this should be a common mistake: blocks are a fundamental part of programming. Block level resolution and scoping is an automatic, ingrained mental process for programmers. The brain just does it (otherwise, reasoning about programming would be much harder). There is no additional mental effort required to remember putting the braces: the programmer also remembers to¬†indent¬†the newly added statement correctly, after all; so the programmer has already mentally processed that a block is involved.” — Konrad Rudolph

Also, one of the sections in this article states that:

“Programmers with enough discipline to always notice the braces (and put them in when needed) don’t need this idiom [always using braces].

“Auto-indent editors make it obvious whether your new statement is part of the¬†else¬†clause, making it unlikely you’ll have the bug this idiom tries to prevent.”

Summary

Personally, I think that using braces when they aren’t necessary is a waste of space, resulting in a lot of unnecessary lines of code. I use them when needed, and don’t use them for single statements. I find nothing wrong with omitting braces when they aren’t needed. This has worked for me for many years, and you may or may not agree with me. Different people find themselves comfortable using different approaches, and there is no general consensus on what is best.

So find out what works best for you, and don’t let anyone tell you how you should write your code based on subjective arguments. While you should definitely learn from more experienced programmers and best practices based on rational and logical arguments, be practical and don’t get too religious about your code.

Setting Connection Strings at Runtime with Entity Framework 5.0, Database First, VS2012

This article was originally posted here at Programmer’s Ranch on Saturday 16th November 2013. The syntax highlighting was added when the article was migrated here.

Hi everyone! ūüôā

This article deals with how to solve the problem of building and setting an Entity Framework connection string at runtime, based on a database-first approach (i.e. you have generated an Entity Data Model based on an existing database). You are expected to be familiar with ADO .NET and the Entity Framework. The first part of the article deals with setting up an Entity Data Model and simple interactions with it; this should appeal to all readers. The second part deals with the custom connection string issue, and will be helpful only to those who have actually run into that problem.

We’re going to be using Visual Studio 2012, and Entity Framework 5.0. Start a new Console Application so that you can follow along.

Setting up the database

You can use whatever database you want, but in my case I’m using SQL Server Compact edition (SQLCE). If you’re using something else and already have a database, you can just skip over this section.

Unlike many of the more popular databases such as SQL Server and MySQL, SQLCE is not a server and stores its data in a file with .sdf extension. This file can be queried and updated using regular SQL, but is not designed to handle things like concurrent users – something which isn’t a problem in our case. Such file-based databases are called embedded databases.

If you have Visual Studio, then you most likely already have SQLCE installed. Look for it in “C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0“. Under the Desktop¬†orPrivate¬†folders you’ll find a file called¬†System.Data.SqlServerCe.dll¬†which we need to interact with SQLCE. Add a reference to it from your Console Application.

Now, we’re going to create the database and a simple one-table schema. We’ll use good old ADO.NET for that. We’ll create the database only if it doesn’t exist already. First, add the following¬†usings at the top of Program.cs:

using System.IO;
using System.Data.SqlServerCe;

In Main(), add the following:

String filename = "people.sdf";
String connStr = "Data Source=" + filename;

Since SQLCE works with just a file, we can create a basic connection string using just the name of the file we’re working with.

The following code actually creates the database and a single table called person.

            try
            {
                // create database if it doesn't exist already

                if (!File.Exists(filename))
                {
                    // create the actual database file

                    using (SqlCeEngine engine = new SqlCeEngine(connStr))
                    {
                        engine.CreateDatabase();
                    }

                    // create the table schema

                    using (SqlCeConnection conn = new SqlCeConnection(connStr))
                    {
                        conn.Open();

                        String sql = @"create table person(
                                       id int identity not null primary key,
                                       name nvarchar(20),
                                       surname nvarchar(30)
                                   );";

                        using (SqlCeCommand command = new SqlCeCommand())
                        {
                            command.CommandText = sql;
                            command.Connection = conn;
                            int result = command.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

We first use SqlCeEngine to create the database file. Then we use ADO .NET to create the person table. Each row will have an auto-incrementing id (primary key), as well as a name and surname. Note that SQLCE does not support the varchar type, so we have to use nvarchar (Unicode) instead.

If you now build and run the application, you should find a people.sdf file in the bin\Debug folder. We’ll use that to create an Entity Data Model for the Entity Framework.

Creating the Data Model

Right click on the project and select Add -> New Item…:

cs-efconnstr-addnewitem

From the Data¬†category, select ADO.NET Entity Data Model. You can choose a name for it, or just leave it as the default Model1.edmx; it doesn’t really matter.

cs-efconnstr-addedm

Click The Add button. This brings up the Entity Data Model Wizard.

cs-efconnstr-edmwiz1

The “Generate from database” option is the default selection, so just click Next.

cs-efconnstr-edmwiz2

Hit the New Connection…¬†button to bring up the Connection Properties¬†window.

cs-efconnstr-connprop

If SQL Server Compact 4.0 is not already selected as the Data source, click the Change…¬†button and select it from the Change Data Source¬†window:

cs-efconnstr-changeds

Back in the Connection Properties¬†window, click the Browse…¬†button and locate the people.sdf¬†file in your bin\Debug folder that we generated in the previous section. Leave the Password¬†field empty, and click Test Connection. If all is well, you’ll get a message box saying that the test succeeded.

Once you click OK, the Entity Data Model Wizard should become populated with a connection string and a default name for the model:

cs-efconnstr-edmwiz3

When you click Next, you’ll get the following message:

cs-efconnstr-localdata

Just click Yes and get on with it. In the next step, import the person table into your model by ticking the checkbox next to it:

cs-efconnstr-edmwiz4

Click Finish. The files for your model are added to the project. You may also get the following warning:

cs-efconnstr-security-warning

You¬†don’t have to worry about it. Just click OK. If you click Cancel¬†instead, you won’t have the necessary autogenerated code that you need for this project.

Interacting with the database using the Entity Framework

After the database-creation code from the first section, and before the end of the try scope, add the following code:

// interact with the database

using (peopleEntities db = new peopleEntities())
{
    db.people.Add(new person() { name = "John", surname = "Smith" });
    db.SaveChanges();

    foreach (person p in db.people)
    {
        Console.WriteLine("{0} {1} {2}", p.id, p.name, p.surname);
    }
}

Here, we create an instance of our entity context (peopleEntities) and then use it to interact with the database. We add a new row to the person table, and then commit the change via db.SaveChanges(). Finally, We retrieve all rows from the table and display them.

Also, add the following at the end of the Main() method so that we can see the output:

Console.ReadLine();

Run the program by pressing F5. The output shows that a row was indeed added:

cs-efconnstr-output1

The Entity Framework knows where to find the database because it has a connection string in the App.config file:

  <connectionStrings>
    <add name="peopleEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=|DataDirectory|\people.sdf&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

This might be good enough in some situations, but other times, we might want to build such connection string in code and ask the Entity Framework to work with it. A reason for this might be because the connection string contains a password, and you want to obtain it from an encrypted source. The following two sections illustrate how this is done.

Building a raw Entity Framework connection string

Let’s start out by commenting out the connection string in the App.config file:

  <connectionStrings>
    <!--
    <add name="peopleEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=|DataDirectory|\people.sdf&quot;" providerName="System.Data.EntityClient" />
    -->
  </connectionStrings>

If you try running the program now, you’ll get a nice exception.

Now, what we want to do is add the connection string into our code and pass it to the entity context (the peopleEntities). So before our Entity Framework code (which starts with¬†using (peopleEntities…), add the following:

String entityConnStr = @"metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&amp;quot;data source=|DataDirectory|\people.sdf&quot;";

If you now try to pass this connection string to the peopleEntities¬†constructor, you’ll realise that you can’t. You can see why if you expand Model1.edmx and then Model1.Context.tt in Solution Explorer, and finally open the Model1.Context.cs¬†file:

cs-efconnstr-dbcontext

The peopleEntities class has only a parameterless constructor, and it calls the constructor of DbContext with the connection string name defined in App.config. The DbContext constructor may accept a connection string instead, but we have no way of passing it through peopleEntities directly.

While you could add another constructor to peopleEntities, it is never a good idea to modify autogenerated code. If you regenerate the model, any code you add would be lost. Fortunately, however, peopleEntities is a partial class, which means we can add implementation to it in a separate file (see this question and this other question on Stack Overflow).

Add a new class and name it peopleEntities. Add the following at the top:

using System.Data.Entity;

Implement the class as follows:

    public partial class peopleEntities : DbContext
    {
        public peopleEntities(String connectionString)
            : base(connectionString)
        {

        }
    }

We can now modify our instantiation of peopleEntities to use our connection string as defined in code:

using (peopleEntities db = new peopleEntities(entityConnStr))

Since we are using a partial class defined in a separate file, any changes to the model will cause the autogenerated peopleEntities to be recreated, but will not touch the code we added in peopleEntities.cs.

When we run the program, we now get a very nice exception (though different from what we got right after commenting out the connection string in App.config):

cs-efconnstr-output2

Apparently this happens because of the &quot; values, which are necessary in XML files but cause problems when supplied in a String literal in code. We can replace them with single quotes instead, as follows:

String entityConnStr = @"metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string='data source=|DataDirectory|\people.sdf'";

If we run the program now, it works fine, and a new row is added and retrieved:

cs-efconnstr-output3

Using EntityConnectionStringBuilder

You’ll notice that the connection string we’ve been using is made up of three parts: metadata, provider, and the provider connection string that we normally use with ADO.NET.

We can use a class called EntityConnectionStringBuilder to provide these values separately and build a connection string. Using this approach avoids the problem with quotes illustrated at the end of the previous section.

First, remove or comment out the entityConnStr variable we have been using so far.

Then add the following near the top of Program.cs:

using System.Data.EntityClient;

Finally, add the following code instead of the connection string code we just removed:

EntityConnectionStringBuilder csb = new EntityConnectionStringBuilder();
csb.Metadata = "res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
csb.Provider = "System.Data.SqlServerCe.4.0";
csb.ProviderConnectionString = "data source=people.sdf";
String entityConnStr = csb.ToString();

When you run the program, it should work just as well:

cs-efconnstr-output4

Summary

This article covered quite a bit of ground:

  • We first used the SqlceEngine and ADO .NET to create a SQL Server Compact database.
  • We then created an Entity Data Model for this database.
  • We added some code to add rows and retrieve data using the Entity Framework.
  • We provided the Entity Framework with a raw connection string in code. To do this, we used a partial class to add a new constructor to the entity context class that can pass the connection string to the parent DbContext. We also observed a problem with using &quot; in the connection string, and solved it by using single quotes instead.
  • We used EntityConnectionStringBuilder to build a connection string from its constituent parts, and in doing so completely avoided the &quot; problem.

I hope you found this useful. Feel free to leave any feedback in the comments below. Check back for more articles! ūüôā

ASP .NET Web API: A Gentle Introduction

This article was originally posted here at Programmer’s Ranch on 1st August 2014.

Hello! ūüôā

Last year, we saw how to intercept HTTP requests in Wireshark, and also how to construct them. As you already know, HTTP is used mainly to retrieve content from the Web; however it is capable of much more than that. In this article, we will learn how HTTP can be used to expose an API that will allow clients to interact with back-end services.

Ideally, you should be using Visual Studio 2013 (VS2013) or later. If you’re using something different, the steps may vary.

Right, so fire up VS2013, and create a new ASP .NET Web Application. In VS2013, Microsoft united various different kinds of web projects under a single banner, which is what people mean when they refer to something called “One ASP .NET“. So there isn’t that much choice in terms of project types:

webapi-intro-newproject

You are given some sort of choice once you click “OK”, however:

webapi-intro-newproject-template

At this stage there are various web project types you can choose from, and in this case you need to select “Web API”. You’ll notice that the “MVC” and “Web API” checkboxes are selected and you can’t change that. That’s because Web API is somewhat based on the ASP .NET MVC technology. Web API is sort of MVC without the View part, so discussing MVC is beyond the scope of this article; however just keep that in mind in case you ever dive into MVC.

Once you click “OK” and create your project, you’ll find a whole load of stuff in your Solution Explorer:

webapi-intro-newproject-created

This may already seem a little confusing. After all, where should we start from? Let’s ignore the code for a moment and press F5 to load up our web application in a browser. This is what we get:

webapi-intro-initialrun-homepage

You’ll notice there is an “API” link at the top. Clicking it takes you to this awesome help page, where things start to clear up:

webapi-intro-initialrun-help

It turns out that the Web API project comes with some sample code that you can work with out of the box, and this help page is telling you how to interact with it. If you look at the first entry, which says “GET api/Values”, that’s something we can point the browser to and see the web application return something:

webapi-intro-initialrun-values

And similarly, we can use the second form (“GET api/Values/{id}”) to retrieve a single item with the specified ID. So if you point your browser to /api/Values/1, you should get the first one:

webapi-intro-initialrun-values-1

That’s all well and good, but where are these values coming from? Let’s go back to the code, and open up the Controllers folder, and then the ValuesController in it:

webapi-intro-initialrun-valuescontroller

You can see how there is a method corresponding to each of the items we saw in the help page. The ASP .NET Web API takes the URL you enter in the web browser and tries to route the request to a method on a controller. So if you’re sending a GET request to /api/Values/, then it’s going to look for a method called Get() in a controller called ValuesController.

Notice how the “Controller” part is omitted from the URL. This is one of many things in Web API that you’re expected to sort of take as obvious – Web API uses something called “convention over configuration”, which is a cool way of saying “it just works that way, and by some kind of magic you should already know that, and good luck trying to change it”. If you’ve read my¬†article about Mystery Meat Navigation, part of which addresses the Windows 8 “content over chrome” design, you’ll notice it’s not very different.

And since, at this point, we have digressed into discussing big buzzphrases designed to impress developers, let’s learn about yet another buzzword: REST. When we use HTTP to browse the web, we mainly use just the GET and POST request methods. But HTTP supports¬†several other request methods. If we take four of them – POST, GET, PUT and DELETE, these map quite smoothly to the CRUD (Create, Read, Update and Delete) operations we know so well from just about any business application. And using these four request methods, we can build APIs that allow us to work with just about any object. That’s what is meant by¬†REST, and is the idea on which the ASP .NET Web API is built. “How I Explained REST to My Wife” is a really good informal explanation of REST, if you want to learn more about it. The irritating thing is that the concept is so simple, yet it’s really hard to find a practical explanation on the web on what REST actually means.

To see this in action, let’s rename our ValuesController to BooksController so that it’s less vague. We’ll also need a sort of simple database to store our records, so let’s declare a static list in our BooksController class:

        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"
        };

Now we can change our Get() methods to return items from our collection. I’m going to leave out error checking altogether to keep this really simple:

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];
        }

We can test this in the browser to see that it works fine:

webapi-intro-books-get

Great! We can now take care of our Create (POST), Update (PUT) and Delete (DELETE) operations by updating the methods accordingly:

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);
        }

Good enough, but how are we going to test these? A browser uses a GET request when you browse to a webpage, so we need something to send POST, PUT and DELETE requests. A really good tool for this is Telerik’s¬†Fiddler.¬†Postman, a Chrome extension, is also a pretty good REST client.

First, make sure that the Web API is running (F5). Then, start Fiddler. We can easily send requests by entering the request method, the URL, any HTTP headers, in some cases a body, and hitting the Execute button. Let’s see what happens when we try to POST a new book title to our controller:

webapi-fiddler-post1

So here we tried to send a POST request to http://localhost:1817/api/Books, with “The Art of War” in the body. The headers were automatically added by Fiddler. Upon sending this request, an HTTP 415 response appeared in the left pane. What does this mean? To find out, double-click on it:

webapi-fiddler-http415

You can see that HTTP 415 means “Unsupported Media Type”. That’s because we’re sending a string in the body, but we’re not specifying how the Web API should interpret that data. To fix this, add the following header to your request in Fiddler:

Content-Type: application/json

When you send the POST request with this header, you should get an HTTP 204, which means “No Content” – that’s because our Post() method returns void, and thus nothing needs to be returned. We can check that our new book title was added by sending a GET request to http://localhost:1817/api/Books, which now gives us the following in response:

webapi-fiddler-after-post

We can similarly test PUT and DELETE:

  • Sending a PUT request to http://localhost:1817/api/Books/1 with “The Prince by Niccolo’ Machiavelli” in the body updates that entry.
  • Sending a DELETE request to¬†http://localhost:1817/api/Books/0 deletes “How to Win Friends and Influence People”, the first book in our list.
  • Sending a GET request to¬†http://localhost:1817/api/Books again shows the modified list:

webapi-fiddler-after-all

Fantastic! In this unusually long article, we have learned the basics of working with the ASP .NET Web API. Lessons learned include:

  • The ASP .NET Web API is based on the REST concept.
  • The REST concept simply means that you use HTTP POST, GET, PUT and DELETE to represent Create, Read, Update and Delete operations respectively.
  • For each object you want to work with, you create a Controller class.
  • Appropriately named methods in this Controller class give you access to the CRUD operations mentioned above.
  • Use Fiddler or Postman to construct and send HTTP requests to your Web API in order to test it.
  • Add a content type header whenever you need to send something in the body (POST and PUT requests).

Thanks for reading, and please share this with your friends! Below is the full code of the BookController class for ease of reference.

    public class BooksController : ApiController
    {
        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"
        };

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];
        }

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);
        }
    }

Determining the bitness (x86 or x64) of a DLL

This article was originally posted here at Programmer’s Ranch on 28th September 2014.

Hello guys and gals! ūüôā

In this article, we’re going to tackle a pretty frustrating scenario: making sure all your .NET assemblies or even native DLLs target the same architecture. At the time of writing, applications tend to be targeted at x86 or x64 architectures, or both. However, mixing DLLs or executables compiled for different architectures is a recipe for disaster. This kind of disaster, in fact:

bitness-badimageformatexception
That’s a BadImageFormatException, saying:

An unhandled exception of type ‘System.BadImageFormatException‘ occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
Additional information: Could not load file or assembly ‘ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

This is why it’s happening:

bitness-mixed-architecture

That’s a very, very stupid thing to do, having an x64 console application depend on an x86 class library (or DLL). Remember:

bitness-dont-mix-architectures

Great, now you know. But you’re bound to run into the BadImageFormatException problem anyway, because while it’s easy to control the bitness of the assemblies in your project, you often depend on DLLs provided by third parties, and their own bitness isn’t clearly defined. Unfortunately, you can’t rely on rightclick -> Properties -> Details because that doesn’t give you the bitness at all.

Fortunately, however, there are tools you can use to find out what architecture those DLLs are compiled for.

Let’s start off with .NET assemblies. If the DLL in question is a .NET assembly, you can¬†use the corflags utility¬†to find out the bitness. corflags is part of the Visual Studio developer tools, so you’ll first need to start a Visual Studio developer command prompt (see¬†this StackOverflow thread¬†or search Windows for CorFlags.exe¬†in case you can’t find one from the Start menu).

Once you’ve located CorFlags.exe or have a Visual Studio developer command prompt, runCorFlags.exe¬†with the full path to the DLL you want to inspect, and check the 32BIT¬†setting in the output:

bitness-corflags

Now CorFlags.exe works great to find out the architecture of a .NET assembly, but can’t tell you the architecture of a native DLL. This is what happens if you try to use it with SDL2.dll, for instance:

bitness-corflags-native

For unmanaged/native DLLs, we can instead¬†use dumpbin. This will spit out a bunch of information, so you can find the architecture quickly if you filter the information by including only the line containing the word “machine”, as the linked Stack Overflow answer suggests:

bitness-dumpbin

So there you go – this article has presented two different ways to check the bitness or CPU architecture of managed and unmanaged DLLs respectively, which helps when troubleshooting those dreaded BadImageFormatExceptions. In reality this article is a consolidation of the information in the two Stack Overflow threads linked above, and I would like to thank the authors because I have found their tips useful on many occasions.

Authenticating with Active Directory

This article was originally posted here at Programmer’s Ranch on 14th March 2014.

Hi! ūüôā

If you work in a corporate environment, chances are that your Windows machine is connected to a domain based on¬†Active Directory. In today’s article, we’re going to write a very simple program that allows us to verify a user’s credentials for the domain using Active Directory.

In order to try this out, you’re going to need an Active Directory domain. In my case, I installed Windows Server 2008 R2 and¬†followed these instructions¬†to set up a domain, which I called “ranch.local”. You may also be able to connect to your domain at work to save yourself the trouble of setting this up.

Let us now create a new Console Application using either SharpDevelop or Visual Studio. After adding a reference to System.DirectoryServices.AccountManagement, add the following statement near the top of your Program.cs file:

using System.DirectoryServices.AccountManagement;

Next, remove any code in Main() and add a simple prompt for the username and password to authenticate against Active Directory:

// prompt for username

Console.Write("Username: ");
string username = Console.ReadLine();

// prompt for password

Console.Write("Password: ");
string password = Console.ReadLine();

For the authentication part, we can use a simple method described here. After obtaining a reference to the domain using the PrincipalContext class (specifying the domain as a parameter), we simply use the ValidateCredentials() method to perform the authentication. This gives us a boolean value indicating whether the authentication was successful or not.

// authenticate

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "RANCH"))
{
    bool authenticated = pc.ValidateCredentials(username, password);

    if (authenticated)
        Console.WriteLine("Authenticated");
    else
        Console.WriteLine("Get lost.");
}

At this point, we need only add a simple statement to wait for user input before letting the application terminate:

Console.ReadLine();

Now, we can build our application and test it on the server (or on any machine that is part of the domain). First, let’s try a valid login:

csadauth-valid

Very good! And now, a user that doesn’t even exist:

csadauth-invalid

Excellent! As you can see, it only takes a couple of lines of code to perform authentication against Active Directory. I hope you found this useful. Follow the Ranch to read more articles like this! ūüôā

SignalR Scaleout with Redis Backplane

Introduction

In “Getting Started with SignalR“, I provided a gentle introduction to SignalR with a few simple and practical examples. The overwhelming response showed that I’m not alone in thinking this is an awesome technology enabling real-time push notifications over the web.

Web applications often face the challenge of having to scale to handle large amounts of clients, and SignalR applications are no exception. In this example, we’ll see one way of scaling out SignalR applications using something called a backplane.

Scaleout in SignalR

SignalRScaleout

Introduction to Scaleout in SignalR” (official documentation) describes how SignalR applications can use several servers to handle increasing numbers of clients. When a server needs to push an update, it first pushes it over a message bus called a backplane. This delivers it to the other servers, which can then forward the update to their respective clients.

According to the official documentation, scaleout is supported using Azure, Redis or SQL Server as backplanes. Third-party packages exist to support other channels, such as SignalR.RabbitMq.

Scaleout Example using Redis

Introduction to Scaleout in SignalR” (official documentation) describes how to use SignalR as a backplane. To demonstrate this, I’ll build on the¬†Chat Example code¬†from my “Getting Started with SignalR” article.

All we need to scaleout using Redis is install the Microsoft.AspNet.SignalR.Redis NuGet package, and then set it up in the Startup class as follows:

        public void Configuration(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.UseRedis("192.168.1.66", 6379, null, "SignalRChat");
            app.MapSignalR();
        }

In the code above, I am specifying the host and port of the Redis server, the password (in this case null because I don’t have one), and the name of the pub/sub channel that SignalR will use to distribute messages.

To test this, you can get a Redis server from the Redis download page. Redis releases for Windows exist and are great for testing stuff, but remember they aren’t officially supported for production environments.

Now to actually test it, I’ve set up the same scaleout-enhanced chat application on two different machines, and subscribed to the Redis pub/sub channel:

signalr-scaleout-computer1

Watching the pub/sub channel reveals what SignalR is doing under the hood. There are particular messages going through when the application initializes on each machine, and you can also see the actual data messages going through. So when you write a message in the chat, you can also see it in the pub/sub channel.

But even better than that, you’ll also see it on the client (browser) that’s hooked up to the other machine:

signalr-scaleout-computer2

The magic you need to appreciate here is that these aren’t two browsers connected to the same server; they are actually communicating with different servers on different machines. And despite that, the messages manage to reach all clients thanks to the backplane, which in this case is Redis.

Caveats

So I’ve shown how it’s really easy to scale out SignalR to multiple servers: you need to install a NuGet package and add a line of code. And I’ve actually tested it on two machines.

stash-1-244250d58073b0ed1

But that’s not really scaleout. I don’t have the resources to do large-scale testing, and only intended to show how scaleout is implemented with this article. The actual benefits of scaleout depend on the application. As the official documentation warns, the addition of a backplane incurs overhead and can become a bottleneck in some scenarios. You really need to study whether your application is a good fit for this kind of scaleout before going for it.

Getting Started with SignalR

Introduction

SignalR is an open source .NET library enabling real-time broadcasts of data on the web. Typical example applications include chats, stock tickers, and even games. It does this by leveraging and abstracting a number of different technologies, choosing the most suitable transport mechanism based on what the client and server support (since WebSocket support is not yet widespread).

At the time of writing this article, SignalR v2 is the latest implementation, but SignalR v3 is in beta along with ASP .NET 5. I’ll be using VS2015 for this article.

In this article, we’ll cover some really simple examples that will get you up and running fast.

The source code for this article is available on the Gigi Labs BitBucket repository:

Setting up a SignalR Hub

Create a new ASP .NET Web Application, and choose the Empty template. I’m using the one under ASP .NET 4.5.2 since ASP .NET 5 is still a preview at the time of writing this article:

signalr-empty-application

Next, you’ll need to add a SignalR Hub (screenshot below). A hub is a publish/subscribe implementation, and automatically tracks connections. Additionally, it provides ways of calling methods on clients, and selecting which clients to broadcast to – we’ll see how this works shortly.

signalr-add-hub

Adding the hub not only adds a class for the hub, but also gives you a basic method and also adds scripts needed for SignalR to run:

signalr-added-hub-scripts

Next, add an OWIN Startup Class:

signalr-add-owin-startup-class

In this class, just set up SignalR in the Configuration() method:

        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }

Good! Now we’re all set to create our examples. We’ll also need some client code, so add an empty HTML page called index.html. Right click it in Solution Explorer, and select “Set as Start Page” so it will be automatically loaded when you hit F5 to debug.

Basic Hello World Example

When we added our Hub, we got some initial code:

        public void Hello()
        {
            Clients.All.hello();
        }

This works as follows: when a client calls this Hello() method on the server (Hub), the hub will call a hello() method on all the connected clients. We can use this example code as-is, but we need to create some client code.

First, add the following structure to index.html:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Example 1</title>
	<meta charset="utf-8" />
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <script src="signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            // TODO client code goes here
        });
    </script>
</head>
<body>
    <div id="log"></div>
</body>
</html>

There are three things to notice here. First, we have a few references to JavaScript files – the versions need to match the ones in the Scripts folder. The signalr/hubs reference is autogenerated, so you don’t have to worry about it. Secondly, there is a placeholder for Javascript client code which we’ll add next. Finally, we have a “log” div which is where we’ll dump any output received from the server.

For the client code, we first need a reference to the hub itself:

var myHub = $.connection.myHub1;

Next, we add the method on the client that the server will call whenever it needs to broadcast something:

            myHub.client.hello = function () {
                $("#log").append("Hello <br />");
            }

Finally, we add code to initialize the hub itself, and when the initialization is complete, we will call the method on the server. This will in turn cause the client method above to be called:

            $.connection.hub.start().done(function () {
                myHub.server.hello();
            });

We can now test this and see that we get a Hello response from the server:

signalr-hello-1

More importantly, if we open a second browser window on the same URL, you’ll notice that both windows will get a new Hello response. That’s because the server/hub is broadcasting to all clients whenever a client calls its Hello() method.

signalr-hello-2

Chat Example

Creating a chat server is not much more complex than this. In fact it’s a typical example of SignalR usage, and you can check out the official tutorial if you like.

For this example, I’ve created a new project with a new Hub:

    public class ChatHub : Hub
    {
        public void Broadcast(string message)
        {
            Clients.All.receive(Context.ConnectionId, message);
        }
    }

Some names have changed, but it’s mostly the same as before. One thing you’ll notice that’s different, though, is that Context.ConnectionId. It’s SignalR’s way of giving you the connectionId of the client who called the server/hub method, and I’m using it to distinguish between clients in the chat (as opposed to the official tutorial which prompts for a name).

On the client side, things have also changed slightly. In the HTML body, I’ve added an input field and a send button:

<body>
    <input id="message" type="text" />
    <button id="send">Send</button>
    <div id="log"></div>
</body>

In the client JavaScript code, as before, we’re first getting a reference to the hub (different name this time):

var chatHub = $.connection.chatHub;

Then we add the method that the server will call on the client. Remember, the signature must match what we declared on the hub. In this case we’re passing in connectionId and message, and then displaying them:

            chatHub.client.receive = function (connectionId, message) {
                $("#log").append("<strong>User " + connectionId
                    + " wrote:</strong>" + message + " <br />");
            }

Then we add the hub initialization code, together with any actions we want to carry out post-initialization. In this case, we set up a handler for when the user sends a message:

            $.connection.hub.start().done(function () {
                $("#send").on("click", function () {
                    var message = $('#message').val();
                    chatHub.server.broadcast(message);
                })
            });

There’s nothing keeping us from adding further logic to show when someone joins the chat, for instance. But let’s keep this super-simple.

We can now test this:

signalr-chat-test

Stock Ticker Example

The previous examples show broadcasts to clients triggered by the clients themselves. There are many scenarios where it makes sense for the server to spontaneously send updates to clients – a stock ticker is a common example (see official tutorial).

For this example, I’ve again created a new project and a new Hub. Since the server will spontaneously send updates to clients, the hub does not need to expose any methods:

    public class StockTickerHub : Hub
    {

    }

Instead, we’ll have a thread that periodically sends updates to the clients of that hub. Since I have no better place to put this, it’s going in the Startup class:

    public class Startup
    {
        private static Thread stockTickerThread = new Thread(() =>
            {
                var stockTickerHub = GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>();

                while (true)
                {
                    stockTickerHub.Clients.All.update(5);
                    Thread.Sleep(1000);
                }
            });

        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();

            stockTickerThread.Start();
        }
    }

The important thing to notice here is how we’re getting a reference to the hub via GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>(). Since I’m more concerned with demonstrating how to use SignalR than any stock ticker logic, I’m just sending a fixed value of 5 every second.

The client code is practically the same as the first example, except that we don’t need to do anything once the hub is initialized:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Example 3</title>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
    <script src="signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var stockTickerHub = $.connection.stockTickerHub;

            stockTickerHub.client.update = function (value) {
                $("#log").append(value + "<br />");
            }

            $.connection.hub.start().done(function () {
                
            });
        });
    </script>
</head>
<body>
    <div id="log"></div>
</body>
</html>

We can now test that the spontaneous updates are received:

signalr-stockticker-test

Beyond this Article

This article showed basic usage of SignalR. I intentionally kept the examples really simple so that you could get up and running in no time.

Having said that, there’s a lot more to SignalR than we’ve seen here. For instance, we’ve always broadcasted to all clients. SignalR allows you to choose which clients to send to, for example you can send to a specific client, or to clients subscribed to a particular topic. That’s beyond the scope of this article, so if you want to know more about SignalR, check out the multitude of resources on the net.

Getting Started with RabbitMQ with .NET

This article contains some instructions to make it easy for people to jump into the wonderful world of message queues with RabbitMQ. Its purpose is not to provide any in-depth explanations, as I’m pretty new to the topic myself. ūüôā

RabbitMQ is built on Erlang, so you’ll need to install that first:

rabbitmq-download-erlang

You can then download and install RabbitMQ itself:

rabbitmq-download-rabbitmq

Next, you should install the management plugin. This provides a web UI allowing you to manage your queue and perform basic testing (e.g. publish messages).

To do this, navigate to the folder where you installed RabbitMQ, and go into the sbin folder. From here, enter the following command:

rabbitmq-plugins enable rabbitmq_management

Once that is installed, you can access the administrative web UI by going to http://localhost:15672/ with username guest and password guest. Go to the Queues tab and create a new queue:

rabbitmq-add-queue

You’ll now see the new queue listed under “All queues”. Click on the name to select it. This will allow you to view information about the queue (including statistics, such as the number of messages in the queue) and perform a number of operations (including publishing messages).

But before we do that, let’s create a simple client in .NET that can subscribe to the queue and consume any messages we publish. Some basic code is available in this tutorial, so we can just install the RabbitMQ.Client NuGet package and then write some code based on it:

        static void Main(string[] args)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };

            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("testqueue", true, false, false, null);

                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += Consumer_Received;
                    channel.BasicConsume("testqueue", true, consumer);

                    Console.ReadLine();
                }
            }
        }

        private static void Consumer_Received(object sender, BasicDeliverEventArgs e)
        {
            var body = e.Body;
            var content = Encoding.UTF8.GetString(body);
            Console.WriteLine(content);
        }

We can now run this client, and leave it waiting for messages.

To test it, let’s publish a message from the RabbitMQ management web UI:

rabbitmq-publish-message

You can see from the client that the message has been received:

rabbitmq-consume-message

So that shows in a very basic way how you can setup RabbitMQ on Windows, publish messages from the management web UI, and consume messages by writing a simple .NET client.

Update 2nd March 2016: If the management plugin fails to install with something like “unable to contact node”, here are a few things you can try: