I have written this application to use mqttnet library but connection failed.
How is it possible to get mqttnet with a trace?
Do you notice something wrong with the connection?
Here my code
var mqttClient = new MqttFactory(new MQTTnet.Diagnostics.MqttNetLogger("MyCustomId")).CreateMqttClient();
var caCert = X509Certificate.CreateFromCertFile("C:\\ca.crt");
var clientCert = new X509Certificate2("C:\\certificate.pfx", "uno");
var options = new MqttClientOptionsBuilder()
.WithCredentials("ut", "pwd")
.WithTcpServer("mydns", 8883)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
SslProtocol = System.Security.Authentication.SslProtocols.Tls13,
Certificates = new List<X509Certificate>()
{
caCert, clientCert
},
CertificateValidationCallback = (X509Certificate x, X509Chain y, SslPolicyErrors z, IMqttClientOptions o) =>
{
return true;
}
})
.Build();
MQTTnet.Client.Connecting.MqttClientAuthenticateResult r=await mqttClient.ConnectAsync(options, CancellationToken.None);
Thank you
any help would be appreciated
I have replaced "CreateMqttClient" with "CreateManagedMqttClient" and modified the subsequent part of the code and all has worked
Related
I want to create an Android app that connects to a proxy by button clicked and I'd like to know what should do to make this event?
My proxy needs(password, username, host, port).
I would be appreciated if you help me with this problem .
Add DIO settings like this
String proxy = '<IP>:<PORT>'; //eg 192.168.1.1:8080
var credentials = HttpClientBasicCredentials(<USERNAME>, <PASSWORD>);
bool isProxyChecked = true;
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(client) {
client.badCertificateCallback = (X509Certificate cert, String host, int port) {
return isProxyChecked && Platform.isAndroid;
};
client.findProxy = (url) {
return isProxyChecked ? 'PROXY $proxy' : 'DIRECT';
};
client.addProxyCredentials(<PROXY_IP>, <PORT>, 'main', credentials);
};
I am trying to use MQTT in a Flutter project to test the prototype. And I am using custom certificate-based authentication.
I am using mqtt_client package.
before connect SecurityContext giving this error in web Unsupported operation: default SecurityContext getter
below is my sample code
try {
SecurityContext securityContext =
SecurityContext(withTrustedRoots: false);
securityContext.setTrustedCertificatesBytes(caCertificate);
securityContext.useCertificateChainBytes(caCertificate);
securityContext.setClientAuthoritiesBytes(clientCertificate,
password: String.fromCharCodes(privateKey));
} catch (e) {
print(e);
}
_client = MqttClient('m.test.com', _identifier);
_client.port = 8883;
_client.keepAlivePeriod = 20;
_client.onDisconnected = onDisconnected;
_client.secure = true;
//_client.securityContext = securityContext;
_client.onBadCertificate = ((X509Certificate cert) => false);
_client.logging(on: true);```
this worked for me but I don't understand what (dynamic a) is doing ... perhaps someone can explain it in more detail ?
void initializeMQTTClient() async {
_client = MqttServerClient(_host, _identifier);
_client.port = 8883; //1883
_client.keepAlivePeriod = 20;
_client.onDisconnected = onDisconnected;
_client.secure = true; // false
_client.logging(on: true);
_client.securityContext = SecurityContext.defaultContext;
// _client.useWebSocket = false;
/// Add the successful connection callback
_client.onConnected = onConnected;
_client.onSubscribed = onSubscribed;
_client.onBadCertificate = (dynamic a) => true;
i made a Async Server Socket Code using C# Socket.
Although i wrote a code, then test to Console Environment,
it was working, but i tested that code at UWP.
but, it was not working. cannot accepts client.
Bind, Listen, Accept there are all no error, but this socket code cannot accepts client!
how can i solve me?? please help me..
private Socket m_ServerSocket;
private List<Socket> m_ClientSocket;
private int m_iPort = 1123;
private int m_iClients = 8;
private int m_iBufferSize = 128;
public bool Open(int IN_iPort, int IN_iClients, int IN_iBufferSize)
{
try
{
m_iPort = IN_iPort;
m_iClients = IN_iClients;
m_iBufferSize = IN_iBufferSize;
m_ClientSocket = new List<Socket>();
m_ServerSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_iPort);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(m_iClients);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
}
catch (Exception e)
{
return false;
}
m_bIsOpen = true;
return true;
}
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
m_ClientSocket.Add(ClientSocket);
if (m_ClientSocket != null)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[m_iBufferSize];
args.SetBuffer(szData, 0, m_iBufferSize);
args.UserToken = m_ClientSocket;
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
}
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
I have check your code, there seems no issue existing in your code. Please check if you have checked Internet(Clent&Server)option in your project appxmanifest. For more detail you could refer to Sockets official documentation.
I am working on iphone push notification. I can able to get my device token. I am using .net for pushing json data. But the issue is i cant get the notification. I just want to know whether .net has to push json data over in hosted machine?
Regards,
sathish
I believe that is related to:
Add iPhone push notification using ASP.NET server
Read through the linked project in there. It is pretty comprehensive. You can actually just use that library... it is pretty good.
Unless I misunderstood the question?
Use following snippet to send Push Notification
public void PendingNotification(string DeviceToken,string message)
{
try
{
int port = 2195;
//Developer
String hostname = "gateway.sandbox.push.apple.com";
//Production
//String hostname = "gateway.push.apple.com";
String certificatePassword = "XXXXXXX";
string certificatePath = Server.MapPath("~/cer.p12");
TcpClient client = new TcpClient(hostname, port);
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certificatePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
//String DeviceToken = "XXXXXXXXXXXX";
String LoginName = "Name";
int Counter = 1; //Badge Count;
String Message = message;
String UID = "your choice UID";
string payload = "{\"aps\":{\"alert\":\"" + Message + "\",\"badge\":" + Counter + ",\"sound\":\"default\"},\"UID\":\"" + UID + "\",\"LoginName\":\"" + LoginName + "\"}";
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(DeviceToken.ToUpper()));
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
public static byte[] HexStringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false;
}
When I try to develop CRM stuff, using the code below:
public static CrmService GetCrmService()
{
//Standard CRM setup
var authenticationToken = new CrmAuthenticationToken();
//Using the active directory
authenticationToken.AuthenticationType = 0;
authenticationToken.OrganizationName = "myorganizationName";
var crmService = new CrmService();
crmService.PreAuthenticate = true;
crmService.UseDefaultCredentials = false;
crmService.CrmAuthenticationTokenValue = authenticationToken;
crmService.Credentials = new NetworkCredential("username", "password", "domain");
crmService.Url = "http://<ourserver>/mscrmservices/2007/CrmServiceWsdl.aspx";
return crmService;
}
public void RetrieveAccount()
{
var accountGuid = new Guid("088FFC38-8285-4AF5-8E36-84BAD6B268ED");
var crmService = GetCrmService();
//Set the column to return
var returnedColumns = new ColumnSet();
returnedColumns.Attributes = new string[] { "name", "telephone1", "customertypecode" };
try
{
var receivedAccount = crmService.Retrieve(EntityName.account.ToString(), accountGuid, returnedColumns) as account;
if (receivedAccount != null)
{
Debug.WriteLine(string.Format("Name: {0}, Telephone: {1}", receivedAccount.name, receivedAccount.telephone1));
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
It comes up with the following exception:
"Possible SOAP version mismatch:
Envelope namespace
http://schemas.xmlsoap.org/wsdl/ was
unexpected. Expecting
http://schemas.xmlsoap.org/soap/envelope/."
Is there any solution for this problem ?
Thanks in advance.
After spending several hours, I have figured out that the problem was occured because of using the wrong service address. Instead of connecting to the actual address, I have connected to a redirected address.
So in the above code, I used the redirected address:
https://servername/MSCrmServices/2007/CrmServiceWsdl.aspx
I should have been used the following address:
https://servername/mscrmservices/2007/crmservice.asmx
Cheers.