Microsoft Message Queuing

MSMQ (Microsoft Message Queuing) is a message queue that is available by default as part of Windows. A reliable way of sending and receiving messages across computer systems, MSMQ provides a queue that’s scalable, thread-safe, simple, and convenient to use while at the same time providing you with the opportunity to persist the messages inside the Windows database. Continue reading Microsoft Message Queuing

Creating API Help Pages

Install ASP.NET and Web Tools 2012.2 Update. This update integrates help pages into the Web API project template.

Next, create a new ASP.NET MVC 4 project and select the Web API project template. The project template creates an example API controller named ValuesController. The template also creates the API help pages. All of the code files for the help page are placed in the Areas folder of the project.


Continue reading Creating API Help Pages

Bing Maps in an MVC Application

Here is a simple example of how to use Bing Maps in an MVC application.

I am using Bing Maps V8 which is the current version of Microsoft.

Also, nothing that document.ready will fire long before the map script loads as it loads asynchronously.  Sometimes document.ready will fire before the page is loaded which means the map div might not even be available. To overcome this, we are using the callback parameter of the map script UR: for example:

http://www.bing.com/api/maps/mapcontrol?callback=LoadMap
Continue reading Bing Maps in an MVC Application

Caching to improve the user experience

(Added LazyCache in to the Testing)

One of the essential factors in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or even parts of a page in memory the initial time they are requested. You can save these items on the Web server or other software in the request stream, such as a proxy server or at the browser. This allows you to avoid recreating information that satisfied a previous request. Known as caching, it will enable you to use many techniques to store page output or application data across HTTP requests and reuse it. When the server does not have to recreate information you save time and resources, and throughput and scalability increase.

It is possible to obtain significant performance improvements in ASP.NET applications by caching frequently requested objects and data in either the Application or Cache classes. While the Cache class indeed offers far more flexibility and control, it only appears to provide a marginal advantage regarding increased throughput over the Application class for caching. It would be challenging to develop a testing scheme that could accurately measure the potential benefits of the Cache class’s built-in management of lesser-used objects through the scavenging process as opposed to the fact that Application does not offer this feature. The developer needs to decide this case and should be based on the needs and convenience of the project and its usage patterns.

In the article, I’ll be looking at the application caching and what is the most effective and scalable options.  If you would like to know more about the web caching then take a look at the Microsoft Caching Architecture Guide for .NET Framework Applications

So we all know that caching increases performance, what I am not getting into here is when it should be used or when it shouldn’t be used.  I’m more interested in the performance and scalability of the caching used.

The performance testing I am going to use the following different caching methods:

I’ve tried to provide some different options that are available for Caching, if you know of any others, please let me know and I’ll add them to this post.

There are two types of tests I am using a small test which waits for 30 milliseconds and then returns back the current date and time:

Thread.Sleep(30);
return System.DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);

then a test to generate a much large object of 267 Mb

public IEnumerable<Block> GetData()
{
    // should eat around 267 Mb of RAM.
    var blocks = new Block[512 * 512 * 1];

    for (var i = 0; i < (512 * 512) * 1; i++)
    {
        blocks[i] = new Block();
    }
    return blocks;
}

Both are straightforward tests, by no means are they an accurate representation of real-world methods, but they do show you how it affects the performance when using different Caching.

The idea is to iterate around these test 1,000 times and record how long it takes for each test, what I don’t do here is work out the amount of memory is being used (if you know of an easy way to include this, please let me know).

I won’t go into great details here on the results of the tests as I think you’ll find them self-explanatory in the test application, attached at the bottom of this post.

Few things to note about the testing and results is that you should use a Paralling process for the examination, as this will be much closer to the real world multi-threading environment.

Also, careful consideration should be given to using locking in the Cache module, as you don’t want the same cache key function running while another one is trying to process the same function, it should wait until the process has finished and stored it into the cache to increase performance.

Here is the sample code with different sample tests showing how useful each option is

Cache

SignalR – the right way

It has been quite sometime that SignalR has been around, 2014, so why are not more people using it? First what is SignalR?

ASP.NET SignalR is a library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available. SignalR supports Web Sockets and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorisation.

For further information check https://www.asp.net/signalr

Could it because people just don’t get it or really understand what it can do, or perhaps they hit issues without realising they don’t understand the structure?  Whatever the reason people are not using SignalR, I’m going to provide a useful sample application to get you off on the right footing.

There are a lot of different samples and information on how to use SignalR, but I’m always a firm believer of KISS (Keep It Simple Stupid).

There are two primary sides to SignalR, the client side and the server hubs, here I have created an MVC application with Individual User Accounts for Authentication.

First, add the SignalR NuGet package

Install-Package Microsoft.AspNet.SignalR

Then we need to map the Hubs connection to the application.

To enable SignalR in your application, create a class called Startup with the following:

