Setup SignalR and Service Bus inside a Azure Service Fabric service - c#

I am porting an existing Cloud Service WorkerRole to Service Fabric as a stateless service. The original Cloud Service uses SignalR and Service Bus (as a SignalR backplane), to send notifications out to any client listening. There is a Startup class that does some of the setup:
class Startup
{
public void Configuration(IAppBuilder app)
{
String connectionString = "Endpoint=sb://[name].servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=[key]";
GlobalHost.DependencyResolver.UseServiceBus(connectionString, "InSys");
app.MapSignalR();
Notifications.Hub = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
}
}
In the OnStart() method in for the WorkerRole I kick-off OWIN with:
var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HttpEndpoint"];
var baseUri = $"{endpoint.Protocol}://{endpoint.IPEndpoint}";
var app = WebApp.Start<Startup>(new StartOptions(url: baseUri));
How is this (i.e., connection the to SignalR Service Bus Backplane) done for a stateless service within Service Fabric?

With the help of https://github.com/marcinbudny/SignalRSelfHostScaleOut (which is an example of scaleout using Redis) I think I have this licked.
In the ServiceManifest.xml I added the following EndPoint:
<Endpoint Protocol="http" Name="ServiceEndpoint" Type="Input" Port="8322" />
I also added a Startup class:
public static class Startup
{
public static void ConfigureApp(IAppBuilder app)
{
String connectionString = "Endpoint=sb://[name].servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=[value]";
GlobalHost.DependencyResolver.UseServiceBus(connectionString, "InSys");
app.MapSignalR();
Notifications.Hub = GlobalHost.ConnectionManager.GetHubContext<InSysMainHub>();
}
}
An OwinCommunicationListener class was also added:
public class OwinCommunicationListener : ICommunicationListener
{
private readonly ServiceEventSource eventSource;
private readonly Action<IAppBuilder> startup;
private readonly ServiceContext serviceContext;
private readonly string endpointName;
private readonly string appRoot;
private IDisposable webApp;
private string publishAddress;
private string listeningAddress;
public OwinCommunicationListener(Action<IAppBuilder> startup, ServiceContext serviceContext, ServiceEventSource eventSource, string endpointName)
: this(startup, serviceContext, eventSource, endpointName, null)
{
}
public OwinCommunicationListener(Action<IAppBuilder> startup, ServiceContext serviceContext, ServiceEventSource eventSource, string endpointName, string appRoot)
{
if (startup == null)
{
throw new ArgumentNullException(nameof(startup));
}
if (serviceContext == null)
{
throw new ArgumentNullException(nameof(serviceContext));
}
if (endpointName == null)
{
throw new ArgumentNullException(nameof(endpointName));
}
if (eventSource == null)
{
throw new ArgumentNullException(nameof(eventSource));
}
this.startup = startup;
this.serviceContext = serviceContext;
this.endpointName = endpointName;
this.eventSource = eventSource;
this.appRoot = appRoot;
}
public Task<string> OpenAsync(CancellationToken cancellationToken)
{
var serviceEndpoint = this.serviceContext.CodePackageActivationContext.GetEndpoint(this.endpointName);
var protocol = serviceEndpoint.Protocol;
int port = serviceEndpoint.Port;
if (this.serviceContext is StatefulServiceContext)
{
StatefulServiceContext statefulServiceContext = (StatefulServiceContext) serviceContext;
listeningAddress = string.Format(
CultureInfo.InvariantCulture,
"{0}://+:{1}/{2}{3}/{4}/{5}",
protocol,
port,
string.IsNullOrWhiteSpace(appRoot)
? string.Empty
: appRoot.TrimEnd('/') + '/',
statefulServiceContext.PartitionId,
statefulServiceContext.ReplicaId,
Guid.NewGuid());
}
else if (serviceContext is StatelessServiceContext)
{
listeningAddress = string.Format(
CultureInfo.InvariantCulture,
"{0}://+:{1}/{2}",
protocol,
port,
string.IsNullOrWhiteSpace(appRoot)
? string.Empty
: appRoot.TrimEnd('/') + '/');
}
else
{
throw new InvalidOperationException();
}
publishAddress = listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN);
try
{
eventSource.Message("Starting web server on " + listeningAddress);
webApp = WebApp.Start(listeningAddress, appBuilder => startup.Invoke(appBuilder));
eventSource.Message("Listening on " + this.publishAddress);
return Task.FromResult(this.publishAddress);
}
catch (Exception ex)
{
eventSource.Message("Web server failed to open endpoint {0}. {1}", this.endpointName, ex.ToString());
StopWebServer();
throw;
}
}
public Task CloseAsync(CancellationToken cancellationToken)
{
this.eventSource.Message("Closing web server on endpoint {0}", this.endpointName);
this.StopWebServer();
return Task.FromResult(true);
}
public void Abort()
{
this.eventSource.Message("Aborting web server on endpoint {0}", this.endpointName);
this.StopWebServer();
}
private void StopWebServer()
{
if (this.webApp != null)
{
try
{
this.webApp.Dispose();
}
catch (ObjectDisposedException)
{
// no-op
}
}
}
}
And then finally I changed the CreateServiceInstanceListeners method in my stateless service code to:
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(serviceContext => new OwinCommunicationListener(Startup.ConfigureApp, serviceContext, ServiceEventSource.Current, "ServiceEndpoint"))
};
}

