WPF TCP/IP Client server communication - c#

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)
{
}

Related

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

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.

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();

Why "threading" is unknown for visual studio?

I include using System.Windows; but threading still it doesn't exist in the namespace
?!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Net.Mail;
using System.Net;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows;
using System.Timers;
using Graduation_Project;
namespace GP
{
public partial class Register : System.Web.UI.Page
{
static int count = 0;
static int timer = 600;
protected void Page_Load(object sender, EventArgs e)
{
System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = new TimeSpan(0, 0, 0, 0, 600000); // 600000 Milliseconds
dt.Tick += new EventHandler(dt_Tick);
}
still have aproblem
System.Windows.Threading.DispatcherTimer is in WindowsBase.dll assembly. Make sure you have added reference to that assembly.
MSDN -
UPDATE -
DispatcherTimer is meant for WPF and Silverlight apps. It can't be used for asp.net project. Instead you should use Timer class meant for web projects.
DispatcherTimer class belongs on System.Windows.Threading namespace which it's belongs in WindowsBase.dll
Be sure you added the right assembly in your project. It is proably in C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0 folder..

How to get grid items --wpf

I made WPF application named as WpfApplication7.It has several folders. One of them is named as Assign_Rights . I have created a UserControl in this folder and named it as Assignment_Rights. Inside this user control i have created a grid and bind it to data explicitly! Now There is button name as Click New. It shows me that PK(Primary Key-Value) of a selected item from grid.
User n = grid.GetRow(view.FocusedRowHandle) as User;
int abc = n.Primary_Key;
Question: As i wrote code to get PK of Selected item it generated error at
int abc = n.Primary_Key;
by saying
Error 'WpfApplication7.Assign_Rights.User' does not contain a definition for 'Primary_Key' and no extension method 'Primary_Key' accepting a first argument of type 'WpfApplication7.Assign_Rights.User' could be found (are you missing a using directive or an assembly reference?) D:\Backup_WPFAppliacation7\New folder\WpfApplication7\WpfApplication7\Assign_Rights\Assignment_Rights.xaml.cs 59 28 WpfApplication7
How to Solve this Error?
EDIT
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
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.Shapes;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Grid;
namespace WpfApplication7.Assign_Rights
{
public partial class Assignment_Rights : UserControl
{
int useridd;
nrcsaEntities d = new nrcsaEntities();
public Assignment_Rights()
{
InitializeComponent();
}
private void ToggleButton1_Click_1(object sender, RoutedEventArgs e)
{
if (view.IsRowSelected(view.FocusedRowHandle) == false)
{
DXMessageBox.Show("Please Select any Item From Grid List");
}
else
{
User n = grid.GetRow(view.FocusedRowHandle) as User;
int abc = n.Primary_Key;
var getd = from p in d.Users select p;
MessageBox.Show(view.FocusedRowHandle.ToString());
} . . . .

Append Xml a given number of times

I am appending to an existing xml file: The code is below: I am using C# .net 4.5 VS 2012 and creating a WPF application.
How could I append this say 30 times and only change D100 attribute number to 2,3,4,5 etc?
The other values are the same!
using System;
using System.Collections.Generic;
using System.Linq;
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.Xml;
namespace AppendX
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Temp.xml");
XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
namespaces.AddNamespace("flp", "http://www.w3.org/2001/flp");
XmlNode nextNode = doc.SelectSingleNode("/flp:Tab/flp:Designs", namespaces);
XmlElement D100 = doc.CreateElement("flp", "D100", "http://www.w3.org/2001/flp");
D100.SetAttribute("Number", "2");
XmlElement Code = doc.CreateElement("flp", "Code", "http://www.w3.org/2001/flp");
Code.InnerText = "B";
D100.AppendChild(Code);
XmlElement Documented = doc.CreateElement("flp", "Documented", "http://www.w3.org/2001/flp");
Documented.InnerText = "false";
D100.AppendChild(Documented);
nextNode.AppendChild(D100);
doc.Save("test1.xml");
}
}
}
Here is the sample xml I am using, sorry I meant to put this up!
<flp:Tab xmlns:flp="http://www.w3.org/2001/flp" Title="Testing">
<flp:Form Number="0" id="1005" />
<flp:Rev Time="2013-01-21T15:08:00">
<flp:Author Name="Brad" Aid="15" />
</flp:Rev>
<flp:Designs Id="D100">
<flp:D100 Number="1">
<flp:Code>A</flp:Code>
<flp:Documented>true</flp:Documented>
</flp:D100>
</flp:Designs>
</flp:Tab>
Create a separate private function that would handle the creation of the document element, given the parameters. ex:
private xmlelement dothework(string param1, string param2){
'do all necessary work to set up the element in here and then return it
}
I would separate the work like this, create a different function for each section of work, so that eventually you can just loop through and append each to the document.

Categories