Using SignalR in ASP.NET 5

Standard

Long back I did some post on SignalR, A collaboration White Board using HTML 5 and SignalR. In this post I am converting that solution to work with ASP.NET 5.

To use SignalR, you need to add “Microsoft.AspNet.SignalR.Server” reference in the project.json file.

{
    "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta1",
		"Microsoft.AspNet.SignalR.Server": "3.0.0-beta1"
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5010"
    },
    "frameworks": {
		"aspnet50": {},
        "aspnetcore50": {}
	}
}

Also you need Microsoft.AspNet.StaticFiles reference, as you need to serve Javascript and HTML files.

Now you need to modify the startup.cs file to use SignalR, similar to MVC, Microsoft introduced some extenstion methods to enable support for SignalR.

public class Startup
{
	public void Configure(IApplicationBuilder app)
	{
		app.UseServices(services =>
		{
			services.AddSignalR();
		});
		app.UseFileServer();
		app.UseSignalR();
	}
}

And you are ready to run the SignalR services. I have modified the script file to support SignalR client side changes. You can find the source code on github.

Happy Programming :)

Creating a WCF service proxy with ChannelFactory <T>

Standard

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.(From wiki). In case of WCF, proxy class helps client application to use WCF service,without knowing the address or implementation details. Here is the code for generic WCF proxy, using ChannelFactory class. ChannelFactory enables you to dynamically creating a proxy object based on the Service Contract. It will help you to avoid update service references or proxies generated using svcutil utility.

internal sealed class GenericProxy<TContract> : IDisposable where TContract : class
{
    private ChannelFactory<TContract> _channelFactory;
    private TContract _channel;

    public GenericProxy()
    {
        _channelFactory = new ChannelFactory<TContract>();
    }

    public GenericProxy(Binding binding, EndpointAddress remoteAddress)
    {
        _channelFactory = new ChannelFactory<TContract>(binding, remoteAddress);
    }

    public void Execute(Action<TContract> action)
    {
        action.Invoke(Channel);
    }

    public TResult Execute<TResult>(Func<TContract, TResult> function)
    {
        return function.Invoke(Channel);
    }

    private TContract Channel
    {
        get
        {
            if (_channel == null)
            {
                _channel = _channelFactory.CreateChannel();
            }

            return _channel;
        }
    }

    public void Dispose()
    {
        try
        {
            if (_channel != null)
            {
                var currentChannel = _channel as IClientChannel;
                if (currentChannel.State == CommunicationState.Faulted)
                {
                    currentChannel.Abort();
                }
                else
                {
                    currentChannel.Close();
                }
            }
        }
        finally
        {
            _channel = null;
            GC.SuppressFinalize(this);
        }
    }
}

The IDisposable implementation will help developers to close / abort channel with “using” statement.

And you can use this like the following.

using (var proxy = new GenericProxy<ICalculator>())
{
    var result = proxy.Execute<int>(x => x.Add(1, 2));
    return result;
}

The code is invoking Add method of Calculator service. The EndPoint and Binding information will fetched from the app.config file.

Happy Programming :)

How to deploy your nuget packages locally

Standard

In ASP.NET 5, everything is nuget package. If you are developing a class library, that is also has to be a nuget package, which you can add as dependency in a different project.json file. This post will help you to build nuget package and deploy it locally.

To build nuget package, you need to use the kpm build command, which will compile the project and build a nuget package based on frameworks key in the project.json. If you have both ASP.NET 5 CLR framework and cloud optimized CoreCLR framework included, kpm will build nuget package for both frameworks.

To deploy nuget packages locally, open Visual Studio. Select Package Manager Settings from Tools > NuGet Package Manager menu. It will display the Visual Studio options dialog. Select the Package Sources item.

NuGet Package source - options

NuGet Package source – options

In the Window, click on + button. Now select the newly added item and modify the name and location, you can provide folder locations here.

Now add dependency of your nuget package in project.json, run kpm restore command, it will look for the package in the locally configured directory as well. You can also modify the NuGet.config file directly from %AppData%\Nuget\ location, if you don’t like Visual Studio GUI ;)

You can find more details about creating and deploying nuget package from NuGet official documentation

Note: You don’t need to create NuGet package while developing the application, you can do it with project.json file. If you keep the project.json file in the same directory level, runtime will pickup the class library automatically.

Happy Programming :)

Generate unit tests for your code using Smart unit tests

Standard

Smart Unit Tests is a new feature in Visual Studio 2015, Smart Unit Tests helps developers to explore their .NET code to generate test data and a suite of unit tests. For every statement in the code, a test input is generated that will execute that statement. A case analysis is performed for every conditional branch in the code. When you run these smart unit tests, you can easily see which tests are failing and add any necessary code to fix them. You can select which of the generated tests to save into a test project to provide a regression suite. As you change your code, rerun Smart Unit Tests to keep the generated tests in sync with your code changes.

You can right click on the class file or method, and select Smart Unit Tests context menu option.

Smart Unit Tests - Context menu option

Smart Unit Tests – Context menu option

A parameterized unit test is generated for this method. The test data is created to exercise the code paths in the method. Smart Unit Tests runs your code many times with different inputs. Each run is represented in the table showing the input test data and the resulting output or exception. The dropdown list in the smart unit tests window will display all the public methods, for which test data is generated.

Generated Test Data and Test cases

Generated Test Data and Test cases

Developers can save the unit test generated, by clicking on the save button of Smart Unit Tests window.Smart unit tests also helps you to identify potential problems in your code as well.

You can find more information about smart unit tests in MSDN

Happy Unit Testing :)