Connecting the SignalR console client to the server on Azure - c#

I want to deploy a server (on Azure) using SignalR.
And the console client, so that it accepts commands from the server.
The server code was taken from here: https://learn.microsoft.com/ru-ru/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr
Example of a console client from here:https://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications
using Microsoft.AspNet.SignalR.Client;
using System;
namespace SignalRClient
{
class Program
{
static void Main(string[] args)
{
IHubProxy _hub;
string url = #"https://signalrchatmsdn20210410135946.azurewebsites.net/";
//string url = #"http://localhost:62545";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("BetHub");
connection.Start().Wait();
_hub.On("ReceiveLength", x => Console.WriteLine(x));
string line = null;
while ((line = System.Console.ReadLine()) != null)
{
_hub.Invoke("DetermineLength", line).Wait();
}
Console.Read();
}
}
}
If I run the server locally, everything works (string url = #"http://localhost:62545";)
If I run the server on Azure, it works through the browser. But the console client throws an exception.
System.Net.WebException

jdweng absolutely right.
In my case, it was enough to change the deployment setting.
TLS\SSL settings => HTTPS Only: Off

Related

Program to downloading a file from S3 to remote EC2 Instance of Windows

I am writing a program in C# (dotnet 6/Mac) which will issue a PowerShell command to a remote EC2 instance running Windows (2012/PowerShell version 5.x) to download a file from S3.
I am on a Mac and I am able to connect to the EC2 Instance with PowerShell for Mac.
Here is the C# program:
public void DownloadS3FileToRemoteMachine(string host,
string user,
string password,
string bucket,
string s3path,
string localPath)
{
string s3DownloadCommand =
$"aws s3 cp s3://{bucket}{s3path} {localPath}";
var securePass = new SecureString();
foreach (char p in password)
{
securePass.AppendChar(p);
}
var credential = new PSCredential(user, securePass);
var connectionInfo = new WSManConnectionInfo
{
ComputerName = host,
Credential = credential,
NoEncryption = true,
Scheme = WSManConnectionInfo.HttpScheme
};
using Runspace rs = RunspaceFactory.CreateRunspace(connectionInfo);
using PowerShell? ps = PowerShell.Create(rs).AddScript(s3DownloadCommand);
Collection<PSObject>? results;
try
{
rs.Open();
results = ps.Invoke();
if (ps.HadErrors)
{
string errors = string.Join(Environment.NewLine, ps.Streams
.Error
.ReadAll()
.Select(err => err.ErrorDetails.Message));
_logger.LogError("Error while downloading the file from S3 to local path {LocalPath}, " +
"error {ErrorMsg}", localPath, errors);
}
}
catch (Exception e)
{
_logger.LogError(e, "Error copying the file from S3 to remote machine");
throw;
}
string enumerable = string.Join("\n", results.Select(r => r.ToString()));
_logger.LogInformation(enumerable);
}
With this, I get the error:
Connecting to remote server 10.62.166.198 failed with the following error message : Authorization failed For more information, see the about_Remote_Troubleshooting Help topic.
However, I know that the code works because I have access to another Windows machine running Window 10 on my local network and I am able to successfully download the file on that machine.
If I remove the line NoEncryption = true from the configuration then I get a different message:
Connecting to remote server 10.62.166.198 failed with the following error message : MI_RESULT_FAILED For more information, see the about_Remote_Troubleshooting Help topic.
Any help will be tremendously appreciated.
Thanks to the amazing people on the PowerShell Discord channel (access via https://www.reddit.com/r/PowerShell) I learnt that the current functionality of PowerShell to remote from Linux to Windows is very limited.
I had to choose OpenSSH option i.e. install OpenSSH on Windows machine, thereafter, I was able to access the service via C# like so:
var info = new ConnectionInfo(host, user, new PasswordAuthenticationMethod(user, password));
using var client = new SshClient(info);
client.HostKeyReceived += (_, e) => e.CanTrust = true;
client.Connect();
string s3DownloadCommand = $"aws s3 cp s3://{bucket}/{source} {destination}";
using SshCommand? cmd = client.CreateCommand(s3DownloadCommand);
string? output = cmd.Execute();

Get Linux server time from windows service c#

Is there anyway I can get linux server time from windows service given linux server IP ? I tried to use Cliwrap (https://github.com/Tyrrrz/CliWrap) and wrote the following function but it is not working as well:
public string GetLinuxServerTime()
{
using (var cli = new Cli("bash.exe"))
{
// Execute
var output = cli.Execute("ssh user#10.104.12.114 date");
return "abc";
}
}
Kindly suggest some another way.

Timeout in socket connection in UWP

I have this code which works fine for project type of Console App (.NET Core).
class Program
{
static void Main(string[] args)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from Console!!!");
Console.WriteLine(BR.ReadString());
}
}
}
But when I use this code in project type of Blank App (Universal Windows) like this:
public MainPage()
{
InitializeComponent();
ThreadPool.RunAsync(foo);
}
static void foo(IAsyncAction operation)
{
var L = new TcpListener(IPAddress.Any, 4994);
L.Start();
using (var C = L.AcceptTcpClientAsync().Result)
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is from UWP!!!");
Debug.Write(BR.ReadString());
}
}
It will listen to that port when I check it by netstat but when the client wants to connect this exception will be thrown.
System.Net.Sockets.SocketException: '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'
The UWP App has Private Networks (Client & Server) and Internet (Client & Server) capabilities.
Turning firewall on and off didn't help.
Target Version: Windows 10 Creators Update (10.0; Build 15063)
Client Code which is a WPF application:
using (var C = new TcpClient("127.0.0.1", 4994))
{
var S = C.GetStream();
var BR = new BinaryReader(S);
var BW = new BinaryWriter(S);
BW.Write("This is a test");
MessageBox.Show(BR.ReadString());
}
Debugging UWP & TCP listeners from localhost has always been problematic. Your code is OK and it should work if you try to connect into it from an external computer. The issue you're seeing is quite likely a bug/hyper-v issue/networking problem in the network isolation.
You can check if the network isolation for your app is enabled (it is by default) running the following from command prompt:
CheckNetIsolation.exe LoopbackExempt -s
My recommendation is to use an external computer to make sure that your code is fine (it should be). After that you can try to fight with the network isolation but that can be frustrating.
Here's an another issue where this has been discussed: Unable to access TCP Server inside a Windows Universal Application

