How to connect mqtt with websocket in c#? - c#

I tried use MQTTnet to connect mqtt.
But seems not worked, it would show the error message:
Unable to connect the remote server, the request was aborted: Could not create SSL/TLS secure channel.
I also found error message on windows event:
A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;
public override void Run()
{
var option = new MqttClientOptionsBuilder()
.WithWebSocketServer("wss://mymqttserver:443")
.WithClientId(Guid.NewGuid().ToString())
.WithTls(new MqttClientOptionsBuilderTlsParameters()
{
AllowUntrustedCertificates = true,
UseTls = true,
SslProtocol = SslProtocols.Tls12,
CertificateValidationCallback = delegate { return true; },
})
.WithCleanSession()
.Build();
var mqtt = new MqttFactory().CreateMqttClient() as MqttClient;
mqtt.ConnectAsync(option).Wait();
string convertMsg = JsonConvert.SerializeObject("Mqtt Connect Successfully!!");
var appMsg = new MqttApplicationMessage();
appMsg.Payload = Encoding.UTF8.GetBytes(convertMsg);
appMsg.Topic = "myTopic";
appMsg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
appMsg.Retain = false;
mqttClient.PublishAsync(appMsg).Wait();
}
I also tried connect my mqtt server with third party application.
It can connect successfully, so my mqtt server should be okay.
But I don't know why I can't use c# to connect.

In the line
.WithWebSocketServer("wss://mymqttserver:443")
You must remove the "wss://" because that is already being specified using the method ".WithWebSocketServer". So, you would have
.WithWebSocketServer("mymqttserver:443")
Just use the server and the port.

Related

I don't know how to enter a password while connecting to the gRPC server

public async Task<string> echo()
{
using var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
// The port number must match the port of the gRPC server.
using var httpClient = new HttpClient(httpClientHandler);
using var channel = GrpcChannel.ForAddress("http://10.0.50.120:30000", new GrpcChannelOptions { HttpClient = httpClient });
var client = new StorageService.StorageServiceClient(channel);
var reply = await client.echoAsync(new EchoRequest { });
return reply.ServiceName;
}
I made a client with blazer and I want to communicate with other servers through echo. However, an exception has occurred.
"The connection failed because the target computer refused to connect. " I thought it was not possible because of the authentication of entering the ID and password of the server. I want to know if that's the right problem and if it is, I want to know how to enter it with code.

Close Connection Message MQTTNet C#

I am using the MQTTNet library for the MQTT connection in my application. I am using Mosquitto Broker as a MQTT broker. My app is in .Net core 3.1.
I am having requirement to send the MQTT message to device when the app is connected, normal disconnected and unexpected disconnected.
For the connected scenario, I am using the UseConnectedHandler extension method of the IMQTTClient.
mqttClient.UseConnectedHandler((MqttClientConnectedEventArgs e) =>
{
// Console.WriteLine("MqttClient - Connected");
// Publish the Connect Message
});
For the unexpected disconnect scenario I am using the WithWillMessage feature.
var mqttOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithWillMessage(_options.LastWillMessage)
.WithCleanSession()
.WithClientId(_options.DevcommMqttClientId)
.WithProtocolVersion(MqttProtocolVersion.V500)
.WithCommunicationTimeout(TimeSpan.FromSeconds(30))
.WithCredentials(_options.DevcommMqttUsername ?? string.Empty, _options.DevcommMqttPassword ?? string.Empty)
.WithTcpServer(_options.DevcommMqttHost, _options.DevcommMqttPort)
.WithTls(o =>
{
o.UseTls = _options.DevcommUseTls;
o.AllowUntrustedCertificates = _options.DevcommTlsAllowUntrustedCertificates;
o.IgnoreCertificateChainErrors = _options.DevcommTlsIgnoreCertificateChainErrors;
o.IgnoreCertificateRevocationErrors = _options.DevcommTlsIgnoreCertificateRevocationErrors;
o.SslProtocol = ParseSslProtocols(_options.DevcommTlsProtocols);
o.Certificates = _options.DevcommTlsClientCertificates.AsEnumerable();
o.CertificateValidationHandler = CertificateValidationHandler;
})
.Build())
.Build();
I am now stuck at graceful disconnect scenario. The UseDisconnectedHandler extension method is being called after the disconnect and not before disconnect.
Mosquitto broker is providing the feature of close message, which is similar of before disconnect event.
Is there anyway that using MQTTNet I can send the before disconnect message?

how to send email using MailKit in Asp.Net Core