using Microsoft.Owin;
using Owin;
using MyWebApplication;

namespace MyWebApplication
{
 public class Startup
 {
   public void Configuration(IAppBuilder app)
   {
     app.MapSignalR();
   }
 }
}

What is important here is that app.MapSignalR() is the last to be called, and this is because any changes to the app need to be done before you call the mapping.  The incorrect order got me once when we had some custom Authentication, and it was not being passed to SignalR hubs.

I won’t be going into how you go about setting up the step by step process, as this is documented in many places, and also comes in the readme.txt file as part of the NuGet package.

What I will be adding is the Authorization to the project, which is covered by Microsoft in Authentication and Authorization for SignalR Hubs.

What is important to note how the connection is handled, we are using a class called SignalRConnectionManager, and this controls the connections based on the username coming from the context and the connection id which also comes from the context.

 

public class SignalRConnectionManager<T> : IDisposable
 {
 private readonly ConcurrentDictionary<T, HashSet<string>> _connections = new ConcurrentDictionary<T, HashSet<string>>();

public int Count { get { return _connections.Count; } }

/// <summary>
 /// Attempts to add the specified userid and connectionid
 /// </summary>
 public void Add(T userid, string connectionid)
 {
 HashSet<string> connections = _connections.GetOrAdd(userid, new HashSet<string>());

lock (connections)
 {
 connections.Add(connectionid);
 }
 }

public IEnumerable<string> Connections(T userid)
 {
 HashSet<string> connections;
 if (_connections.TryGetValue(userid, out connections))
 {
 return connections;
 }

return Enumerable.Empty<string>();
 }

public IEnumerable<T> UserIds()
 {
 return _connections.Keys;
 }

/// <summary>
 /// Attempts to remove a connectionid that has the specified userid
 /// </summary>
 public void Remove(T userid, string connectionid)
 {
 HashSet<string> connections;
 if (!_connections.TryGetValue(userid, out connections))
 {
 return;
 }

lock (connections)
 {
 connections.Remove(connectionid);

if (connections.Count == 0)
 {
 HashSet<string> emptyConnections;
 _connections.TryRemove(userid, out emptyConnections);
 }
 }
 }

#region IDisposable Support

private bool disposedValue = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
 {
 if (!disposedValue)
 {
 if (disposing)
 {
 _connections.Clear();
 }

// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
 // TODO: set large fields to null.

disposedValue = true;
 }
 }

// This code added to correctly implement the disposable pattern.
 public void Dispose()
 {
 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
 Dispose(true);
 // TODO: uncomment the following line if the finalizer is overridden above.
 // GC.SuppressFinalize(this);
 }

#endregion IDisposable Support
 }

Client Code

In my case I’m going to be looking at JavaScript within a C# MVC application, which looks like this:

<p>SignalR</p>
<!--The jQuery library is required. -->
<script src="~/Scripts/jquery-1.10.2.js"></script>
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.3.min.js"></script>
<!--Reference the auto generated SignalR hub script. -->
<script src="~/signalr/hubs"></script>

<!--Add script to update the page and send messages - SignalR - HeartBeat.-->
<script type="text/javascript">
 $(function () {
 // Declare a proxy to reference the hub.
 var heartBeat = $.connection.heartBeatHub;

heartBeat.client.broadcastMessage = function (html) {
 $('#message').html(html).fadeIn();
 };

if ($.connection.hub && $.connection.hub.state === $.signalR.connectionState.disconnected) {
 $.connection.hub.start()
 .done(function () {
 console.log('SignalR now connected, connection ID=' + $.connection.hub.id);
 heartBeat.server.send('Heart beat listening');
 console.log("Heart beat started")
 })
 .fail(function () { console.log('Could not Connect!'); });
 }
 });
</script>
<div id="message">
</div>

two important lines in this code are:

Reference the auto generated SignalR hub script

<script src="~/signalr/hubs"></script>

Declaring the proxy to reference the hub, you’ll notice the case of the letter ‘h’ is different the the C# code, this is important otherwise you will get a JavaScript error in your browser.

var heartBeat = $.connection.heartBeatHub;

Another important thing to note is that you should only start the hub once, no matter how many SignalR endpoints you have, and you place the listening code within the done section of hub, I’ve commented out another listening hub in this sample code:

if ($.connection.hub && $.connection.hub.state === $.signalR.connectionState.disconnected) {
 $.connection.hub.start()
 .done(function () {
 console.log('SignalR now connected, connection ID=' + $.connection.hub.id);
 heartBeat.server.send('Heart beat listening');
 console.log("Heart beat started")
 //anotherHub.server.send('Another hub listening');
 })
 .fail(function () { console.log('Could not Connect!'); });
 }

That is it for now, a good clean SignalR project, and here it is: SignalR

https://github.com/BryanAvery/Signalr