Sending Images over Async Server Client Chat C# - c#

I'm new to C# development. I'm working on a Server Client Chat application and I wish to enable image exchanging feature between the server and the client. I've tried alot of online tutorials but none adjusts to my code. Following is my code:
namespace ServerClientChat
{
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public Image img_to_receive;
public String text_to_send;
public Image img_to_send;
public String UserName = "Asad";
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //getting own IP
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBox3.Text = address.ToString();
}
}
// textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
private void button3_Click(object sender, EventArgs e) //Connect to server
{
if (string.IsNullOrWhiteSpace(this.textBox7.Text))
{
MessageBox.Show("Please enter a Username.");
}
else if (string.IsNullOrWhiteSpace(this.textBox5.Text))
{
MessageBox.Show("Please enter an IP address.");
}
else if (string.IsNullOrWhiteSpace(this.textBox6.Text))
{
MessageBox.Show("Please enter a Port number.");
}
else
{
textBox7.Enabled = false;
textBox2.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
client = new TcpClient();
//set client side endpoint consisting of client's ip address and port
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
client.Connect(IP_End);
if (client.Connected)
{
textBox2.AppendText(">> Connected to Server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
if (string.IsNullOrWhiteSpace(this.textBox7.Text))
{
MessageBox.Show("Please enter a Username.");
}
else if (string.IsNullOrWhiteSpace(this.textBox4.Text))
{
MessageBox.Show("Please enter a Port number.");
}
else
{
textBox7.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
textBox2.Enabled = false;
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text)); //Listens for connections from TCP network clients.
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream()); //Implements a TextReader that reads characters from a byte stream in a particular encoding.
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true; //Setting AutoFlush to true means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed.
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //to receive data
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText( receive + "\n\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //to send data
{
if(client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText(text_to_send + "\n\n"); }));
}
else
{
MessageBox.Show("Send Failed");
}
backgroundWorker2.CancelAsync();
}
private void button1_Click(object sender, EventArgs e) //Send button
{
if(textBox1.Text!="")
{
text_to_send = textBox7.Text+":"+textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
DialogResult f = MessageBox.Show("Welcome to My Chat App! Do you want to start your own Server? ", "Welcome!", MessageBoxButtons.YesNoCancel);
if (f == DialogResult.Yes)
{
button3.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
}
if (f == DialogResult.No)
{
button2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
}
if(f==DialogResult.Cancel)
{
this.Close();
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(this, new EventArgs());
}
}
private void button4_Click(object sender, EventArgs e)
{
}
private void browsebtn_Click(object sender, EventArgs e)
{
}
private void sendimg_Click(object sender, EventArgs e)
{
try
{
}
catch(Exception c)
{
MessageBox.Show(c.Message);
}
}
}
}

Related

C# Save SerialPort settings in json file environment

