0
votes

I used signalr self hosting with MVC and need to call it from client on another machine so I wrote code like that:

   $(function () {

    jQuery.support.cors = true;

    $.connection.hub.url = "http://[server external Ip]:3031/signalr";

    var chat = $.connection.CustomHub;

    chat.client.addMessage = function (data, IMEI) {
                  //SomeCode
        }
    }

Everything going well but I have this error in Firefox Firebug:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:// [server external IP]/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%22customhub%22%7D%5D&clientProtocol=1.3&_=1400692033406. This can be fixed by moving the resource to the same domain or enabling CORS.

2

2 Answers

3
votes

You have to enable Cross-Domain on the server application by installing Microsoft.Owin.Cors package and the calling UseCors() when starting up SignalR (assuming you are using SignalR 2.x). You do NOT need to specify jQuery.support.cors = true; in SignalR 2.0, actually you should remove it AFAIK.

0
votes

It seems that the error refer to the network connection, we have already used signalR and the identification of the Url to hub is not mandatory.
Below an implementation of SignalR for Sales object:

1- Enable the service broker on the Database SQL Server:

ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;

2- Install signalR from nuget

Install-Package Microsoft.AspNet.SignalR

3- Add reference to signalr javascript library if not added via nuget

<script src="/Scripts/jquery.signalR-2.2.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>

4- Add Javascript to call the Hub

$(function () {
    // Declare a proxy to reference the hub.
    var salesNotificationsHub = $.connection.salesHub;

    // Create a function that the hub can call to broadcast messages.
    salesNotificationsHub.client.updateClientsales = function () {
        Search();
        //alert('des nouveaux sales');
    };

    // Start the connection.

    $.connection.hub.start().done(function () {
        alert('successful connection');
    }).fail(function (e) {
        alert(e);
    });
});

5- Add the Search function created in step 4

function Search() {
    grid.reload({ searchString: searchfields });
}

6- Creation of the code to load the Grid from GetList function in the Controller

 grid = $("#grid").grid({
                dataKey: "Codsales",
                uiLibrary: "bootstrap",
                dataSource:"/sales/GetList",
                autoLoad: true,
                columns: [
                    { field: "Codsales", title: "Code Demande", width: 200, sortable: true },
                    { field: "Libelsales", title: "Libellé Demande", width: 200, sortable: true },
                ],
                pager: { enable: true, limit: 10, sizes: [10, 20, 30, 40] }
            });

7- Creation GetList function in the controller

public JsonResult GetList()
{
    List<salesData> objsalesList = GetList().ToList();
    return Json(objGridData, JsonRequestBehavior.AllowGet);
}

8- Create Function GetList Where will be attached the SqlDependency Object

public static List<salesData> GetList()
{            
    SqlDependency dependency = new SqlDependency();

    using (SqlConnection cn = new SqlConnection(connectionString))
    {
        using (var command = new SqlCommand(@"SELECT Codsales, Libelsales, Datsales,DatDetailledsales FROM [dbo].sales ", cn))
        {
            command.Notification = null;
            dependency = new SqlDependency(command);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

            if (cn.State == ConnectionState.Closed)
                cn.Open();
            command.ExecuteNonQuery();
        }
    }

    List<salesData> objList = new List<salesData>();
    objList=Fetchsales(filterExpression, sortExpression, pageIndex, pageSize, out total);
    rowsCount = total;
    return objList;
}

    private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {                
            salesHub.Updatesales();
        }
    }

9- Create Hub class

public class salesHub : Hub
{   
    [HubMethodName("updatesales")]
    public static void Updatesales()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<salesHub>();
        context.Clients.All.updateClientsales();
    }
}

10- Configuration of the Sqldependency in Global.asax file

protected void Application_Start()
{            //Start SqlDependency with application initialization
    string connString= ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    SqlDependency.Start(connString);
}

protected void Application_End()
{
    //Stop SQL dependency
    string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    SqlDependency.Stop(connString);
}

Cordially