Create a Stateless service With Owin listener. Then in start up configure for signalR and backplane(service bus or sql). The issue ideally you would face is with a negotiate(Hand shake between Signalr client with server) At this point try configure for cross origin request, a sample code for persistent connection will look like below.
Also note the line appBuilder.UseAesDataProtectorProvider("Your Key") as it is important. The result of this is that you wont end up getting HTTP 400 to connect most of the time. This is because SignalR will make at least 2 requests at handshake and those will usually hit two different machines.
Thanks to marcin budny on the explanation.
var config = new HttpConfiguration();
// Configure your origins as required.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
FormatterConfig.ConfigureFormatters(config.Formatters);
RouteConfig.RegisterRoutes(config.Routes);
appBuilder.UseWebApi(config);
GlobalHost.DependencyResolver.UseServiceBus("yourconnection string comes here", "signalrbackplaneserver");
appBuilder.UseAesDataProtectorProvider("some password");
appBuilder.Map("/echo", map =>
{
map.UseCors(CorsOptions.AllowAll).RunSignalR<MyEndPoint>();
});

Related

Hangfire Dashboard authorization ends up in infinite loop

I've configured hangfire server on my local machine. I use dashboard and added dashboard authorization as it was described in this documentation https://github.com/HangfireIO/Hangfire.Dashboard.Authorization
public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireDB");
app.UseHangfireServer();
var options = new DashboardOptions()
{
Authorization = new IDashboardAuthorizationFilter[]
{
new DashboardAuthorization()
}
};
app.UseHangfireDashboard("/hangfire", options);
InitializeJobs();
}
public class DashboardAuthorization : IDashboardAuthorizationFilter
{
public bool Authorize([NotNull] DashboardContext context)
{
string ipAddress = HttpContext.Current.Request.UserHostAddress;
return CommonUtils.IsIpAddressValid(ipAddress.Trim());
}
}
The problem is that the Authorize function is called infinitely. Any solution?

Service Fabric service with WCF communication deployment

Here is a simple Service Fabric stateless service with WCF communication and it's client - a console app. It works well on the local cluster, client gets responce from the service. But I don't know how to communicate with a service if I deploy it in the cloud. What should I do to access it from console app?
SF Stateless service with WCF communications:
Contract:
[ServiceContract]
public interface IPresidentialService
{
[OperationContract]
Task<string> GetInfo();
}
Service:
internal sealed class PresidentialService : StatelessService, IPresidentialService
{
public PresidentialService(StatelessServiceContext context) : base(context)
{
}
public Task<string> GetInfo() => Task.FromResult($"Node {Context.NodeContext.NodeName} operating");
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(context =>
new WcfCommunicationListener<IPresidentialService>(wcfServiceObject: this, serviceContext: context,
endpointResourceName: "WcfServiceEndpoint",
listenerBinding: WcfUtility.CreateTcpListenerBinding()))
};
}
}
}
Client console app:
WCF client:
public class PresidentialServiceClient : ServicePartitionClient<WcfCommunicationClient<IPresidentialService>>
{
public PresidentialServiceClient(
ICommunicationClientFactory<WcfCommunicationClient<IPresidentialService>> communicationClientFactory,
Uri serviceUri, ServicePartitionKey partitionKey = null,
TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null,
OperationRetrySettings retrySettings = null) : base(communicationClientFactory, serviceUri, partitionKey,
targetReplicaSelector, listenerName, retrySettings)
{
}
public Task<string> GetInfo() => InvokeWithRetryAsync(client => client.Channel.GetInfo());
}
Client App:
private static void Main(string[] args)
{
var binding = WcfUtility.CreateTcpClientBinding();
var partitionResolver = ServicePartitionResolver.GetDefault();
var wcfClientFactory =
new WcfCommunicationClientFactory<IPresidentialService>(binding,
servicePartitionResolver: partitionResolver);
var serviceUri = new Uri("fabric:/Application5/PresidentialService");
var client = new PresidentialServiceClient(wcfClientFactory, serviceUri, ServicePartitionKey.Singleton);
do
{
Console.WriteLine(client.GetInfo().Result);
Console.ReadKey();
} while (true);
}
Added to ServiceManifest.xml:
<Endpoints>
<Endpoint Name="WcfServiceEndpoint" />
</Endpoints>
UPDATE
Changed ServicePartitionResolver:
var partitionResolver = new ServicePartitionResolver("sfapp.westeurope.cloudapp.azure.com:19000");
Still not works.
UPDATE
Added a load balancer rule for TCP port 777.
When the service is running in the cloud, you can't use the default resolver.
The default ServicePartitionResolver assumes that the client is
running in same cluster as the service. If that is not the case,
create a ServicePartitionResolver object and pass in the cluster
connection endpoints.
Try something like
ServicePartitionResolver resolver = new ServicePartitionResolver("mycluster.cloudapp.azure.com:19000");
https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-communication-wcf

