I'm Trying to subscribe from mqtt broker using C# Application - c#

Hi i published a message from paho client to MQTT broker and want to subscribe that message using that topic ; my problem is when debugger comes to the line client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; it is not executing the method and moving to the next line.
I use hive mqtt broker and c# Form Application with M2MQTT libraries added.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
// including the M2Mqtt Library
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
private void button1_Click(object sender, EventArgs e)
{
MqttClient client = new MqttClient("192.168.43.51");
client.ProtocolVersion = MqttProtocolVersion.Version_3_1;
byte code = client.Connect(Guid.NewGuid().ToString());
ushort msgIds = client.Subscribe(new string[] { #"Factory1\Sensor1" },
new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
textBox1.Text = "";
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
}
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
this.Invoke((MethodInvoker)delegate ()
{
textBox1.Text += "Received = " + Encoding.UTF8.GetString(e.Message) + "
on topic " + e.Topic + "\r\n";
});
}
I want to get the published message in the text box. will you people help me please.
Thank you.

my problem is when debugger comes to the line client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; it is not executing the method and moving to the next line.
This line should not execute the method as it is only wiring up an event handler. Instead, the code in the event handler client_MqttMsgPublishReceived will be invoked when the MqttClient class raises the MqttMsgPublishReceived event (on receiving an MQTT message).
You can see this by adding a breakpoint to the client_MqttMsgPublishReceived function and publishing a message to the Factory1\Sensor1 topic. You can use a separate MQTT client to publish this message. (Note that the MQTT topic separator is a forward slash '/' so you will need to publish to a topic with a backslash.)
See https://learn.microsoft.com/en-us/dotnet/standard/events/#event-handlers for an overview of how to subscribe to events.

Related

WPF TCP/IP Client server communication

Here I'm trying to implement a TCP/IP client server Communication in a WPF application. I see many examples in console applications and forms, but not in WPF applications.
And also I don't know how to stream messages between a client and server. Could anybody help me out with source code?
enter image description here
Client code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;
using System.Net.NetworkInformation;
using WPFclient;
namespace WPFClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
protected ClientProp WpfClient_;
public MainWindow()
{
InitializeComponent();
}
private void Btncnnct1_Click(object sender, RoutedEventArgs e)
{
TxtBoxIp1.Text = "192.168.0.150";
//TcpClient client = new TcpClient();
this.WpfClient_ = new ClientProp(ipAddress: (this.TxtBoxIp1.Text), portNumber: 138);
this.WpfClient_.BeginPrepareTCPClient();
WpfClient_.Connect(IPAddress.Parse(this.TxtBoxIp1.Text), port: 137);
TxtBoxInfo1.Text = "connected" + Environment.NewLine;
}
private void BtnSnd_Click(object sender, RoutedEventArgs e)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(TxtBoxMsg1.Text);
NetworkStream networkStream = WpfClient_.GetStream();
StreamWriter stream = new StreamWriter(TxtBoxMsg1.Text);
stream.Write(TxtBoxMsg1.Text, 0, TxtBoxMsg1.Text.Length);
TxtBoxInfo1.Text += $"Server : {TxtBoxMsg1.Text}{Environment.NewLine}";
}
Help me out to communicate between a server and client in a WPF application. I checked out many methods like stream, network stream, dispatcher, etc.... I couldn't understand the code. I have created two WPF Applications one for server and one for client.
[enter image description here][2] [2]: https://i.stack.imgur.com/pYKaq.png
Server Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace ServerWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private string line;
public MainWindow()
{
InitializeComponent();
}
private void BtnStrt_Click(object sender, RoutedEventArgs e)
{
TxtBoxIp.Text = "192.168.0.150";
TcpListener server = new TcpListener(IPAddress.Parse(TxtBoxIp.Text), port: 137);
server.Start();
TcpClient client = server.AcceptTcpClient();
TxtBoxInfo.Text = "Server Connected" + Environment.NewLine;
BtnStrt.IsEnabled = false;
BtnSend.IsEnabled = true;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(client.GetStream(), Encoding.UTF8);
}
private void BtnSend_Click(object sender, RoutedEventArgs e)
{
}

how to get cpu state in C#

I am new to C# and programming in general.
I have created a simple plc programme (step7), simulated on PLSIM simulator.
and i want to control this programme with a WPF Interface in C# using Siemens S7ProSim COM Object reference.
here is the problem:
when i want to assign the CPU State to my label, this message is shown:
Error 1 'System.Windows.Controls.Label' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Windows.Controls.Label' could be found (are you missing a using directive or an assembly reference?) C:\Users\Lenovo\Documents\Visual Studio 2010\Projects\CSProject\CSProject\MainWindow.xaml.cs 32 28 CSProject
here is my proramm and my wpf interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CSProject
{
public partial class MainWindow : Window
{
public S7PROSIMLib.S7ProSim ps = new S7PROSIMLib.S7ProSim();
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
ps.Connect();
label_CPUState.Text = ps.GetState();
labelScanMode.Text = ps.GetScanMode().ToString();
}
}
}
Thanks a lot.
I believe you want the Content property of the Label, not the Text property. Text is Winforms.
So, simply:
labelScanMode.Content = ps.GetScanMode().ToString();

