ASP.net app connection REDIS SocketFailure on Ping - asp.net

I just installed the REDIS server in one of my development servers. And i am trying to connect my localhost application with this external server. I am using StackExchange.REDIS api to make the connection to this REDIS server located at my internal development server 10.26.130.170. I installed the REDIS software with everything default, and made no customization's so far.
Here is the connection class from my project ::
public sealed class RedisSingleton
{
private static Lazy<ConfigurationOptions> configOptions = new Lazy<ConfigurationOptions>(() =>
{
var configOptions = new ConfigurationOptions();
configOptions.EndPoints.Add("10.26.130.170:6379");
configOptions.ClientName = "MyAppRedisConn";
configOptions.ConnectTimeout = 100000;
configOptions.SyncTimeout = 100000;
configOptions.AbortOnConnectFail = true;
return configOptions;
});
private static Lazy<ConnectionMultiplexer> LazyRedisconn = new Lazy<ConnectionMultiplexer>(
() => ConnectionMultiplexer.Connect(configOptions.Value));
public static ConnectionMultiplexer ActiveRedisInstance
{
get
{
return LazyRedisconn.Value;
}
}
}
Please advise on some suggestions. Is there a way i can quickly check in my localhost and verify the connection reach to the REDIS server at the port 6379 using ping or some other command.
The 6379 port is not open on the remote server of redis. I found it with the help of the windows PortQueryUI tool.

I found the solution by opening the port at the remote server.
https://stackoverflow.com/a/40164691/86023

Related

Android emulator port forwarding results in ERR_EMPTY_RESPONSE

