c# websocket client unable to connect to Service Fabric service - c#

I have a stateless service acting as an api gateway along with a stateful service that is deployed to Azure on a secured service fabric cluster (using Azure AD). I'm exposing a websocket endpoint (wss). When connecting from my client app (console application using a ClientWebSocket instance), I'm getting "Unable to connect to the remote server" with an inner exception stating: "Authentication failed because the remote party has closed the transport stream." This happens if I attach the SSL cert (from my local machine) that the cluster is secured with, or if I pass my NetworkCredentials in with the ClientWebsocket object when I create it. The endpoint I'm hitting looks like this: wss://blahblahblah.cloudapp.azure.com:19000/mygateway/data. When I tested this code locally before I secured it, I was able to connect. Once I got this deployed successfully to a secured cluster, my client app won't connect. Is there something else I need to provide from the client side to get through the security?
public async Task<bool> ConnectAsync(Uri serviceAddress)
{
this._clientWebSocket = new ClientWebSocket();
using (CancellationTokenSource tcs = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
{
try
{
_clientWebSocket.Options.ClientCertificates = GetCertForRemoteAuthentication();
_clientWebSocket.Options.Credentials = new NetworkCredential{Domain = "mydomain", Password = "somepassword", UserName = "username"};
await this._clientWebSocket.ConnectAsync(serviceAddress, tcs.Token);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
return true;
}

By specifying a specific port and hitting that endoint to our stateful service, as opposed to our service fabric application endpoint (on port 19000) - we were able to get through to our service. Also had to add some code on the server code to make sure we were binding the server certificate to the websocket listener on the server side. That solved our issue.

Related

C# Error in SFTP connection. Exception: System.Net.Sockets.SocketException (11001): No such host is known

I have written a SFTP connection, which is connecting to a secure domain host (MBox location) in .NET Core:
IPHostEntry ip = Dns.GetHostEntry(Host);
using (SftpClient client = new SftpClient(ip.ToString(), Port, User, Password))
{
//connect to client
client.Connect();
var files = client.ListDirectory(PathToRead).ToList();
......
//wait for downloads to finish
await Task.WhenAll(tasks);
// disconnect the client by closing connection
client.Disconnect();
}
which is hosted in Azure App service with subscription and Azure AD configured as per my client's domain. When I am running the code I am seeing the following error:
Error in FTP connection. Exception: System.Net.Sockets.SocketException (11001): No such host is known
Can you please help.
ip.ToString() returns the name of the type, System.Net.IPHostEntry. Your SftpClient is then trying to look up System.Net.IPHostEntry in DNS and not finding anything, thus the exception.
I'm not familiar with the constructors provided by SftpClient, but presumably you need to do something like:
using (SftpClient client = new SftpClient(ip.AddressList, Port, User, Password))

Xamarin.Droid HttpRequestException

I am new to Xamarin Forms. I am building an app which consumes a web service. I am getting HttpRequestException while trying to connect to server. The InnerException throws System.Net.WebException: Error: NameResolutionFailure at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult).
The code that crash is:
public async Task<IEnumerable<Bono>> GetAll()
{
var Url = Constants.baseUrl + "cliente/1/bonos";
HttpClient cliente = new HttpClient();
var bonos = await cliente.GetStringAsync(Url);
return JsonConvert.DeserializeObject<List<Bono>>(bonos);
}
I am using VS for Mac. The same works for Xamarin.iOS. Any suggestion on this?
If the endpoint that you are trying to consume is hosted on your local machine and you are running the application in the local android emulator, you could use the following IP address to reach the host machine from the emulator:
http://10.0.2.2
Of course this will break iOS but it's the IP that can be used from an android emulator to access the host. As an alternative you could use ngrok which can create a publicly accessible tunnel to an endpoint hosted on your local machine and then access the public endpoint from the android application. It could be helpful during development if you want to avoid hosting your endpoint to a network location that can be accessed from the emulator.

Azure connection failed because connected host has failed to respond ip:443

So I implemented an interface to communicate with a rest web service using the HttpClient class to make requests.
The code works perfectly locally, but when I deploy to Azure my application can't fire the request, it crashes on this line:
using (var response = await HttpClient.PostAsync(uri, content)) { ... }
// uri = https://api-rest.zenvia360.com.br/services/send-sms
The exact exception message is this:
A connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because
connected host has failed to respond 200.203.125.26:443
The web service provider states that "if you use firewall or proxy you must add and exception for our IPs. For HTTPS, use port 443:
200.203.125.24
200.203.125.25
200.203.125.26 (the ip of the exception message)
200.203.125.27
200.203.125.28
200.203.125.29"
I looked everywhere in Azure looking for a firewall or something and I got nothing. Also this exception message is pretty cryptc. I tested the same code with another url (fired a post to www.gooogle.com) and it worked.
Any ideas?
The problem turned out to be on the web service side. The service I'm using blocks international requests by default. I asked them to whitelist the azure outbound IPs and now it works.

SignalR client won't connect using OWIN Self Host in Azure Worker Role

I have an Azure Cloud Service with a worker role that starts an OWIN web app on startup, which uses SignalR.
Separately, I have a console project that uses the SignalR client library to connect to this worker role and listen for events.
Everything is working when I run the client and the service locally using the Azure emulators.
When I publish the cloud service and point the console application to it and try to connect, I get the following in the SignalR trace logs:
WS Connecting to: ws://myapp.cloudapp.net/signalr/connect?clientProtocol=1.4&transport=webSockets&connectionData=[{"Name":"MessageBusHub"}]&connectionToken=...
OnError(System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details. ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
It then proceeds to try again using server sent events and long polling with the same error each time.
I'm using the following endpoint in my Cloud service config:
<Endpoints>
<InputEndpoint name="SignalREndpoint" protocol="http" port="80" localPort="80" />
</Endpoints>
And here is how I create my OWIN web app:
var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["SignalREndpoint"];
string webAppUrl = $"{endpoint.Protocol}://{endpoint.IPEndpoint}";
_webApp = WebApp.Start<Startup>(webAppUrl);
Finally, here's how I configure SignalR:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.UseServerAuthentication();
GlobalHost.DependencyResolver.UseServiceBus(CloudConfigurationManager.GetSetting("ServiceBusConnectionString"), "SignalRMessageBus");
app.MapSignalR(new HubConfiguration()
{
EnableDetailedErrors = true,
});
}
}
In the client project I am simply using a HubConnection to connect using the following URL for local testing, http://localhost:80, and the following URL for connecting to the cloud instance, http://myapp.cloudapp.net
I'm not sure what's different between the actual Azure instance and my local emulator that's causing it to not work in the cloud.
Interestingly, if I use the browser to connect to the URL http://myapp.cloudapp.net/signalr/hubs, it works and returns the JS proxy file.
Have you tried using TCP instead of HTTP as a protocol?
I am not a SignalR expert in any way, but I know about it. When we host our server (XSockets.NET) on Azure worker roles we configure the protocol to be TCP (not HTTP).
Have no idea why it would work on localhost though.
Another thing to consider is if the worker role supports websockets? SignalR requires IIS8+ for websocket support and I have no idea if you have access to that in a worker role. There are no options in Azure to turn websockets on/off on a worker role (from what I can see). So my guess is that there is no Microsoft WebSockets in the worker role. By I might be wrong here!
EDIT: Looked at one of my instances and saw that I can change OS and that the default one is 2012 Server. So Microsoft websockets should be available!

Silverlight client consuming WCF service

Please bear with me as I am new to WCF services/ Windows services. I've created a WCF service hosted in a Windows service. I want to consume that WCF service in a Silverlight in-browser application over TCP. Below is the code fragment in Silverlight to access WCF service:
var messageEncoding = new BinaryMessageEncodingBindingElement();
var tcpTransport = new TcpTransportBindingElement();
var binding = new CustomBinding(messageEncoding, tcpTransport);
// Create a channel factory for the service endpoint configured with the custom binding.
var cf = new ChannelFactory<ICalcService>(binding, new EndpointAddress("net.tcp://192.168.2.104:4508"));
// Open the channel.
ICalcService channel = cf.CreateChannel();
// Invoke the method asynchronously.
channel.BeginAdd(9, 5, AddCallback, channel);
private void AddCallback(IAsyncResult asyncResult)
{
try
{
double endAdd = ((ICalcService) asyncResult.AsyncState).EndAdd(asyncResult);
}
catch (Exception exception)
{
throw exception;
}
}
The code works fine sometimes but often it throws an infamous System.ServiceModel.CommunicationException with the following message for some reasons:
Could not connect to net.tcp://192.168.2.104:4508/. The connection attempt lasted for a time span of 00:00:00.1010058. TCP error code 10013: An attempt was made to access a socket in a way forbidden by its access permissions.. This could be due to attempting to access a service in a cross-domain way while the service is not configured for cross-domain access. You may need to contact the owner of the service to expose a sockets cross-domain policy over HTTP and host the service in the allowed sockets port range 4502-4534.
The innerException of type System.Net.Sockets.SocketException says
An attempt was made to access a socket in a way forbidden by its access permissions.
What are the possible reasons behind this exceptions? Based on what I investigated so far, I could find only one reason: Improper ClientAccessPolicy.xml. What may be the other reasons? If you have any useful resources, please provide me the same. One more question, if I want to make Windows service hosted WCF service to get consumed by other machines on LAN, what settings do I have to make? E.g. firewall settings? My code cannot access WCF service on other machine. It throws the same exception I mentioned above. Any ideas about how to get rid of this exception?
Problem sorted..!! I had to do following things:
1) Specified SecurityMode.None while creating NetTcpBinding in Windows service.
2) Created an Inbound Rule in Windows Firewall With Advanced Security to allow TCP traffic on the port I specified in the end point address.

Categories