'
public partial class ComPortForm : Form
{
//Port Numaralarını ports isimli diziye atıyoruz.
string[] ports = SerialPort.GetPortNames();
public ComPortForm(SerialPort SP)
{
InitializeComponent();
}
private void ComPortForm_Load(object sender, EventArgs e)
{
foreach (string port in ports)
{
// Port isimlerini combobox1'de gösteriyoruz.
comboBox1.Items.Add(port);
comboBox1.SelectedIndex = 0;
}
// Baudrate'leri kendimiz combobox2'ye giriyoruz.
comboBox2.Items.Add("2400");
comboBox2.Items.Add("4800");
comboBox2.Items.Add("9600");
comboBox2.Items.Add("19200");
comboBox2.Items.Add("115200");
comboBox2.SelectedIndex = 2;
//Bu esnada bağlantı yok.
label1.Text = "Bağlantı Kapalı";
}
private void ComPortForm_Load(object sender, FormClosingEventArgs e)
{
// Form kapandığında Seri Port Kapatılmış Olacak.
if (Program.serial.IsOpen == true)
{
Program.serial.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
if (Program.serial.IsOpen == false)
{
if (comboBox1.Text == "")
return;
// combobox1'e zaten port isimlerini aktarmıştık.
Program.serial.PortName = comboBox1.Text;
//Seri Haberleşme baudrate'i combobox2 'de seçilene göre belirliyoruz.
Program.serial.BaudRate = Convert.ToInt16(comboBox2.Text);
try
{
//Haberleşme için port açılıyor
Program.serial.Open();
label1.ForeColor = Color.Green;
label1.Text = "Bağlantı Açık.";
}
catch (Exception hata)
{
MessageBox.Show("Hata:" + hata.Message);
}
}
else
{
label1.Text = "Bağlantı Zaten Açık!";
}
}
private void button2_Click(object sender, EventArgs e)
{
//BAĞLANTIYI KES BUTONU
timer1.Stop();
if (Program.serial.IsOpen == true)
{
Program.serial.Close();
label1.BackColor = Color.Transparent;
label1.ForeColor = Color.Red;
label1.Text = "Bağlantı Kapalı.";
}
}
private void button3_Click(object sender, EventArgs e)
{
//kaydet butonuyla Form2'yi kapatıyoruz.
this.Close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//resim kutusuna dokununca url ye gidecek.
System.Diagnostics.Process.Start("explorer.exe", #"https://hosseven.com.tr/");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
'
My application for which I selected the Serial Port settings is currently running, but I want to save these settings and use them when my application starts again.I want to keep my chosen settings between application starts? Do I need to save to json file? please edit my code and help.I'm new at this job.

C# from UART How do I separate the data I read into bytes?

I will be glad if you tell me what I need to edit on the code. I want to separate the data I receive byte by byte, how do I do it?
namespace _1993
{
public partial class Form1 : Form
{
string[] ports = SerialPort.GetPortNames(); //Port Numaralarını ports isimli diziye atıyoruz.
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string port in ports)
{
comboBox1.Items.Add(port); // Port isimlerini combobox1'de gösteriyoruz.
comboBox1.SelectedIndex = 0;
}
comboBox2.Items.Add("2400"); // Baudrate'leri kendimiz combobox2'ye giriyoruz.
comboBox2.Items.Add("4800");
comboBox2.Items.Add("9600");
comboBox2.Items.Add("19200");
comboBox2.Items.Add("115200");
comboBox2.SelectedIndex = 2;
label3.Text = "Bağlantı Kapalı"; //Bu esnada bağlantı yok.
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Form kapandığında Seri Port Kapatılmış Olacak.
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
string sonuc = serialPort1.ReadExisting();//Serial.print kodu ile gelen analog veriyi alıyoruz,string formatında sonuc'a atıyoruz
if (sonuc != "")
{
label1.Text = sonuc + ""; //Labele yazdırıyoruz.
listBox1.Items.Add(sonuc); //labele yazdırdığını listboxa ekle
byte[] ba = Encoding.Default.GetBytes(sonuc);
var hexString = BitConverter.ToString(ba);
if (ba[0] == 0XFF)
{
Console.WriteLine(ba);
}
else
{
Console.WriteLine("hatalı");
}
//Console.WriteLine(ba[0]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // basarısız olursa hata verecek.
timer1.Stop();
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start(); //250 ms olarak ayarladım timer'ı.
if (serialPort1.IsOpen == false)
{
if (comboBox1.Text == "")
return;
serialPort1.PortName = comboBox1.Text; // combobox1'e zaten port isimlerini aktarmıştık.
serialPort1.BaudRate = Convert.ToInt16(comboBox2.Text); //Seri Haberleşme baudrate'i combobox2 'de seçilene göre belirliyoruz.
try
{
serialPort1.Open(); //Haberleşme için port açılıyor
label3.ForeColor = Color.Green;
label3.Text = "Bağlantı Açık";
}
catch (Exception hata)
{
MessageBox.Show("Hata:" + hata.Message);
}
}
else
{
label3.Text = "Bağlantı kurulu !!!";
}
}
private void button2_Click(object sender, EventArgs e)
{
//BAĞLANTIYI KES BUTONU
timer1.Stop();
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
label3.ForeColor = Color.Red;
label3.Text = "Bağlantı Kapalı";
}
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Add(label1.Text); //Okunan veri listbox'a atılıyor
}
private void button4_Click(object sender, EventArgs e)
{
listBox1.Items.Clear(); // listbox temizleniyor.
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
SerialPort already returns bytes reads and returns bytes. ReadExisting converts those bytes to a string using the SerialPort.Encoding. To get the raw bytes use Read or ReadByte instead :
var buffer=byte[1024];
var read=port.Read(buffer,0,buffer.Length);
if (read>0 && buffer[0] == 0XFF)
{
....
}
You'll have to convert the bytes to a string explicitly using Encoding.GetString if you want to display the or write them to the console. :
var str=SerialPort.Encoding.GetString(buffer,0,read);
Be careful though.
The default for SerialPort.Encoding is ASCIIEncoding, the 7-bit US-ASCII encoding. This will mangle all non-Latin characters. If the port returnes non-US-ASCII text you'll have to find the proper encoding and use it. On a POS this would mangle non-English product names.

C# Windows Forms Serial Communication with GMap app crash

I've written desktop application, that receives location via serial communication from NRF/GPS module, split that data in order to distinguish latitude, longitude and then i load these coordinates to map(i use GMap). But when i receive data, first 1 or 2 seconds it comes in a little confused form(like this 06840.370056;49.84006068). And i thought adding some Thread.Sleep will solve this problem, but instead application crashes after 5-10 seconds. How can i solve this problem, because i want my app run smoothly? Here is part of my code:
public partial class Form1 : Form
{
public string dataIn;
private List<PointLatLng> _points;
public Form1()
{
_points = new List<PointLatLng>();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = AppConfig.Key;
string[] ports = SerialPort.GetPortNames();
cBoxCom.Items.AddRange(ports);
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
gMap.MapProvider = GMapProviders.GoogleMap;
gMap.ShowCenter = false;
gMap.DragButton = MouseButtons.Left;
gMap.SetPositionByKeywords("Chennai, India");
}
private void btnConnect_Click(object sender, EventArgs e)
{
serialPort1.PortName = cBoxCom.Text;
serialPort1.BaudRate = Convert.ToInt32(cBoxBaudrate.Text);
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
serialPort1.Open();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
}
private void btnClearDataIn_Click(object sender, EventArgs e)
{
if (richBoxReciever.Text != "")
{
richBoxReciever.Text = " ";
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
dataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
Thread.Sleep(3000);
richBoxReciever.Text += dataIn;
Thread.Sleep(5000);
string[] locationData = dataIn.Split(new char[] { ';' });
List<string> tokens = new List<string>();
foreach (string s in locationData)
{
if (s.Length != 0)
{
tokens.Add(s);
}
}
txtLat.Text = tokens[0];
txtLon.Text = tokens[1];
}

Filtering scanned MAC address and display in textbox or listbox without duplication

Tool Image Winform
I am working on a tool that connected to my Bluetooth receiver and scan and get MAC address of BLE devices. So far I can scan and have the mac address continuously display in textbox. I am having problem with filtering MAC address?(Our assigned MAC address 88 99 66 55 4X XX the last 12 bit is free to use). How can I filter this while scanning and put it in Listbox or Textbox for later use.
public SerialPort serialport;
private bool buttonWasClicked = false;
public Form1()
{
InitializeComponent();
foreach (string s in SerialPort.GetPortNames())
{
cmPort.Items.Add(s);
}
}
public void serialport_connect(String port, int baudrate)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
serialport = new SerialPort(port, baudrate);
try
{
serialport.Open();
textBox1.AppendText(" OPEN " + "[" + dtn + "] " + " Port Opened: Connected\n");
// Event Handler
serialport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
//TextBox.CheckForIllegalCrossThreadCalls = false;
if (buttonWasClicked == true)
{
ThreadSafeDelegate(delegate { ScanList.Items.Add(serialport.ReadExisting()); });
//ThreadSafeDelegate(delegate { textBox3.Text += "\r\n"; });
}
else
{
ThreadSafeDelegate(delegate { textBox1.AppendText(serialport.ReadExisting()); });
ThreadSafeDelegate(delegate { textBox1.Text += "\r\n"; });
//textBox1.AppendText(serialport.ReadExisting());
//textBox1.Text += "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
byte[] msg = ASCIIEncoding.ASCII.GetBytes(textBox2.Text + "\0");
serialport.Write(msg, 0, msg.Length);
}
private void button2_Click(object sender, EventArgs e)
{
String port = cmPort.Text;
int baudrate = Convert.ToInt32(cmBaud.Text);
//Parity parity = (Parity)Enum.Parse(typeof(Parity), cmbparity.Text);
//int databits = Convert.ToInt32(cmbdatabits.Text);
//StopBits stopbits = (StopBits)Enum.Parse(typeof(StopBits), cmbstopbits.Text);
button3.Enabled = true;
serialport_connect(port, baudrate);
}
private void button3_Click(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
String dtn = dt.ToShortTimeString();
if (serialport.IsOpen)
{
serialport.Close();
button3.Enabled = false;
button2.Enabled = true;
textBox1.AppendText("[" + dtn + "] " + "Port Close: Disconnected\n");
}
}
private void btnClear_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void ThreadSafeDelegate(MethodInvoker method)
{
if (InvokeRequired)
BeginInvoke(method);
else
method.Invoke();
}
private void Scan_Click(object sender, EventArgs e)
{
buttonWasClicked = true;
byte[] msg = ASCIIEncoding.ASCII.GetBytes( "SNS10" + "\0");
serialport.Write(msg, 0, msg.Length);
}
}
}

Create a HaarCascade to output percentages instead of outputting a "true" when a threshold is being surpassed

My goal is to use my webcam to capture my face and detect my mood by facial expression. The output should be probabilites like 70 % happy, 10 % sad, ...
My approach: very happy and very sad ( and other states ) faces should be saved in a HaarCascade.
My problems are twofold:
How do I create a HaarCascade to use with HaarObjectDetector for the
HaarObjectDetector object to output percentages instead of
outputting a "true" when a threshold is being surpassed?
How do I create a HaarCascade for HaarCascade? Is it easier to use String path = #"C:\Users\haarcascade-frontalface_alt2.xml"; HaarCascade cascade1 = HaarCascade.FromXml(path); with opencv-xml or generate it using HaarCascade m = new HaarCascade(20,20,HaarCascadeStages);? What would HaarCascadeStages be?
Have others already solved this issue and offer sourcecode for c#?
My current code:
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
Bitmap picture;
HaarObjectDetector detector;
FaceHaarCascade cascade;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
picture = (Bitmap)eventArgs.Frame.Clone();
//Rectangle[] objects = detector.ProcessFrame(picture);
//if (objects.Length > 0)
//{
// RectanglesMarker marker = new RectanglesMarker(objects, Color.Fuchsia);
// pictureBox1.Image = marker.Apply(picture);
//}
pictureBox1.Image = picture;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList();
cascade = new FaceHaarCascade();
detector = new HaarObjectDetector(cascade, 30);
detector.SearchMode = ObjectDetectorSearchMode.Average;
detector.ScalingFactor = 1.5f;
detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;
detector.UseParallelProcessing = false;
detector.Suppression = 2;
}
private void rfsh_Click_1(object sender, EventArgs e)
{
}
private void start_Click_1(object sender, EventArgs e)
{
if (start.Text == "Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(640, 480);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "Start";
}
}
}
}

Categories

Resources