My scenario is as follows. I have an Android Emulator which is hosting an EmbedIO web server through an App. When I try to access the URL to the web server from the host machine's (Mac) browser I receive ERR_EMPTY_RESPONSE error.
I have issued the following port forwarding commands through ADB:
adb forward tcp:8080 tcp:8080
In the browser I am navigating to: http://localhost:8080/api/ChangeBackGround
and the Android emulator web server is listening on: http://10.0.2.16:8080/api/ChangeBackGround
Here is the code that starts the web server in the Xamarin Forms App (runs on Android Emulator):
public static class WebServerFactory
{
public static WebServer CreateWebServer<T>(string url, string baseRoute)
where T : WebApiController, new()
{
var server = new WebServer(url)
.WithWebApi(baseRoute, api => api.WithController<T>());
// Listen for state changes.
server.StateChanged += (s, e) => Debug.WriteLine($"WebServer New State - {e.NewState}");
return server;
}
}
public class EventController : WebApiController
{
[Route(HttpVerbs.Get, "/ChangeBackGround")]
public void ChangeBackGround()
{
Device.BeginInvokeOnMainThread(() =>
{
App.Current.MainPage.BackgroundColor = Color.Green;
});
}
}
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
private WebServer _WebServer;
protected override void OnStart()
{
var localIPAddress = GetLocalIPAddress();
var url = $"http://{localIPAddress}:8080";
Task.Factory.StartNew(async () =>
{
_WebServer = WebServerFactory.CreateWebServer<EventController>(url, "/api");
await _WebServer.RunAsync();
});
((MainPage)MainPage).Url = url;
}
private string GetLocalIPAddress()
{
var IpAddress = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault();
if (IpAddress != null)
return IpAddress.ToString();
throw new Exception("Could not locate IP Address");
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
The scenario currently works on the iOS simulator and an Android physical device. But I always get ERR_EMPTY_RESPONSE even when I've setup the port forwarding rules.
Any help would be much appreciated.
Please first make sure your android emulator could connect internet properly.
If the problem perisist, you can try the following methods:
Method 1:
1.start your Command prompt by runing as an admistrator;
2.Run the following commands in sequence:
netsh int ip reset c:\resetlog.txt
netsh winsock reset
ipconfig /flushdns
exit
Method 2: (If method 1 didn't work,try modthod 2)
Open your Control Panel -->NetWork and Internet-->Network and Sharing Center-->Change adapter settings-->right click Ethenet and click Properties-->select Internet Protocol 4-->click Properties -->using the following NDS server addresses
Fill in the following configuration:
Preferred NDS Server: 1.1.1.1
Alternate NDS Server: 1.0.0.1
Method 3: (If above methods didn't work,try modthod 3)
Open Settings in your PC-->Open NetWork and Internet-->click Nnetwork reset-->press Reset Now
Note:
For more details, you can enter keywords How to fix "ERR_EMPTY_RESPONSE" Error [2021] in your browser and then you will find relative tutorail.
You should have you service listening on either one of these IPs:
127.0.0.1: The emulated device loopback interface (preferred, I don't think you have reasons to use a different one)
10.0.2.15: The emulated device network/ethernet interface
See https://developer.android.com/studio/run/emulator-networking#networkaddresses

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" });

grpc .net-core app not visible from outside local

I have grpc dotnet core app, dotnet core version 2.1.
App runs fine when executed on local maschine and accessed from that maschine. When I want to access it from other machine (althought firewall disabled, port opened) I can't access it. I think it is something to the code. I'm not dotnet developer but have some microservice legacy code:). Can it be that problem is in Grpc.Core Server class?
Please help out
Code:
using System;
using System.Collections.Generic;
using System.IO;
using Grpc.Core;
...
static void Main()
{
const int port = 4000;
const string host = "localhost";
var cert = File.ReadAllText("cert.pem");
var key = File.ReadAllText("key.pem");
var keypair = new KeyCertificatePair(cert, key);
var server = GetServer(port, host, keypair);
server.Start();
server.ShutdownTask.Wait();
}
private static Server GetServer(int port, string host, KeyCertificatePair keypair)
{
return new Server
{
Services = { SomeService.BindService(new SomeServiceImpl()) },
Ports = { new ServerPort(host, port, new SslServerCredentials(new List<KeyCertificatePair>
{
keypair
}))}
};
}
Your code explicitly says const string host = "localhost"; which means that it will only listen on the loopback interface (= not accessible from other machines). Use e.g. "[::]" or "0.0.0.0" to listen on all network interfaces.

Could not create SSL/TLS secure channel when connecting through WSS, only on Azure

I am building a Web Api (using ASP.NET Web API), that connects via Secure WebSockets to an endpoint that our client exposed (wss://client-domain:4747/app/engineData). They gave me their certificates all in .pem format (root.pem and client.pem), and a private key (client_key.pem).
In order to get this done I did the following:
1) Converted client.pem and client_key.pem to a single .pfx file (used this here: Convert a CERT/PEM certificate to a PFX certificate)
2) I used the library System.Net.WebSockets, and wrote the following code:
private void InitWebSockesClient()
{
client = new ClientWebSocket();
client.Options.SetRequestHeader(HEADER_KEY, HEADER_VALUE); //Some headers I need
AddCertificatesSecurity();
}
private void AddCertificatesSecurity()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
// I KNOW THIS SHOULDNT BE USED ON PROD, had to use it to make it
// work locally.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
X509Certificate2 x509 = new X509Certificate2();
// this is the pfx I converted from client.pem and client_key
byte[] rawData = ReadFile(certificatesPath + #"\cert.pfx");
x509.Import(rawData, "123456", X509KeyStorageFlags.UserKeySet);
X509Certificate2Collection certificateCollection = new X509Certificate2Collection(x509);
client.Options.ClientCertificates = certificateCollection;
}
And when I want to connect I call:
public async Task<bool> Connect()
{
Uri uriToConnect = new Uri(URL);
await client.ConnectAsync(uriToConnect, CancellationToken.None);
return client.State == WebSocketState.Open;
}
This works fine locally. But whenever I deploy my Web Api on Azure (App Service) and make an HTTP request to it, it throws:
System.Net.WebSockets.WebSocketException - Unable to connect to the remote server.
And the inner exception:
System.Net.WebException - The request was aborted: Could not create SSL/TLS secure channel.
I enabled WebSockets on the AppService instance.
If I delete the line that always return true for the certificate validation, it doesn't work even locally, and the message says something like:
The remote certificate is invalid according to the validation procedure.
So definitely I got something wrong with the certificates, those three .pem files are being used right now in a similar [![enter image description here][1]][1]app in a node.js and work fine, the WSS connection is established properly. I don't really know what usage give to each one, so I am kind of lost here.
These are the cipher suites of the domain I want to connect: https://i.stack.imgur.com/ZFbo3.png
Inspired by Tom's comment, I finally made it work by just adding the certificate to the Web App in Azure App Service, instead of trying to use it from the filesystem. First I uploaded the .pfx file in the SSL Certificates section in Azure. Then, in the App settings, I added a setting called WEBSITE_LOAD_CERTIFICATES, with the thumbprint of the certificate I wanted (the .pfx).
After that, I modified my code to do work like this:
private void InitWebSockesClient()
{
client = new ClientWebSocket();
client.Options.SetRequestHeader(HEADER_KEY, HEADER_VALUE); //Some headers I need
AddCertificateToWebSocketsClient();
}
private void AddCertificateToWebSocketsClient()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
// this should really validate the cert
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
// reading cert from store
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection =
certStore.Certificates.Find(X509FindType.FindByThumbprint,
CERTIFICATES_THUMBPRINT,
false);
if (certCollection.Count > 0)
{
client.Options.ClientCertificates = certCollection;
}
else
{
// handle error
}
certStore.Close();
}
Where CERTIFICATES_THUMBPRINT is a string (thumbsprint of your certificate, the one you saw on Azure).
In case you want to make it work locally, you just need to install the certificate on your computer, as otherwise it won't obviously find it on the store.
Reference for all this in Azure docs: https://learn.microsoft.com/en-us/azure/app-service/app-service-web-ssl-cert-load.

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

Resources