SignalR target a specific user from server with custom IUserIdProvider

I've an application using SignalR & WebAPI. I've a custom Authorization context based on a token, which I give on each SignalR requests using the QueryString.
I've implement and IUserIdProvider, in order to retrieve my User from the Token.
And finally, I want to call a client method from the server, for a specific User (with is ID), I'm using a HubContext from the GlobalHost.ConnectionManager.
My problem is that my User is never find from my HubContext, but it is from the Hub itself...
Here is my IUserIdProvider implementation
public class SignalRUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
var token = request.QueryString["token"];
var scope = GetUnprotectedScope(token);
if (scope == null)
return null;
return scope.Id_User.ToString();
}
}
Here is my Hub imlementation
[HubName("notifier")]
public class NotifierHub : Hub
{
public void Notify(string message)
{
Clients.User("1").Notify(message); //When call from a client, this works very well, only the User with the Id = 1 receive the notification
}
}
And finally, I use this to call the client method from my server:
GlobalHost
.ConnectionManager
.GetHubContext<NotifierHub>()
.Clients
.User("1")
.Notify(notification.Message);
// This does nothing...
I'm out of solution at this point, I don't understand what happens, does anyone have already achieve this ?
I've finally figured the issue, but I don't know how to fix it...
The actual issue is simple, the Hub itself has a good context with the clients and everything, but the GlobalHost.ConnectionManager have nothing.
If I change my Hub to something like this:
[HubName("notifier")]
public class NotifierHub : Hub
{
public void Notify(string message)
{
Clients.User("1").Notify(message + " from Hub itself");
GlobalHost
.ConnectionManager
.GetHubContext<NotifierHub>()
.Clients
.User("1")
.Notify(message + " from ConnectionManager");
}
}
My client receive "My message from Hub itself", but never receive "My message from ConnectionManager".
In conclusion, I've a problem with my DependencyInjection... I'm using Structuremap, with this DependencyResover :
public class StructureMapSignalRDependencyResolver : DefaultDependencyResolver
{
private IContainer _container;
public StructureMapSignalRDependencyResolver(IContainer container)
{
_container = container;
}
public override object GetService(Type serviceType)
{
if (serviceType == null)
return null;
var service = _container.TryGetInstance(serviceType) ?? base.GetService(serviceType);
if (service != null) return service;
return (!serviceType.IsAbstract && !serviceType.IsInterface && serviceType.IsClass)
? _container.GetInstance(serviceType)
: _container.TryGetInstance(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = _container.GetAllInstances(serviceType).Cast<object>();
return objects.Concat(base.GetServices(serviceType));
}
}
My Startup file:
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", RegisterSignalR);
}
public static void RegisterSignalR(IAppBuilder map)
{
var resolver = new StructureMapSignalRDependencyResolver(IoC.Initialize());
var config = new HubConfiguration { Resolver = resolver };
map.UseCors(CorsOptions.AllowAll);
map.RunSignalR(config);
}
And finally my Registry...
For<Microsoft.AspNet.SignalR.IDependencyResolver>().Add<StructureMapSignalRDependencyResolver>();
For<INotifier>().Use<SignalRNotifier>();