C# connect with RDP to windows server 2012

I need to do the following things:
1) Сonnect to the server
2) Run the application E:\backup\backup.exe
3) copy E:\backup\log.txt in E:\backup\history\ 18.11.16 20-54-32.txt where the file name will be changed to the current time.
4) Disconnect from the server.
Tell me please, possible to do this the following on C #? And if its possible - preferably example or link to the necessary. Thanks.
using System;
//using Cassia;
using MSTSCLib;
namespace rdm
{
class Program
{
static void Main(string[] args)
{
var rdp = new MsRdpClient8NotSafeForScripting();
rdp.Server= "192.168.0.101"; //adress
rdp.Domain = "localdomain"; //domain
rdp.UserName = "test"; //login
rdp.AdvancedSettings8.ClearTextPassword = "123456";//password
try
{
rdp.Connect();
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine(rdp.Connected);
if (rdp.Connected != 0)
{
rdp.Disconnect();
}
Console.ReadKey(true);
}
}
}
Wow....what a lot of flak for a simple can it or can it not be done?
Dunkan...yes it can.
Visit here: C# Custom Remote Desktop Client using RDP 8.0

How to create a simple local web page using C# windows forms

I am looking to create a simple webpage using C# Windows Forms Application, or a C# Console application.
Running the application will begin hosting a web page at:
http://localhost:3070/somepage
I have read a little bit on MSDN about using endpoints, however being self-taught, this isn't making a ton of sense to me...
In short, this program, when running will display some text on a webpage at localhost:3070.
Sorry for such a vague question, however my hour(s) of searching for a decent tutorial haven't yielded any understandable results...
Thanks for your time!
🛑 2020 Update:
Original answer at the bottom.
Kestrel and Katana are now a thing and I would strongly recommend you look into those things as well as OWIN
Original Answer:
You will want to look into creating an HttpListener, you can add prefixes to the listener such as Listener.Prefixes.Add("http://+:3070/") which will bind it to the port your wanting.
A simple console app: Counting the requests made
using System;
using System.Net;
using System.Text;
namespace TestServer
{
class ServerMain
{
// To enable this so that it can be run in a non-administrator account:
// Open an Administrator command prompt.
// netsh http add urlacl http://+:8008/ user=Everyone listen=true
const string Prefix = "http://+:3070/";
static HttpListener Listener = null;
static int RequestNumber = 0;
static readonly DateTime StartupDate = DateTime.UtcNow;
static void Main(string[] args)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("HttpListener is not supported on this platform.");
return;
}
using (Listener = new HttpListener())
{
Listener.Prefixes.Add(Prefix);
Listener.Start();
// Begin waiting for requests.
Listener.BeginGetContext(GetContextCallback, null);
Console.WriteLine("Listening. Press Enter to stop.");
Console.ReadLine();
Listener.Stop();
}
}
static void GetContextCallback(IAsyncResult ar)
{
int req = ++RequestNumber;
// Get the context
var context = Listener.EndGetContext(ar);
// listen for the next request
Listener.BeginGetContext(GetContextCallback, null);
// get the request
var NowTime = DateTime.UtcNow;
Console.WriteLine("{0}: {1}", NowTime.ToString("R"), context.Request.RawUrl);
var responseString = string.Format("<html><body>Your request, \"{0}\", was received at {1}.<br/>It is request #{2:N0} since {3}.",
context.Request.RawUrl, NowTime.ToString("R"), req, StartupDate.ToString("R"));
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
// and send it
var response = context.Response;
response.ContentType = "text/html";
response.ContentLength64 = buffer.Length;
response.StatusCode = 200;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
}
And for extra credit, try adding it to the services on your computer!
Microsoft Relased an Open Source Project called OWIN it is simlar to Node but bottom line it allows you to host web applications in a console application:
You can find more information here:
https://github.com/duovia/duovia-http
http://owin.org/
http://katanaproject.codeplex.com/
But if you insist in creating your personal listener you can find some help here:
http://msdn.microsoft.com/en-us/library/system.net.httplistener(VS.80).aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/b7f476d1-3147-4b18-ba5e-0b3ce8f8a918/want-to-make-a-webserver-with-httplistener

Categories