0% found this document useful (0 votes)
11 views10 pages

User Control

The document contains a C# class definition for a UserControlAnalyzer that manages communication through serial ports, network sockets, and file-based interfaces. It includes methods for initializing communication settings, handling data reception, and managing client connections. The class also implements error handling and logging for various communication scenarios.

Uploaded by

ibrahim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views10 pages

User Control

The document contains a C# class definition for a UserControlAnalyzer that manages communication through serial ports, network sockets, and file-based interfaces. It includes methods for initializing communication settings, handling data reception, and managing client connections. The class also implements error handling and logging for various communication scenarios.

Uploaded by

ibrahim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

protected override void Dispose(bool disposing)

{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Linq;

namespace LISA
{
public partial class UserControlAnalyzer : UserControl
{
public DataRow dtCentral;
private SerialPort ObjSPAccess;
private LISAINTERFACE_SERIAL LisaInterfaceComm_Serial = null;
private LISAINTERFACE_NETWORK LisaInterfaceComm_Network = null;
private LISAINTERFACE_NETWORK_CLIENT LISACLIENTTCPCommInterface = null;
private LISAINTERFACE_FILEBASE LISAFILEBASECOMMINTERFACE = null;
private StreamWriter sw;
public TcpListener tcpListener;
public Thread listenThread;
public static TcpClient client;
private IPEndPoint fetchedEP;
private TcpClient tcpClient;
public ASCIIEncoding encoder;
public string ReceivedString = null;
public string TCPInstance;
public static List<SerialPort> sPorts = new List<SerialPort>();
private Socket comm_client_conn;
private Socket client_conn;
private IPEndPoint fetched_endpoint;
private byte[] comm_bytemsg;
private bool check = false;
private IPAddress hostIPAddress;
public int Ports;

public UserControlAnalyzer(DataRow dt)


{
InitializeComponent();
dtCentral = dt;
CommPortLoad();
}

private void CommPortLoad()


{
try
{
if (dtCentral["protocol"].ToString().ToUpper() == "SERIAL")
{

string[] ports = SerialPort.GetPortNames();

if (ports.Length >= 1 && dtCentral != null)


{

string comport = dtCentral["portnumber"].ToString().Trim();

if (ports.Contains(comport))
{
richTextBox_analyzerString.Text += "Channelizing !!!!";
ObjSPAccess = new SerialPort();
ObjSPAccess.PortName =
dtCentral["portnumber"].ToString().Trim();
ObjSPAccess.BaudRate =
Convert.ToInt32(dtCentral["baudrate"].ToString().Trim());
ObjSPAccess.DataBits =
Convert.ToInt32(dtCentral["databits"].ToString().Trim());
ObjSPAccess.Parity = (Parity)Enum.Parse(typeof(Parity),
dtCentral["parity"].ToString().Trim());
ObjSPAccess.StopBits =
(StopBits)Enum.Parse(typeof(StopBits), dtCentral["stopbits"].ToString().Trim());
ObjSPAccess.Handshake =
(Handshake)Enum.Parse(typeof(Handshake), dtCentral["handshake"].ToString().Trim());

if (dtCentral["dtr_rts"].ToString().Trim() == "Y")
{
ObjSPAccess.DtrEnable = true; //
ObjSPAccess.RtsEnable = true; //
}

if (ObjSPAccess.IsOpen)
{
ObjSPAccess.Close();
}
ObjSPAccess.Open();

richTextBox_analyzerString.Text += Environment.NewLine
+ "Communication Started !!!!";
ObjSPAccess.DataReceived += sPort_DataReceived;
string Class_Name = "LISA." +
dtCentral["device_name"].ToString().Trim() + ",LISA";
this.LisaInterfaceComm_Serial =
(LISAINTERFACE_SERIAL)Activator.CreateInstance(System.Type.GetType(Class_Name,
true), (object)dtCentral["deviceid"].ToString().Trim());

label_machinename.Text =
dtCentral["device_name"].ToString().Trim();
label_port.Text =
dtCentral["protocol"].ToString().Trim() + " (" +
dtCentral["portnumber"].ToString().Trim() + ")";
label1.Text = "COMPORT:";
pictureBox_status.Image = Properties.Resources.correct;
sPorts.Add(ObjSPAccess);

}
else
{
MessageBox.Show("Port Not Available");
}
}
else if (dtCentral["protocol"].ToString().ToUpper() == "NETWORK")
{

if (dtCentral["mode"].ToString().ToUpper() == "SERVER")
{
IPAddress localaddr =
IPAddress.Parse(dtCentral["hostip"].ToString());
int iPort =
Int32.Parse(dtCentral["portnumber"].ToString());
string instance_name = "LISA." +
dtCentral["device_name"].ToString().Trim() + ",LISA";
TCPInstance = instance_name;

if (localaddr != null)
{
tcpListener = new TcpListener(localaddr, iPort);
listenThread = new Thread(AttendClientsComm);
listenThread.Start();
}

}
else if (dtCentral["mode"].ToString().ToUpper() == "CLIENT")
{
string instance_name = "LISA." +
dtCentral["device_name"].ToString().Trim() + ",LISA";
TCPInstance = instance_name;
Ports = Int32.Parse(dtCentral["portnumber"].ToString());
hostIPAddress =
IPAddress.Parse(dtCentral["deviceip"].ToString());
fetched_endpoint = new IPEndPoint(hostIPAddress, Ports);

comm_client_conn = new Socket(AddressFamily.InterNetwork,


SocketType.Stream, ProtocolType.Tcp);
comm_client_conn.BeginConnect(fetched_endpoint, Connect,
comm_client_conn);

label_machinename.Text =
dtCentral["device_name"].ToString().Trim();
label_port.Text = dtCentral["protocol"].ToString().Trim() + "
(" + dtCentral["portnumber"].ToString().Trim() + ")";
label1.Text = "PORT NUMBER:";
pictureBox_status.Image = Properties.Resources.correct;

}
else if (dtCentral["protocol"].ToString().ToUpper() == "FILEBASED")
{

try
{
string Class_Name = "LISA." +
dtCentral["device_name"].ToString().Trim() + ",LISA";
this.LISAFILEBASECOMMINTERFACE =
(LISAINTERFACE_FILEBASE)Activator.CreateInstance(System.Type.GetType(Class_Name,
true), (object)dtCentral["deviceid"].ToString().Trim(),
(object)dtCentral["filepath"].ToString().Trim());
label_machinename.Text =
dtCentral["device_name"].ToString().Trim();
label_port.Text = dtCentral["protocol"].ToString().Trim();
label1.Text = "PROTOCOL:";
pictureBox_status.Image = Properties.Resources.correct;
}
catch (Exception ex)
{
sw = File.AppendText(Application.StartupPath + "\\
Instance_FILEBASE.txt");
sw.WriteLine(ex.Message);
sw.Close();
}
}

}
catch (Exception ex)
{
pictureBox_status.Image = Properties.Resources.incorrect;
sw = File.AppendText(Application.StartupPath + "\\
Comm_Port_load.log");
sw.WriteLine(DateTime.Now.ToString() + ex.Message);
sw.Close();
}

//TCP CLIENT

private void CheckConn()


{
try
{
fetched_endpoint = new IPEndPoint(hostIPAddress, Ports);
comm_client_conn = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
comm_client_conn.BeginConnect(fetched_endpoint, Connect,
comm_client_conn);
}
catch (Exception)
{
}
}

private void Connect(IAsyncResult iar)


{
try
{
client_conn = (Socket)iar.AsyncState;
client_conn.EndConnect(iar);
comm_bytemsg = new byte[400];
check = true;
RecieveDataCLIENTCOMMTCP(TCPInstance, "", client_conn);
comm_client_conn.BeginReceive(comm_bytemsg, 0, comm_bytemsg.Length,
SocketFlags.None, Recieve, comm_client_conn);

}
catch (Exception ex)
{
pictureBox_status.Image = Properties.Resources.incorrect;
sw = File.AppendText(Application.StartupPath + "\\
TCPClient_Load.log");
sw.WriteLine(DateTime.Now.ToString() + ex.Message);
sw.Close();
}
}

private void Send(IAsyncResult iar)


{
try
{
Socket client_conn = (Socket)iar.AsyncState;
client_conn.EndSend(iar);
}
catch (Exception ex)
{

}
}

public void Write(string str)


{
try
{
if (comm_client_conn.Connected)
{
byte[] byData = Encoding.ASCII.GetBytes(str);
comm_client_conn.BeginSend(byData, 0, byData.Length,
SocketFlags.None, Send, comm_client_conn);
comm_client_conn.BeginReceive(comm_bytemsg, 0,
comm_bytemsg.Length, SocketFlags.None, Recieve, comm_client_conn);
}
else
{
check = false;
}
}
catch (Exception ex)
{

}
}
public void Recieve(IAsyncResult iar)
{
try
{
Socket client_conn = (Socket)iar.AsyncState;
client_conn.EndReceive(iar);
if (comm_bytemsg.Length != 0)
{
string Data3 = null;
Data3 = Encoding.ASCII.GetString(comm_bytemsg, 0,
comm_bytemsg.Length);
Data3 = Data3.Replace("\0", "").Trim();
if (Data3.Trim() == "")
{
check = false;
}
else
{
AppendTextBox(Data3);
RecieveDataCLIENTCOMMTCP(TCPInstance, Data3, client_conn);
comm_client_conn.BeginReceive(comm_bytemsg, 0,
comm_bytemsg.Length, SocketFlags.None, Recieve, comm_client_conn);
}
}
}
catch (SocketException)
{

}
}

public void AppendTextBox(string value)


{
try
{
richTextBox_analyzerString.Invoke((Action)delegate
{

if (richTextBox_analyzerString.Text.Trim() == string.Empty)
{
richTextBox_analyzerString.Text += value;
}
else
{
richTextBox_analyzerString.Text += Environment.NewLine +
value;
}

});

if (richTextBox_analyzerString.Lines.Length >= 500)


{
richTextBox_analyzerString.Clear();
}
}
catch (Exception ex)
{
sw = File.AppendText(Application.StartupPath + "\\
Data_Recieved_Network_Client.log");
sw.WriteLine(DateTime.Now.ToString() + ex.Message);
sw.Close();
}
}

public void RecieveDataCLIENTCOMMTCP(string InstanceName, string bytes,


Socket ClientStream)
{
try
{
this.LISACLIENTTCPCommInterface =
(LISAINTERFACE_NETWORK_CLIENT)Activator.CreateInstance(System.Type.GetType(Instance
Name, true), (object)("1"));
LISACLIENTTCPCommInterface.ParseDataTCP_Client(bytes,
ClientStream);
}
catch (Exception ex)
{
sw = File.AppendText(Application.StartupPath + "\\TcpCLIENT.txt");
sw.WriteLine(ex.Message);
sw.Close();
}
}

//SERIAL PORT

private void sPort_DataReceived(object sender, SerialDataReceivedEventArgs


e)
{
try
{
pictureBox_status.Image = Properties.Resources.correct;

string oBytes = ObjSPAccess.ReadExisting();

richTextBox_analyzerString.Invoke((Action)delegate
{

if (richTextBox_analyzerString.Text.Trim() == string.Empty)
{
richTextBox_analyzerString.Text += oBytes;
}
else
{
richTextBox_analyzerString.Text += Environment.NewLine +
oBytes;
}

});

if (richTextBox_analyzerString.Lines.Length >= 500)


{
richTextBox_analyzerString.Clear();
}

LisaInterfaceComm_Serial.ParseData_Serial(oBytes, ObjSPAccess);

}
catch (Exception ex)
{
pictureBox_status.Image = Properties.Resources.incorrect;
sw = File.AppendText(Application.StartupPath + "\\
Data_Recieved_Serial.log");
sw.WriteLine(DateTime.Now.ToString() + ex.Message);
sw.Close();
}
}

//TCP SERVER

private void AttendClientsComm()


{
try
{
tcpListener.Start();
while (true)
{
client = tcpListener.AcceptTcpClient();
fetchedEP = (IPEndPoint)client.Client.RemoteEndPoint;
Thread clientThread = new Thread(Operate_Client_Comm);
clientThread.Start(client);
}
}
catch (Exception ex)
{
pictureBox_status.Image = Properties.Resources.incorrect;
sw = File.AppendText(Application.StartupPath + "\\
Data_Recieved_Clients.log");
sw.WriteLine(DateTime.Now.ToString() + ex.Message);
sw.Close();
}

private void Operate_Client_Comm(object client)


{
byte[] message = new byte[4096];
try
{
tcpClient = (TcpClient)client;
if (tcpClient != null && !tcpClient.Connected)
{
richTextBox_analyzerString.Invoke((Action)delegate
{
if (richTextBox_analyzerString.Text.Trim() == string.Empty)
{
richTextBox_analyzerString.Text = DateTime.Now +
"Server Connection Closed";
}
else
{
richTextBox_analyzerString.Text = Environment.NewLine +
DateTime.Now + "Server Connection Closed";
}

});
tcpClient.Close();
}

NetworkStream clientStream = tcpClient.GetStream();


byte[] message2 = new byte[4096];
while (true)
{
int bytesRead2 = 0;
try
{
bytesRead2 = clientStream.Read(message2, 0, 4096);
}
catch (Exception)
{
break;
}
if (bytesRead2 == 0)
{
break;
}
encoder = new ASCIIEncoding();
ReceivedString = encoder.GetString(message2, 0, bytesRead2);

richTextBox_analyzerString.Invoke((Action)delegate
{
if (richTextBox_analyzerString.Text.Trim() == string.Empty)
{
richTextBox_analyzerString.Text += ReceivedString;
}
else
{
richTextBox_analyzerString.Text += Environment.NewLine
+ ReceivedString;
}
});

if (richTextBox_analyzerString.Lines.Length >= 500)


{
richTextBox_analyzerString.Clear();
}
pictureBox_status.Image = Properties.Resources.correct; //

RecieveDataTCPComm(TCPInstance, ReceivedString, clientStream);

}
tcpClient.Close();

if (!tcpClient.Connected)
{
richTextBox_analyzerString.Invoke((Action)delegate
{
richTextBox_analyzerString.Text += Environment.NewLine +
DateTime.Now + "Disconnected from Client IP Address :" + fetchedEP;
});
AttendClientsComm();
}
}
catch (Exception ex)
{
pictureBox_status.Image = Properties.Resources.incorrect;
sw = File.AppendText(Application.StartupPath + "\\Tc1p.txt");
sw.WriteLine(ex.Message);
sw.Close();
}
}

public void RecieveDataTCPComm(string InstanceName, string bytes,


NetworkStream ClientStream)
{
try
{
this.LisaInterfaceComm_Network =
(LISAINTERFACE_NETWORK)Activator.CreateInstance(System.Type.GetType(InstanceName,
true), (object)("1"));
LisaInterfaceComm_Network.ParseDataTCP_Server(bytes, ClientStream);
}
catch (Exception ex)
{
pictureBox_status.Image = Properties.Resources.incorrect;
sw = File.AppendText(Application.StartupPath + "\\
Receivedt_Tcp.txt");
sw.WriteLine(ex.Message);
sw.Close();
}
}

private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)


{

private void UserControlAnalyzer_Load(object sender, EventArgs e)


{

}
}
}

You might also like