SignalR Remote connection to RemoteDesktop - c#

Simple situation. How to connect to SignalR server app which is in my remote desktop server(Ports enabled) using client which is in my computer. Connection works perfect while in local host, as soon as I put my remote machine IP it gives error 400.
Server side:
namespace SignalRHub
{
class Program
{
static void Main(string[] args)
{
string url = #"http://localhost:8080/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine(string.Format("Server running at {0}", url));
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
[HubName("TestHub")]
public class TestHub : Hub
{
public void DetermineLength(string message)
{
Console.WriteLine(message);
string newMessage = string.Format(#"{0} has a length of: {1}", message, message.Length);
Clients.All.ReceiveLength(newMessage);
}
}
}
Client side
namespace SignalRClient
{
class Program
{
static void Main(string[] args)
{
IHubProxy _hub;
//string url = #"http://localhost:8080/";
string url = #"http://111.11.11.111:8080";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
try
{
connection.Start().Wait();
Console.WriteLine("Connection OK. Connected to: "+url);
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
throw;
}
_hub.On("ReceiveLength", x => Console.WriteLine(x));
string line = null;
while ((line = System.Console.ReadLine()) != null)
{
_hub.Invoke("DetermineLength", line).Wait();
}
Console.Read();
}
}
}
Error it gives:
"System.AggregateException: One or more errors occurred. ---> Microsoft.AspNet.SignalR.Client.HttpClientException: StatusCode: 400, ReasonPhrase: 'Bad Request'"
I know there are similar topics but since I am only familiar with C# console and Windows apps only, would be great to found a solution for connection for app to app kind of thing. My RDP server is fully reachable I have databases and other services running there, so the problem is obviously in code. I have changed the IP in post by the way so its not real..
P.S. if I use url = #"http://*8080/" in server side, the compiler gives "HttpListenerException: Access is denied" ...

Problem solved by opening connection in server side using CMD as administrator and putting:
netsh http add urlacl http://*:8080/ user=EVERYONE
Also make sure ports are opened in firewall.
.NET application development WebSocket services in ISS has to be enabled too.

Related

Communication between an Azure web application and a windows form app on Azure VM

This is my first project using Azure. So if I am asking very basic question, please be patient with me.
I have a web application which runs on Azure server. I also have a windows form app which is hosted on Azure VM. According to the requirement, a web app will establish a connection with the windows form app whenever it is required, will send a notification to the form app, receive a response from it and will cut off the connection. So here Web app is like a client and a Windows form app is like a server.
I tried using SignalR. Activated the end point and a port for the Windows form app on Azure portal. I was able to establish the connection but never getting the confirmation of that connection back from the Windows Form app.
Am I using the proper technique or there is a better way to do this? I hope someone will suggest a proper solution.
Here is what I tried
Server side code in Windows form app
Installed the Microsoft.AspNet.SignalR package by Nuget
Activated the VM end point and port #12345 from Azure portal
DNS name of VM - abc.xyz.net
Endpoint port number - 12345
public partial class FormsServer : Form
{
private IDisposable SignalR { get; set; }
const string ServerURI = "http://abc.xyz.net:12345";
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
Task.Run(() => StartServer());
}
private void StartServer()
{
try
{
SignalR = WebApp.Start<Startup>(ServerURI);
}
catch (TargetInvocationException)
{ }
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR("/CalcHub", new HubConfiguration());
}
}
public class CalcHub : Hub
{
public async Task<int> AddNumbers(int no1, int no2)
{
MessageBox.Show("Add Numbers");
return no1 + no2;
}
}
Client side code in web application
Installed the Microsoft.AspNet.SignalR.Client by Nuget
public class NotificationAppClient
{
Microsoft.AspNet.SignalR.Client.HubConnection connectionFr;
IHubProxy userHubProxy;
public void InitiateServerConnection()
{
connectionFr = new Microsoft.AspNet.SignalR.Client.HubConnection("http:// abc.xyz.net:12345/CalcHub", useDefaultUrl: false);
connectionFr.TransportConnectTimeout = new TimeSpan(0, 0, 60);
connectionFr.DeadlockErrorTimeout = new TimeSpan(0, 0, 60);
userHubProxy = connectionFr.CreateHubProxy("CalcHub");
userHubProxy.On<string>("addMessage", param => {
Console.WriteLine(param);
});
connectionFr.Error += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await connectionFr.Start();
};
}
public async Task<int> AddNumbers()
{
try
{
int result = -1;
connectionFr.Start().Wait(30000);
if (connectionFr.State == ConnectionState.Connecting)
{
connectionFr.Stop();
}
else
{
int num1 = 2;
int num2 = 3;
result = await userHubProxy.Invoke<int>("AddNumbers", num1, num2);
}
connectionFr.Stop();
return result;
}
catch (Exception ex)
{ }
return 0;
}
}
There is actually no need to connect and disconnect constantly. The persistent connection will work as well.
Thanks for the reply
So the code works even if it is messy. Usually this is a firewall issue so I would make absolutely sure the port is open all the way between the two services. Check both the Windows firewall and the one in the Azure Network Security Group to make sure that the port is open. I recommend double checking the "Effective Security Rules". If there are multiple security groups in play it is easy to open the port in one group but forget the other.
In order to rule out a DNS issue, you can change const string ServerURI = "http://abc.xyz.net:12345"; to `"http://*:12345" and try connecting over the public IP.
Finally if the catch blocks are actually empty as opposed to just shortening the code either remove them or add something in them that allows you to see errors. As is any errors are just being swallowed with no idea if they are happening. I didn't get any running your code, but it would be good to be sure.
As far as the method of communication goes, if you are going to stick with SignalR I would move opening the connection on the client into the InitiateServerConnection() and leave it open as long as the client is active. This is hoq SignalR is designed to work as opposed to opening and closing the connection each time. If your end goal is to push information in real time from your forms app to the web app as opposed to the web app pulling the data this is fine. For what you are currently doing this is not ideal.
For this sort of use case, I would strongly suggest looking at WebAPI instead of SignalR. If you are going to add more endpoints SignalR is going to get increasingly difficult to work with in comparison to WebApi. You can absolutely use both in parallel if you need to push data to the web client but also want to be able to request information on demand.
The Startup method on the server changes just a bit as Microsoft.AspNet.WebApi is what is being setup instead of SignalR:
class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config);
}
}
Instead of a Hub you create a controller.
public class AddController : ApiController
{
// GET api/add?num1=1&num2=2
public HttpResponseMessage Get(int num1, int num2)
{
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent((num1 + num2).ToString());
return response;
}
}
The client side is where things get a lot simpler as you no longer need to manage what is usually a persistent connection. InitiateServerConnection() can go away completely. AddNumbers() becomes a simple http call:
public static async Task<int> AddNumbers(int num1, int num2)
{
try
{
using(var client = new HttpClient())
{
return Int32.Parse(await client.GetStringAsync($"http://<sitename>:12345/api/add?num1={num1}&num2={num2}"));
}
}
catch (Exception e)
{
//Do something with the exception
}
return 0;
}
If that doesn't end up resolving the issue let me know and we can continue to troubleshoot.

Slow SignalR HubConnection Start

My Question: Is there a way to speed up the initial connect to the hub?
Details:
I am using SignalR at a selfhosted Webservice #Win 8.1.
The Hub application got local clients and remote clients.
I granded SignalR access via DNS, localhost and 127.0.0.1 by:
'netsh http add urlacl url=http://<Replace>:<Port>/ user=Everyone'
Usually all clients even the local ones are using DNS. And it works.
My problem is one sporned child process (using c# Microsoft.AspNet.SignalR.Client.HubConnection). It usually connects withing 400ms. Thats ok. But sometimes it takes seconds.
I have tried to switch at this client to 127.0.0.1 and localhost but without any change.
Afterwards the initial connect, SignalR is pritty fast.
If there is no easy way I have to switch back to plain UDP.
SignalR Config at Hub:
using System;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Owin;
[assembly: OwinStartup(typeof(SignalRStartUp))]
namespace Onsite
{
public class SignalRStartUp
{
// Any connection or hub wire up and configuration should go here
public void Configuration(IAppBuilder pApp)
{
try
{
pApp.UseCors(CorsOptions.AllowAll);
pApp.MapSignalR();
pApp.UseFileServer(true);
var lOptions = new StaticFileOptions
{
ContentTypeProvider = new CustomContentTypeProvider(),
FileSystem = new PhysicalFileSystem(Constants.Root)
};
pApp.UseStaticFiles(lOptions);
// Configure Web API for self-host.
var lConfig = new HttpConfiguration();
lConfig.Routes.MapHttpRoute("RemoteApi", "api/{controller}/{action}");
lConfig.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
pApp.UseWebApi(lConfig);
}
catch (Exception lEx)
{
Logger.Error(lEx);
}
}
}
}
Startup at the Client:
public static string GetConnectionString(string pHost = null)
{
var lHost = pHost ?? GetMainClientDns();
return string.Format("http://{0}{1}", lHost, SignalRPort);
}
private void StartSignalR()
{
try
{
var lConnectionString = GetConnectionString("127.0.0.1");
var lStopWatch = new Stopwatch();
lStopWatch.Restart();
IsConnectingHost = true;
_connection = new HubConnection(lConnectionString, string.Format("AccessKey={0}&Role={0}", Constants.AccessKeyPlugIn));
_connection.Reconnected += SetConnected;
_connection.Reconnecting += SetDisConnected;
MTalkHub = _connection.CreateHubProxy("OnsiteHub");
MTalkHub.On("RequestSetNext", RequestSetNext);
MTalkHub.On("RequestSetPrevious", RequestSetPrevious);
MTalkHub.On("RequestEcho", RequestEcho);
_connection.TransportConnectTimeout = _transportConnectTimeout;
var lTask = _connection.Start();
lTask.Wait();
lStopWatch.Stop();
SetConnected();
}
catch (TargetInvocationException lEx)
{
IsDisconnected = true;
Task.Run(() => TryToConnect());
Logger.Fatal(string.Format("Server failed to start. Already running on: '{0}'", lConnectionString), lEx);
}
catch (Exception lEx)
{
IsDisconnected = true;
Task.Run(() => TryToConnect());
Logger.Fatal(string.Format("Connecting to: '{0}' failed!", lConnectionString.ToStringNs()));
}
finally
{
IsConnectingHost = false;
}
}
After a bugfix for another issue I the long initial connect was also gone.
What I have found: There was a race condition and rarely a lock with FileAccess via network share blocked the Hub by updating the local cached thumbnails.
Thx anyway!

Grapevine REST server , I could not reach from other PC with IP or host name

I am using VS2012 and Grapevine 3.0.4 , when i use the Grapevine same machine with localhost
hostname , everything works well.
If I want to reach from other PC with client , Server could not be start listening with hostname ip address or Computername
If i try server pc set hostname to localhost , it starts listening but when reached from other PC with IP or name server returns bad request 400
Is it something wrong with my code or library.
My Server code is
public class embeddedHTTP
{
private RESTServer Server;
public void ServerStart()
{
try
{
Server = new RESTServer();
Server.Port = GlobalVars.HttpHostPort;
Server.Host = GlobalVars.HttpHostAdress; // THIS ONLY WORKS FOR LOCALHOST
Server.MaxThreads = 20;
Server.Start();
while (Server.IsListening)
{
Thread.Sleep(GlobalVars.HttpHostRespTime);
}
}
catch (Exception ex)
{
messenger.logque("embedded HTTP server not started, Error ID : 52", 3, null);
}
}
public void ServerStop()
{
Server.Stop();
}
public sealed class MyResource : RESTResource
{
//d+$^ [a-zA-Z]+
[RESTRoute(Method = Grapevine.HttpMethod.GET, PathInfo = #"/")]
public void HandleFooRequests(HttpListenerContext context)
{
//String RawuR = context.Request.RawUrl;
String URL = Convert.ToString(context.Request.Url);
String ResultXML = brain.HTTPCMD(URL);
this.SendTextResponse(context, ResultXML);
}
}
}
If you can't reach the server from a remote machine, you are likely running a firewall that is blocking inbound traffic to the port you are listening on. Try opening the port on your firewall, and see if that works for you.
How to Open a Port in the Windows 7 Firewall
Also, you can listen on all hosts by using the asterisk (*) as your hostname.

How do I connect to a Azure Worker Role with tcp endpoint? Tech help needed with Tcp and Azure

I created a worker role in visual studio and deployed it to Azure. Azure shows it is running on my staging.
On my cloud services screen there is a URL for the service, but that doesn't seem to do anything when I ping it or just navigate there. I get:
This webpage is not available
ERR_NAME_NOT_RESOLVED
I wrote the following code to try and access the service through a TcpClient:
string ip = "http://mysite.cloudapp.net";
int port = 10;
TcpClient client = new TcpClient();
try
{
client.Connect(ip, port); // This line throws the error.
if (client.Connected)
{
client.Close();
}
}
catch (Exception ex)
{
Trace.Warn(ex.Message);
}
On client.Connect(ip, port) There is an error that says
Message = "The requested name is valid, but no data of the requested type was found"
My WorkerRole has the following Run method (copied from an online tutorial i believe).
public override void Run()
{
Trace.TraceInformation("wr is running");
TcpListener listener = null;
try
{
listener = new TcpListener(
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["myEndpoint"].IPEndpoint);
listener.ExclusiveAddressUse = false;
listener.Start();
}
catch (SocketException)
{
Trace.Write("Echo server could not start.", "Error");
return;
}
while (true)
{
IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
connectionWaitHandle.WaitOne();
}
}
Finally in my csdef my endpoint appears like so:
<InputEndpoint name="myEndpoint" protocol="tcp" port="10" localPort="10" />
I'd like to get the connection talking back and forth.
Have you tried removing the "http:" from the value of the "ip" variable? You want the IP that address points to, but aren't bound to the HTTP protocol.
I thought that I could use the url, but apparently using the ipaddress listed on the azure portal on my service page, under the Input Endpoints (kind of obvious). I did the following:
IPAddress ipAddress = IPAddress.Parse("13.71.112.31");
int port = 10;
TcpClient client = new TcpClient();
try
{
client.Connect(ipAddress, port);
if (client.Connected) // now true
{
I used this tutorial as a reference.

Ping to server for external connectivity

I have a c# application that has a module for checks the server connection. The relevant code is like the following:
private void PingCheck(string hostName)
{
using (var p = new Ping())
{
try
{
var pr = p.Send(hostName, 2000);
if (pr.Status != IPStatus.Success)
{
log.ErrorFormat("Ping error! Host = {0}, Ping status = {1}", hostName, pr.Status.ToString());
}
}
catch (Exception exc)
{
log.Error("Ping error!", exc);
}
}
}
We have deployed this application to our server that is inside the same network as the target machine. That's why this method checks internal connectivity. Is there any way to check server external connectivity? Because sometimes server connection is available in our network although connection from external network is down. How can I achieve this?
No, there is not, since you are on the server itself.
Either ping some resource outside to check connectivity, or use the NetworkInterface.GetIsNetworkAvailable() method to check whether there is an active connection.

Categories