A day with .Net

My day to day experince in .net

Archive for May, 2016

SignalR in Web Farm or Web Garden Enviornment

Posted by vivekcek on May 23, 2016

I was trying to use SignalR 2 for one of my project and successfully implemented a progress bar using it.
Everything was working fine in our test server also. But fortunately i tested this SignalR 2 based progress bar in Web-garden mode of IIS,
Woww surprised nothing is working. Thanks God, because our production servers are load balanced Web Farm.

Any way found solution in Microsoft documentation. I will discuss that below.

Hope you have an understanding of SignalR.

1. Create an MVC 5 app.

2. Add Nuget package for SignalR.

Install-Package Microsoft.AspNet.SignalR

3.Now Paste the below code in your cshtml.

<input type="button" value="Submit" id="btnSubmit" />
<input type="hidden" id="connectionid" />

<div id="uploadModal"></div>

@section scripts
{
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <script type="text/javascript">

        $(document).ready(function() {
            var con = $.connection.uploaderHub;
            $.connection.hub.start().done(function() {
                $("#connectionid").val($.connection.hub.id);

            }).fail(function(e) {
                alert('There was an error');
                console.error(e);
            });
            con.client.print = function() {
                $("#uploadModal").append("Vivek");
            };

            $("#btnSubmit").click(function() {

                var connectionid = $("#connectionid").val();
                var url = '@Url.Action("Test", "Home")';
                url = url + '?connectionid=' + connectionid;
                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function(messages) {

                    },
                    error: function() {

                    }
                });

            });

        });
    </script>
}

4. Now create an action in your controller.

        [HttpPost]
        public ActionResult Test(string connectionid)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<UploaderHub>();
            hubContext.Clients.Client(connectionid).print();
            return Json(new { Success = "True" });
        }

5. Create a SignalR hub.

using Microsoft.AspNet.SignalR;

namespace SignalR.Controllers
{
    public  class UploaderHub:Hub
    {

    }
}

6. In your OWIN Startup.cs add the code below.

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR.Startup))]
namespace SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
}

Deploy this to IIS and click submit button, Which will print the text defined in client side print method.

Now increase the worker process count in your application pool to 5, Also set processor affinity true.
Try the same after some refresh, You will found the messaging is not working.

1

To Solve this you can use another SignalR package for SQL Server

Install-Package Microsoft.AspNet.SignalR.SqlServer -Version 2.2.0

Then update your OWIN Startup.cs add this.

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(SignalR.Startup))]
namespace SignalR
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            string sqlConnectionString = "Connecton string to your SQL DB";
            GlobalHost.DependencyResolver.UseSqlServer(sqlConnectionString);
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }
}

Which will create some tables, in the database you specified in your connection string.
And now debug…

Posted in AJAX, MVC, SignalR | Tagged: , , , | 2 Comments »

Injecting different implementation of same interface via Ninject – Contextual Injection

Posted by vivekcek on May 8, 2016

Hi Guys,

I was just working on combining a Factory Method Pattern with Strategy Pattern. During this i came across contextual injection.
Please refer my old post.
Strategy Pattern
Factory Method Design Pattern

I have a common Factory interface, But i want to use separate implementation of this same interface in my two controllers.
I am always using Ninject for all of my MVC app’s. Then I found Ninject have feature for Contextual injection.

Hope You know how to use Ninject, else refer my blog.
Using Ninject

So come to the point.

This is my interface.

    public interface IMyInterface
    {
        void add();
    }

This is my First Implementation.

 public class MyImplementation1 : IMyInterface
    {
        public void add()
        {
            throw new NotImplementedException();
        }
    }

This is my second implementation.

 public class MyImplementation2 : IMyInterface
    {
        public void add()
        {
            throw new NotImplementedException();
        }
    }

The below code can be used for contextual mapping in Ninject

            kernel.Bind<IMyInterface>().To<MyImplementation1>().Named("Implementation1");
            kernel.Bind<IMyInterface>().To<MyImplementation2>().Named("Implementation2");

Now in my First Controller, i can use first implementation.

        IMyInterface _myImpe = null;
        public HomeController([Named("Implementation1")] IMyInterface myImpe)
        {
            _myImpe = myImpe;
        }

In the Second controller.

        IMyInterface _myImpe = null;
        public AccountController([Named("Implementation2")] IMyInterface myImpe)
        {
            _myImpe = myImpe;
        }

For property injection use this snippet.

        [Inject, Named("Implementation2")]
        public IMyInterface Foo { get; set; }

Posted in MVC, Ninject | Tagged: , , , | Leave a Comment »

Web API inside an MVC Area

Posted by vivekcek on May 7, 2016

This is strange thing, i faced when added a Web Api controller inside an area of my production code.
I was using the defualt Web Api route pattern in WebApiConfig.cs

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Unfortunately when i tried to access the path via Jquery Ajax, I got the path not found exception.

This was the path i tried.
http://localhost:56109/api/MySecond

Ok, so i thought as my API controller is under an Area, i should try this way.

http://localhost:56109/api/MyArea/MySecond

Ooops!! still path not found, hmm. I added below code in my AreaRegistraion.Cs file.
Don’t forget to add refrence of “System.Web.Http”

context.Routes.MapHttpRoute(
"FileUpload",
"MyArea/api/{controller}/{id}",
new { AreaName = "MyArea", id = UrlParameter.Optional }
);

Wow now this path is working fine “http://localhost:56109/api/MyArea/MySecond

NB: This was experience in a production app developed with MVC 5 and VS 2013, Anyway i was not able to reproduce this in VS 2015.
As far as my understanding Web Api controllers and routing is independent of MVC Area.

Posted in MVC, Web API | Tagged: , , | Leave a Comment »