How to give Common path to video

I am working in project in which I have used vlc plugin v2. the path for my video is
axVLC.playlist.add(#"D:\My Project\Science\Resources\myvideo.mp4");
axVLC.playlist.play();
now the problem is when I build the project and give it to someone and he/she install it on his/her computer , it show exception that video path is wrong. I am sure that path is not suitable as my the video path in my project is D:... and he/she installed it on C.
So my question is that is there any way to give it common path by which user don`t face such kind of error
Import IO
Using System.IO;
then declare a string that will reference to your video folder
string AbsoluteRef;
use this code in your form load
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
Now declare a string for your video or which ever file like
string vlcvideo;
now add the two together
vlcvideo = AbsoluteRef & "myvideo.mp4";
Finnally add all this into your vlc plugin
axVLC.playlist.add(vlcvideo);
Complete Code looks like so.
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;
using yournamespace.Forms;
using System.IO;
namespace yourNameSpace
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string AbsoluteRef = null;
private void frmMain_Load(object sender, EventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
string vlcVideo = AbsoluteRef + "myvideo.mp4";
axVLC.playlist.add(vlcvideo);
}

Server unable to execute EWS autodiscover

On our testing server, EWS autodiscover does not work. To eliminate an ill-set IIS option from the list of causes, I C&P'ed together a WindowsForms Application (code below) and put it, together with the Microsoft.Exchange.Webservice.dll, into a folder on which I have write permission.
Unfortunately, neither xml nor text file are created. Instead, I get an Unhandled Exception error.
System.NullReferenceException
at System.Windows.Forms.TextBoxBase.AppendText(String text)
This does not happen on my development machine, which is in the same AD domain and on which the test app always returns that autodiscover was successful.
Question: How come no Trace output is generated?
So now, my app code:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
namespace ADDebugWin
{
public partial class Form1 : Form
{
public static string traceData;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.TraceListener = new TraceListener();
// Optional flags to indicate the requests and responses to trace.
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
ews.TraceEnabled = true;
ews.UseDefaultCredentials = true;
try {
ews.AutodiscoverUrl("email#mydomain.com");
textBox1.AppendText("AutoDiscover erfolgreich.");
} catch (Exception ex) {
textBox1.AppendText(traceData);
textBox1.AppendText(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
TraceListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ADDebugMvc.Controllers;
using Microsoft.Exchange.WebServices.Data;
using System.Xml;
namespace ADDebugMvc.Models
{
class TraceListener : ITraceListener
{
public void Trace(string traceType, string traceMessage)
{
CreateXMLTextFile(traceType, traceMessage.ToString());
HomeController.traceData += traceType + " " + traceMessage.ToString() + "\r\n";
}
private void CreateXMLTextFile(string fileName, string traceContent)
{
// Create a new XML file for the trace information.
try
{
// If the trace data is valid XML, create an XmlDocument object and save.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(traceContent);
xmlDoc.Save(fileName + ".xml");
}
catch
{
// If the trace data is not valid XML, save it as a text document.
System.IO.File.WriteAllText(fileName + ".txt", traceContent);
}
}
}
}
One should note that
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
is not returning any Traces during AutoDiscover.
(ews.TraceFlags = TraceFlags.All; does.)
So no string is appended to traceData, which is why traceData==null -> Exception when appending it to a TextBox.

using Microsoft Translate ( GetTranslation Service )

I'm going to build website that uses the translation service from Microsoft. I need to get all the available translations for each word but the code I have provides only one translation while it is supposed to give all available translations. Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using microsofttranslator;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.ServiceModel;
using TranslatorService;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{string Appid="my Appid";
string t="any text";
microsofttranslator.TranslateOptions options = new microsofttranslator.TranslateOptions();
options.Category = "general";
options.ContentType = "text/plain";
options.User = "TestUserId";
options.Uri = "";
bool a=true;
SoapService s = new SoapService();
microsofttranslator.GetTranslationsResponse translations = s.GetTranslations(Appid, t, "ar", "en", 5,a, options);
Response.Write(string.Format("Available translations for source text '{0}' are", t));
foreach (microsofttranslator.TranslationMatch translationMatch in translations.Translations)
{
Response.Write(string.Format("Translated text: {0}" + Environment.NewLine + " Rating:{1}" + Environment.NewLine + "Count:{2}" + Environment.NewLine, translationMatch.TranslatedText, translationMatch.Rating.ToString(), translationMatch.Count.ToString()));
} }}
I added Microsft translate WSDL as a web reference http://api.microsofttranslator.com/v2/Soap.svc?wsdl and I added TranslatorService as a service reference http://api.microsofttranslator.com/V2/Soap.svc
This code works well but as I said it gives only one translation while it is supposed to give all the available translations of a word. I cannot figure out what I am doing wrong.
Maybe you should use the "translateArray" method.
http://msdn.microsoft.com/en-us/library/ff512438.aspx

Categories