can not use signalr sample for a console application - asp.net

i was trying signalR hubs trough their sample at https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs.
i managed to create an mvc 4 asp.net app using their sample for asp.net, BUT when i try to debug the console app program :
public class Program
{
public static void Main(string[] args)
{
// Connect to the service
var hubConnection = new HubConnection("http://localhost/5623");
// Create a proxy to the chat service
var chat = hubConnection.CreateHubProxy("chat");
// Print the message when it comes in
chat.On("addMessage", message => Console.WriteLine(message));
// Start the connection
hubConnection.Start().Wait();
string line = null;
while((line = Console.ReadLine()) != null)
{
// Send a message to the server
chat.Invoke("Send", line).Wait();
}
}
}
it send me an exception at hubConnection.Start().Wait(); saying {"The remote server returned an error: (500) Internal Server Error."}.
i think it has something to do with the http://localhost/5623, i tried http://localhost/5623/Home and http://localhost/5623/Home/Chat i got {"The remote server returned an error: (404) Not Found."} error instead.
How can i solve this please.
Thank you.

Related

Signalr core client - call server methode from Razor component

How can I send a message to my server from, let's say a Razor component?
The situation:
I have a working SignalR (Core) connection with my server.
My client code:
public class StartMySignalR
{
HubConnection connection;
public async void StartSignalRHub()
{
connection = new HubConnectionBuilder()
.WithUrl(new Uri("https://myurl.my/LogOnHub"))
.WithAutomaticReconnect()
.Build();
connection.On<string>("ReceiveMessage", (message) =>
{
//Do some stuff
ii.InsertIntoLog("INFO", "SignalR ID = " + message);
});
//Start SignalR client
await connection.StartAsync();
//Send message to server (test connection).
await connection.InvokeAsync("WelcomeMessage", connection.ConnectionId);
I send a test message to my server, that works fine. I can also send a message back from my server,.. so far so good. But now I want to do that from a Razor component in my OnInitializedAsync() Task. So when my page loads, the test message is sent to my server. There I am stuck. When I try to send the message from my Razor component I receive an error (System.NullReferenceExeption - Object reference not set to an instance of an object) -> connection was null error.
Can somebody put me in the right direction?
When I set the Hubconnection to static it works.
public static HubConnection connection;

Can you run a asp.net core 3.0 gRPC CLIENT in IIS? (possibly on Azure?)

I've read a lot of conflicting information about this and it seems people are not 100% clear on what is possible and what is not. I am certain that you cannot host a gRPC server app in IIS due to the HTTP/2 limitations. The documentation is pretty clear. However, I want to use IIS as a reverse proxy, with the internal side communicating using gRPC. So the client would be in IIS, not the server. I assumed that since the communication at this point (i.e. the back end) was not funneled through IIS, there would be no issue with this. However, I keep seeing mixed answers.
I have created a dumb webapp that is hosted in IIS Express and can successfully post to my service running on Kestrel with gRPC.
Client code sample below. The SubmitButton is just a form post on the razor page.
public async void OnPostSubmitButton()
{
// The port number(5001) must match the port of the gRPC server.
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(
new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
Server code is the boilerplate template for gRPC but looks like this:
namespace grpcGreeter
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
namespace grpcGreeter
{
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
}
This works. But, because I keep seeing mixed information saying it that it won't, I am not certain that once I go to deploy the client code (i.e. the reverse proxy), if I will run into problems. I would like to use a host like Azure...but don't know if it's possible or not.
Any clarity on the subject would be greatly appreciated.
As far as I know, we could use asp.net core mvc or razor page application as the client to call the grpc server.
But gRPC client requires the service to have a trusted certificate when you hosted the application on remote server IIS.
If you don't have the permission to install the certificate, you should uses HttpClientHandler.ServerCertificateCustomValidationCallback to allow calls without a trusted certificate.
Notice: this will make the call not security.
Additional configuration is required to call insecure gRPC services with the .NET Core client. The gRPC client must set the System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport switch to true and use http in the server address.
Code as below:
AppContext.SetSwitch(
"System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var httpClientHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
var httpClient = new HttpClient(httpClientHandler);
var channel = GrpcChannel.ForAddress("https://localhost:5001",
new GrpcChannelOptions { HttpClient = httpClient });
var client = new Greeter.GreeterClient(channel);
var response = await client.SayHelloAsync(new HelloRequest { Name = "World" });

Connecting with SignalR after login or Delayed connection with SignalR

I am working with SignalR & MVC. The code that i looked up actually connects the user to the hub at startup.
[assembly: OwinStartup(typeof(Uno.Hubs.Startup))]
namespace ChatTBox
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
}
}
}
However, i need the user to connect to SignalR after it has successfully logged in and then keep and display the list of connected signed in user. How to do that?
This call doesn't connect the user to the hub, it simply registers the SignalR middleware (the same way you would call app.UseWebApi()). Connecting a user is initiated by the client from the client.
You can connect a client after login from the client. The example on asp.net can be modified to suit:
// login
// assuming your hub is called ChatTBoxHub
var chatTBoxHubProxy = $.connection.contosoChatHub;
// wire up the event the server can call on the client
chatTBoxHubProxy.client.addMessageToPage = function (name, message) {
console.log(name + ' ' + message);
};
// start the signalR connection
$.connection.hub.start().done(function () {
// Wire up Send button to call NewContosoChatMessage on the server.
chatTBoxHubProxy.server.register(someUniqueClientIdServer);
});
// For .Net clients:
var hubConnection = new HubConnection("http://yourUrl/");
IHubProxy chatTBoxHubProxy = hubConnection.CreateHubProxy("ChatTBoxHub");
chatTBoxHubProxy.On<Message>("addMessageToPage", message => Console.WriteLine("Message '{0}' received from {1}", message.Body, message.Name));
await hubConnection.Start();
// EDIT to add example registration in your server hub class
public void Register(string uniqueClientId)
{
hubUsers[uniqueClientId] = Context.ConnectionId; // Context is supplied by SignalR base class.
}

SignalR .Net Client can't establish conection (404 not found)

I have a solution in which i am using SignalR. There is a Hub in one of the projects and SignalR.Client in the others that are connecting to that Hub.
This solution is hosted on two servers, and I have a strange problem. In one server everything works fine, but in the other i get an 404 not found error when I am trying to establish the connection from the SignalR.Client.
Hub Code:
public class GlobalHub : Hub
{
public void Hello()
{
Clients.All.hello();
}
public void Notify(string user,NotificationViewModel model)
{
Clients.Group(user).notify(model);
}
public override System.Threading.Tasks.Task OnConnected()
{
string name = Env.UserId().ToString();
Groups.Add(Context.ConnectionId, name);
return base.OnConnected();
}
}
Global.asax Hub Map:
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJavaScriptProxies = true
};
RouteTable.Routes.MapHubs("/signalr",hubConfiguration);
The connection attempt:
string portal = CommonHelper.GetPortalUrl("user");
if(portal.Contains(":50150"))
{
portal = portal.Replace(":50150", "");
}
var connection = new HubConnection(portal+"signalr",false);
IHubProxy myHub = connection.CreateHubProxy("GlobalHub");
connection.Start().Wait();
myHub.Invoke("Notify", userID.ToString(), result2);
I am pretty sure that my connection url is correct, I checked it 50 times.
Error occurs on this line:
onnection.Start().Wait();
SS of Error:
Thanks
The problem may be that when hosting a SignalR project on two servers, clients connected to one can only be connected to other clients connected to the same server. That is because SignalR doesn't automatically broadcast a message through all servers.
http://www.asp.net/signalr/overview/performance/scaleout-in-signalr
Try have a look here and I hope it is helpful to you. One of the proposed solution is to use the Redis Pub/Sub (http://redis.io/topics/pubsub) solution, or Azure Service Bus (http://azure.microsoft.com/en-us/services/service-bus/) - both of whom are use as a backplane (when a server receives a message, it is broadcast to all of them and the one that needs it can use it).
Thanks I solved the problem. It turned out that it was a problem with the server. The server itself couldnt recognize that url (throws 404 on the url).
After that problem was fixed, SignalR started working

Windows phone app crashes while communicating to wcf service without internet connection

I have added the web service to my WPF windows phone store app, when i run my app in emulator it works, but sometime it get creshes cause lack of internet connectivity.
i'm checking my emulator IMEI is registerd or not in database using WCF service on main_pageload event
my code looks like this
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
SchoolWebService.SchoolAppWebServiceSoapClient proxy = new SchoolAppWebServiceSoapClient();
proxy.CheckIMEIRegisteredOrNotCompleted += new EventHandler<CheckIMEIRegisteredOrNotCompletedEventArgs>(proxy_CheckIMEIRegisteredOrNotCompleted);
proxy.CheckIMEIRegisteredOrNotAsync(strIMEI);
}
in this service im checking the mobile IMEI registerd or not. i have checked by debugging the app it goes upto proxy.CheckIMEIRegisteredOrNotAsync(strIMEI);
when it leave the context it throuw the error
An exception of type 'System.ServiceModel.CommunicationException' occurred in System.ServiceModel.ni.dll but was not handled in user code
please suggest me some advice,,,thanks in advance
To check if the Internet connection is available I just simply create a method to check it and execute it then application is launching or page is loading. This method I create in App.xaml.cs:
public bool CheckInternetConnection()
{
bool connection = true;
ConnectionProfile currentConnection = NetworkInformation.GetInternetConnectionProfile();
if (currentConnection == null)
{
connection = false;
}
return connection;
}
Then in some page_loaded event I execute it:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
bool connection = ((App)Application.Current).CheckInternetConnection();
if (connection == false)
{
MessageBox.Show("Internet connection is not available", "Internet connection", MessageBoxButton.OK);
Application.Current.Terminate();
}
}
Now then a client don't have the Internet connection available it won't crash, but it will show a message for the user. I hope it will help.

Resources