Am not sure whether the old method of sending Mail using Mailkit is quite working with this code below
try
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress(_emailConfig.SenderName, _emailConfig.SenderAddress));
emailMessage.To.Add(new MailboxAddress(email));
emailMessage.Subject = subject;
var builder = new BodyBuilder
{
HtmlBody = message
};
emailMessage.Body = builder.ToMessageBody();
using var smtp = new SmtpClient
{
ServerCertificateValidationCallback = (s, c, h, e) => true
};
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
await smtp.ConnectAsync(_emailConfig.SmtpServer, Convert.ToInt32(_emailConfig.Port), false).ConfigureAwait(false);
await smtp.AuthenticateAsync(_emailConfig.Username, _emailConfig.Password).ConfigureAwait(false);
await smtp.SendAsync(emailMessage).ConfigureAwait(false);
await smtp.DisconnectAsync(true).ConfigureAwait(false);
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
but am having exceptions if i use the code above to send email
nvalidOperationException: 534: 5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbv
5.7.14 26mzQKtlwfyEdGzHHdpi3ewWG6skAWgOBbdNNYmwzr9Sg3fGu-KixLAfODpJsVafutidE
5.7.14 8xBOp_8rNCvk9Y6iEcOkDlcZ1d-483zQ1Krw04NvqxQdq3w4iTtC8E9bL8uGprgV>
5.7.14 Please log in via your web browser and then try again.
5.7.14 Learn more at
5.7.14 https://support.google.com/mail/answer/78754 o5sm2555896wmh.8 - gsmtp
so when i changed this line of code below to use SSLS, A new error came out
await smtp.ConnectAsync(_emailConfig.SmtpServer, Convert.ToInt32(_emailConfig.Port), true).ConfigureAwait(false);
Exception returned
InvalidOperationException: An error occurred while attempting to establish an SSL or TLS connection.
This usually means that the SSL certificate presented by the server is not trusted by the system for one or more of
the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
4. The certificate presented by the server is expired or invalid.
Another possibility is that you are trying to connect to a port which does not support SSL/TLS.
It is also possible that the set of SSL/TLS protocols supported by the client and server do not match.
See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeException for possible solutions.
have searched everywhere on how to do it,even turned on my less secured app. some recommended sendGrid, i created a free account with them also,but i dont have access to the account created. Does anyone knows how to fix the code above using Mailkit
Try it like this.
using (var smtpClient = new SmtpClient())
{
smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
await smtpClient.ConnectAsync("host", port, false);
if (smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
{
smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
await smtpClient.AuthenticateAsync(username, password);
}
await smtpClient.SendAsync(mailMsg);
smtpClient.Disconnect(true);
}

C# - TLS / SSL Websockets using fleck

Im trying to make a TLS/SSL websocket connection using Fleck lib.
https://github.com/statianzo/Fleck (0.9.8.25)
now i got the server startet .
but when a client connects i get the following message.
28-02-2014 19:16:15 [Info] Server started at wss://localhost:8081
28-02-2014 19:18:51 [Debug] Client connected from 127.0.0.1:62543
28-02-2014 19:18:51 [Debug] Authenticating Secure Connection
28-02-2014 19:18:52 [Debug] 0 bytes read. Closing.
anybody got an idea of what im doing wrong ?
Browser: Chrome, version : 33.0.1750.117
// sample code.
FleckLog.Level = LogLevel.Debug;
var allSockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("wss://localhost:8081");
server.Certificate = new X509Certificate2(#"CRT.pfx", "Pwd");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
foreach (var user in allSockets.ToList())
{
if(user.ConnectionInfo.Id != socket.ConnectionInfo.Id){
user.Send(message);
}
}
};
});
var input = Console.ReadLine();
while (input != "exit")
{
foreach (var socket in allSockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
Is certificate signed by a browser trusted CA? If not, the web page you are opening with Chrome has to be under HTTPS so you can be prompted to accept the certificate, otherwise the connection will fail.
If even doing that does not work, please try with WebSocketListener and tell me which error you get if any.
Some issues I found debugging WSS:
Remember to change the port number to a one different to the one you used for not secure connections. Some browsers get confused if suddenly a port becomes secure or viceversa.
Remember to use the hostname indicated in the certificate to connect and not the IP.
If you are using a self-signed certificate, use it for HTTPS so you can see the dialog for accepting that certificate. When accessing via WSS:// there is not certificate acceptance dialog, it will just fail to connect.
Try with a self-signed certificate as well and see if it works.

SignalR C# Client 407 Proxy Authentication Required

I'm trying to build a C# SignalR app (console app on the server, winforms app on the client), and it works great (in Visual Studio) when both the client and server are on the same PC, but when I deploy the server and repoint the client to the server, I'm getting a "407 Proxy Authentication Required" exception when it tries to start.
This is my code...
var _connection = new HubConnection("http://www.redacted.com:8088/");
var _hub = _connection.CreateProxy("MyHub");
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
MessageBox.Show(string.Format("Could not connect - {0}", task.Exception.ToString()));
}).Wait();
I noticed that HubConnection has a Credentials property, and so I figured I'd try replacating some code I've used with WebServices when dealing with proxies (shown below, where I just make an HTTP request out and then pick up the proxy settings and credentials from that), but I get the same exception.
var _connection = new HubConnection("http://www.redacted.com:8088/");
var req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
var proxy = new WebProxy(req.Proxy.GetProxy(req.RequestUri).AbsoluteUri) {UseDefaultCredentials = true};
_connection.Credentials = proxy.Credentials;
var _hub = _connection.CreateProxy("MyHub");
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
MessageBox.Show(string.Format("Could not connect - {0}", task.Exception.ToString()));
}).Wait();
This is required for some work I'm doing for a client where they want their local PCs to be able to receive messages from a remote system that's hosted outside the company.
Thanks!
Try to set the DefaultWebProxy:
WebProxy wproxy = new WebProxy("new proxy",true);
wproxy.Credentials = new NetworkCredential("user", "pass");
WebRequest.DefaultWebProxy = wproxy;

Categories