Konda.eu

Category Archives: C#

5 comments

ASP.NET 5 and SignalR 3

SignalR is a great library from Microsoft for working with WebSockets. It's really fast and supports various fallbacks even for people that use browsers from stone age itself (IE6 for example, but let just hope nobody uses it anymore).

Of course not everything is that nice... When it comes to implementing it in ASP.NET 5 with absolutely NO documentation the entire process of setting this two frameworks/libraries together can be very, very painful.

First thing, to be able to download latest version of SignalR 3 for ASP.NET 5 MyGet repository needs to be referenced. I Added Nuget.config with the following content, but you can also add an URL to global NuGet configuration:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>
    <add key="enabled" value="True" /> <!-- Allow NuGet to download missing packages -->
    <add key="automatic" value="True" /> <!-- Automatically check for missing packages during build in Visual Studio -->
  </packageRestore>
  <packageSources>
    <add key="aspnetmaster" value="https://www.myget.org/F/aspnetmaster/api/v3/index.json" />
  </packageSources>
</configuration>

After that is set up, go to project.json and add the following line to dependencies:

"Microsoft.AspNet.SignalR.Server": "3.0.0-*"

The last thing needed to be done is to add SignalR to the application. To do that go to Startup.cs and make sure that you have the following line somewhere in Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...
    app.UseSignalR();
    // ...
}

At this step everything is ready to go. You can follow any SignalR tutorial, like this chat room for example. At this point there are no updated client side JavaScript libraries, version 2.2.0 works just fine but on the bad side you're still stuck with jQuery...

Some unfortunate souls like myself may stumble upon the following exception:

InvalidOperationException: No service for type 'Microsoft.AspNet.SignalR.Hubs.IJavaScriptProxyGenerator' has been registered.

At this point there are two choices. First one is to manually generate JavaScript files for all Hubs in the project, more about this you can read here, or the second option that I prefer is to register the default provider and all of the JavaScript code is automatically generated. To do this, simply go back to your Startup.cs into ConfigureServices method, and make sure that you have the following line inside:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSignalR();
    // ...
}

That's it! SignalR 3 should now successfully work together with ASP.NET 5 with automatic code generation.

1 comment

C# and AngularJS - Receive Post data

AngularJS is awesome, C# also. But AngularJS has slightly unstandardized way of sending data over networks. Data is packet body instead of header, which may cause quite some problems  if you're unaware of this.

MVC Framework will automatically deserialize data into object when it receives, you only need to tell it that it should look for data in body instead of header.

[HttpPost]
public int method([FromBody]Model m)
{
        // ...

 

No comments

ASP.NET 5 Change Default Views Directory

Testing out new asp.net 5 MVC project template and integrating it into an existing project, predefined project structure didn't really suite my needs. Most of the things work if you move them into a subdirectory, Views directory isn't one of those. You need to create IViewLocationExpander and add it to appropriate service. Example bellow remaps everything into Server subdirectory.

public class ViewsLocationRemapper : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context)
    {
        // Do nothing
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(loc => "Server" + loc);
    } 
}

And then in Startup.cs, ConfigureServices. method, simply call:

services.Configure<RazorViewEngineOptions>(o =>
{
    o.ViewLocationExpanders.Add(new ViewsLocationRemapper());
});

Of course it can be used for simple tasks like prefixing Shader directory with _ (underscore), so that it can be easily found in Solution Explorer.

No comments

C# - Dependency Injections and Automatic Registration with Autofac

Dependency Injections are an awesome design pattern for adding a layer of abstraction into your application for various services and providers. Those can be quickly changed by registering another class and an instance is simply acquired by specifying desired interface as a parameter in constructor therefore decreasing or completely removing factory design pattern.

The only thing I find disturbing is whenever a new dependent class is added it must be registered with dependency injection provider, manual by default. As I consider everything that must be changed or added on a completely different place bad practice, I help myself with the following snippet of code:

var builder = new Autofac.ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
var assemblyTypes = assembly.GetTypes();

foreach (var type in assemblyTypes)
{
    // Ignore interfaces
    if (type.IsInterface)
        continue;

    var typeInterfaces = type.GetInterfaces();

    // Class should implement IDependecy or ISingletonDependency
    if (!typeInterfaces.Any(i => i.IsAssignableFrom(typeof(IDependency))))
        continue;

    var registration = builder.RegisterType(type).AsImplementedInterfaces();

    if (typeInterfaces.Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
        registration.SingleInstance();
    else
        registration.InstancePerRequest();
}

Where IDependency and ISingletonDependency are:

public interface IDependency {}

public interface ISingletonDependency : IDependency {}