Passing ClientConnections around different processes

Have run into a slight problem regarding Client Connections that need to be passed between threads.
1.) We have a service class
public class Service : ServiceBase
{
public ServiceHost serviceHost = null;
public CMLiteService()
{
ServiceName = "MyService";
}
public static void Main()
{
ServiceBase.Run(new Service());
}
protected override void OnStart(string[] args)
{
try
{
if (serviceHost != null)
{
serviceHost.Close();
}
Uri baseAddress = new Uri("net.pipe://localhost/Service");
// Step 2 Create a ServiceHost instance
serviceHost = new ServiceHost(typeof(Service), baseAddress);
// Step 3 Add a service endpoint.
serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "Service");
serviceHost.Open();
}
catch(Exception e)
{
}
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
2.) We have an interface
[ServiceContract]
public interface IService
{
[OperationContract]
string InitalizeDataStore(string uri1, string uri2);
[OperationContract]
string CheckHealth();
[OperationContract]
string CreateObject(string parameters);
}
3.) We have a method that Initializes Our data storage
ObjectOperations objectOperations;
public InitalizeDataStore (string uri1, string uri2)
{
Admin admin = new Admin(uri1, uri2);
objectOperations = new ObjectOperations(admin.client1, admin.client2);
}
4.) Here is the admin class that does the actual connecting to the database, both there clients are thread safe and support multithreading
StorageClient1 client1
StorageClient2 client2
string URI1;
string URI2;
public AdminServices(string uri1, string uri2)
{
URI1 = uri1;
URI2 = uri2;
InitializeClient1();
InitializeClient2();
}
public StorageClient1 InitializeClient1()
{
try
{
client1 = new Client(new Uri(URI1));
client1.Connect();
return client1;
}
catch (Exception e)
{
throw e;
}
}
public Client2 InitializeClient2()
{
try
{
client2 = new Client(new Uri(URI2));
client2.Connect();
return client2;
}
catch (Exception e)
{
throw e;
}
}
5.) When we start the service and run the initialization method it connects and works. But when we start another process the client connections are null? If we run the code top down in one console app it works but we are in need of running initialization once and then the client connection must be set for future processes.
So Process 1:
IService pipeProxy = pipeFactory.CreateChannel();
pipeProxy.InitalizeDataStore(); //Returns "Connected"
Process 2:
IService pipeProxy = pipeFactory.CreateChannel();
pipeProxy.CheckHealth(); //returns null
How do we insure that the Client Connection details are also made availible in another process. I am very new too this so Im not too clued up on multithreading.
I believe what you are trying to accomplish is served by the WCF Singleton instance mode:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
Attribute your implementing class with the above, and all clients will share an instance.

No clients available in SignalR Hub context

I am new to SignalR and am experimenting with setting up a self host service that I can use to send events to other applications. I am having a problem getting a method to be called on all clients. In the code below _context.Clients.All is always empty. Any Ideas?
Test Method:
var server = new SignalRServer();
server.Start("http://localhost:8555");
var hubConnection = new HubConnection("http://localhost:8555");
var proxy = hubConnection.CreateHubProxy("testHub");
var executed = false;
proxy.On("testMethod", () =>
{
executed = true;
});
hubConnection.Start().Wait();
var hub = new TestHubContext(GlobalHost.ConnectionManager.GetHubContext<TestHub>());
hub.Test();
hubConnection.Stop();
server.Stop();
Self host server:
public class SignalRServer
{
private IDisposable _signalR;
public void Start(string url)
{
_signalR = WebApp.Start<SignalRStartup>(url);
}
public void Stop()
{
_signalR.Dispose();
}
}
public class SignalRStartup
{
public static IAppBuilder App = null;
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
Hub:
public class TestHub : Hub
{
}
public class TestHubContext
{
private IHubContext _context;
public TestHubContext(IHubContext context)
{
_context = context;
}
public void Test()
{
if (_context != null)
{
// At this poing _context.Clients.All is always empty
_context.Clients.All.testMethod();
}
}
}
I think your context / client connections are fine. Without further information I'm guessing your problem is that you are closing your connection and server too quickly after calling hub.Test()
Comment out the two .Stop() calls (and stick a Console.ReadLine in there to keep the console open) and see what happens

Categories

Resources