C# InvaildOperationException Collection was modified - c#

I am having an issue with my C# application, it runs fine or x amount of minutes but hits an error at some point which complains about 'InvaildOperationException Collection was modified'. I am quite new to C# and i am unable to find the solution even after reading other posts.
From what i can tell after reading the posts it is something to do with my for loop, could anyone be so kind as to tell me what i have done wrong.
The error i think is caused by the UpdateGraph function.
The code is designed to connect to a Cisco router and get the cellular data via Serial and show it in a graph and richTextBox which is all working minus the error i get at some point :(
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Cisco_Cellular_Diagnostics
{
public partial class Form1 : Form
{
SerialPort serialPort;
string[] ports;
string rawStrings;
int ComPort_ComboBoxIndex;
bool serialIsOpen = false;
bool autoScroll = false;
readonly String executingFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
TextWriter txtFile;
List<int> bandwidthArray = new List<int>();
List<int> rssiArray = new List<int>();
List<int> rsrpArray = new List<int>();
List<int> rsrqArray = new List<int>();
List<int> snrArray = new List<int>();
List<int> nearbyCellsArray = new List<int>();
private static System.Timers.Timer pollingTimer;
public Form1()
{
InitializeComponent();
ports = SerialPort.GetPortNames();
ToolTip toolTip1 = new ToolTip
{
AutoPopDelay = 5000,
InitialDelay = 500,
ReshowDelay = 500,
ShowAlways = true
};
ComPortComboBox.Items.AddRange(ports);
ComPortComboBox.SelectedIndex = 0;
autoScroll = true;
pollingTimer = new System.Timers.Timer(5000);
pollingTimer.Elapsed += new ElapsedEventHandler(SendCellularCmd);
Console.WriteLine("executingFolder = " + executingFolder);
String fileDate = DateTime.Today.ToString("d").Replace("/", "-");
txtFile = new StreamWriter(executingFolder + "\\Cisco Celluar log " + fileDate + ".txt", true);
LoadChart();
}
private void LoadChart()
{
var chart = chart1.ChartAreas[0];
chart.AxisX.IntervalType = DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisX.LabelStyle.IsEndLabelVisible = true;
chart.AxisX.Minimum = 0;
chart.AxisY.Minimum = -128;
chart.AxisY.Maximum = 128;
chart.AxisX.Interval = 1;
chart.AxisY.Interval = 16;
chart1.Series[0].IsVisibleInLegend = false;
chart.AxisX.Title = "Reading";
chart.AxisY.Title = "dB";
//chart1.Series[0].XValueType = ChartValueType.DateTime;
chart1.Series.Add("Bandwidth");
chart1.Series["Bandwidth"].ChartType = SeriesChartType.Line;
chart1.Series["Bandwidth"].Color = Color.Green;
chart1.Series["Bandwidth"].BorderWidth = 8;
chart1.Series.Add("RSSI");
chart1.Series["RSSI"].ChartType = SeriesChartType.Line;
chart1.Series["RSSI"].Color = Color.Blue;
chart1.Series["RSSI"].BorderWidth = 8;
chart1.Series.Add("RSRP");
chart1.Series["RSRP"].ChartType = SeriesChartType.Line;
chart1.Series["RSRP"].Color = Color.Yellow;
chart1.Series["RSRP"].BorderWidth = 8;
chart1.Series.Add("RSRQ");
chart1.Series["RSRQ"].ChartType = SeriesChartType.Line;
chart1.Series["RSRQ"].Color = Color.Red;
chart1.Series["RSRQ"].BorderWidth = 8;
chart1.Series.Add("SNR");
chart1.Series["SNR"].ChartType = SeriesChartType.Line;
chart1.Series["SNR"].Color = Color.Purple;
chart1.Series["SNR"].BorderWidth = 8;
chart1.Series.Add("Nearby cells");
chart1.Series["Nearby cells"].ChartType = SeriesChartType.Line;
chart1.Series["Nearby cells"].Color = Color.DarkGray;
chart1.Series["Nearby cells"].BorderWidth = 8;
chart1.Series["Bandwidth"].Points.AddXY(0, 0);
chart1.Series["RSSI"].Points.AddXY(0, 0);
chart1.Series["RSRP"].Points.AddXY(0, 0);
chart1.Series["RSRQ"].Points.AddXY(0, 0);
chart1.Series["SNR"].Points.AddXY(0, 0);
chart1.Series["Nearby cells"].Points.AddXY(0, 0);
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
BeginInvoke((MethodInvoker)delegate ()
{
rawStrings += indata;
//txtFile.Write(indata);
//txtFile.WriteLine(DateTime.Now + "\n");
ReceivedDataRichTextBox.AppendText(indata);
if (autoScroll)
ReceivedDataRichTextBox.ScrollToCaret();
});
}
private void OpenSerial_Click(object sender, EventArgs e)
{
ComPort_ComboBoxIndex = ComPortComboBox.SelectedIndex;
if (ComPort_ComboBoxIndex >= 0 && !serialIsOpen)
{
try
{
string selectedCOM = ComPortComboBox.SelectedItem.ToString();
serialPort = new SerialPort(selectedCOM, 9600);
serialPort.ReadTimeout = 3000;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
serialPort.Handshake = Handshake.None;
serialIsOpen = true;
serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
OpenSerialOne.Text = "Close Serial";
serialPort.Open();
LogIntoCLI();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else if (serialIsOpen)
{
try
{
serialPort.Write("exit");
serialPort.Close();
txtFile.Close();
pollingTimer.Enabled = false;
serialIsOpen = false;
OpenSerialOne.Text = "Open Serial";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
else
{
MessageBox.Show("Error, check the baud Rate and COM port is selected and try again.");
}
}
private void LogIntoCLI()
{
if (serialIsOpen)
{
try
{
serialPort.Write("\r");
Thread.Sleep(2000);
serialPort.Write("\r"); // "exit\r"
Thread.Sleep(2000);
serialPort.Write("enable\r");
Thread.Sleep(3000);
serialPort.Write("met0cean\r");
Thread.Sleep(2000);
pollingTimer.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void SendCellularCmd(object sender, ElapsedEventArgs e)
{
ExtractData();
serialPort.Write("show cell 0 radio\r");
Console.WriteLine("sending command...");
}
private void ExtractData()
{
try
{
txtFile.Write(rawStrings);
txtFile.WriteLine(DateTime.Now + "\n");
String[] listOfStrings = rawStrings.Split('\n');
rawStrings = "";
foreach (String value in listOfStrings)
{
String[] strlist = value.Split(' ');
if (value.IndexOf("Bandwidth") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "Bandwidth", ref bandwidthArray);
}
else if (value.IndexOf("RSSI") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSSI", ref rssiArray);
}
else if (value.IndexOf("RSRP") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSRP", ref rsrpArray);
}
else if (value.IndexOf("RSRQ") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSRQ", ref rsrqArray);
}
else if (value.IndexOf("SNR") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "SNR", ref snrArray);
}
else if (value.IndexOf("nearby cells") >= 0 && strlist.Length == 6)
{
if (int.TryParse(strlist[5], out int extractedValue))
UpdateGraph(extractedValue, "Nearby cells", ref nearbyCellsArray);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void UpdateGraph(int a_value, String a_ID, ref List<int> a_List)
{
try
{
// keep the list count to 20 items
if (a_List.Count == 20)
a_List.RemoveAt(0);
a_List.Add(a_value);
// clear chart and add items
chart1.Series[a_ID].Points.Clear();
for (int i = 0; i < a_List.Count; i++)
{
chart1.Series[a_ID].Points.AddXY(i, a_List[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing Application", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
try
{
txtFile.Close();
serialPort.Write("exit");
serialPort.Close();
pollingTimer.Enabled = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
break;
}
}
private void PollingTimeNumericUpDown_ValueChanged(object sender, EventArgs e)
{
pollingTimer.Interval = Convert.ToDouble(PollingTimeNumericUpDown.Value);
}
private void ClearDataButton_Click(object sender, EventArgs e)
{
ReceivedDataRichTextBox.Clear();
chart1.Series["Bandwidth"].Points.Clear();
chart1.Series["RSSI"].Points.Clear();
chart1.Series["RSRP"].Points.Clear();
chart1.Series["RSRQ"].Points.Clear();
chart1.Series["SNR"].Points.Clear();
chart1.Series["Nearby cells"].Points.Clear();
chart1.Series["Bandwidth"].Points.AddXY(0, 0);
chart1.Series["RSSI"].Points.AddXY(0, 0);
chart1.Series["RSRP"].Points.AddXY(0, 0);
chart1.Series["RSRQ"].Points.AddXY(0, 0);
chart1.Series["SNR"].Points.AddXY(0, 0);
chart1.Series["Nearby cells"].Points.AddXY(0, 0);
}
private void SendManualCmd_Click(object sender, EventArgs e)
{
try
{
serialPort.Write(textBox1.Text + "\r");
textBox1.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void ReloadComPortsButton_Click(object sender, EventArgs e)
{
ComPortComboBox.Items.Clear();
ports = SerialPort.GetPortNames();
ComPortComboBox.Items.AddRange(ports);
}
private void ComComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// CiscoComPort = ComPortComboBox.SelectedItem.ToString();
}
}
}

Related

Not getting response from Lane Control Board

I'm trying to get inputs/outputs from a LCB(lane control board),which in serial. I'm using prolific usb-serial as the interface . I'm new to programming,but i've managed to get send/receive inputs when i shorted pin 2 and 3 of DB9 together . But when i plugged the db9 connector to the LCB , it can send , but not receiving any .
I'm using VS2010 in Windows 10.
Below are my snippets ;
namespace serialPort_wengweng
{
public partial class Form1 : Form
{
byte[] DataReceived = new byte[4096];
byte[] DataTransmitted = new byte[15] { 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15 };
ArrayList ar = new ArrayList();
//------------------------------------LCB input properties here-START------------------------//
String LCBInput;
Boolean i1, i2, i3, i4, i5, i6, i7, i8 = false;
//------------------------------------LCB input properties here-START------------------------//
public Form1()
{
InitializeComponent();
this.serialPort1.DataReceived +=new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void btnConnect_Click(object sender, EventArgs e)
{
Console.Write("Connect button pressed .. ");
//if (serialPort1.IsOpen == true)
//{
//}
//else
// MessageBox.Show("");
if (btnConnect.Text == "Connect")
{
serialPort1.PortName = Convert.ToString(cboPortNames.SelectedItem);
serialPort1.BaudRate = Convert.ToInt32(cboBaudRate.SelectedItem);
serialPort1.DataBits = Convert.ToInt32(cboDataBits.SelectedItem);
serialPort1.DtrEnable = true;
serialPort1.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandshake.SelectedItem.ToString());
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.SelectedItem.ToString());
serialPort1.RtsEnable = true;
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.SelectedItem.ToString());
try
{
if (serialPort1.IsOpen) serialPort1.Close();
serialPort1.Open();
progressBar.Value = 100;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
btnConnect.Text = "Disconnect";
}
else
{
btnConnect.Text = "Connect";
if (serialPort1.IsOpen) serialPort1.Close();
progressBar.Value = 0;
txtTX.Text = String.Empty;
txtRXAll.Text = String.Empty;
txtRXParsing1.Text = String.Empty;
}
Console.WriteLine("Done!");
}
void UpdateTextBox(TextBox objTextBox, String DataParsing)
{
Console.WriteLine("In Update Text Box...");
objTextBox.AppendText(DataParsing);
Console.WriteLine("Done!");
}
void ReceivedData(TextBox objTextBox, String DataParsing)
{
Console.WriteLine("In ReceivedData...");
if (objTextBox.InvokeRequired)
{
this.Invoke(new Action<TextBox, String>(UpdateTextBox), new object[] { objTextBox, DataParsing });
}
Console.WriteLine("Done!");
}
private void PrintValues(ArrayList ar, ComboBox objComboBox)
{
Console.Write("Printing Values... ");
try
{
if (objComboBox.Name == "cboPortNames")
{
foreach (var v in ar)
{
objComboBox.Items.Add("COM" + v);
}
}
else
{
foreach (var v in ar)
{
objComboBox.Items.Add(v);
}
}
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
Console.WriteLine("Print Values T.T");
}
Console.WriteLine("Done!");
}
private void Form1_Load(object sender, EventArgs e)
{
Console.Write("In Form Load()");
GetPortNames();
GetBaudRate();
GetDataBits();
GetParity();
GetStopBits();
GetHandshake();
txtTX.Text = ASCIIEncoding.ASCII.GetString(DataTransmitted);
Console.WriteLine("Done!");
}
void GetPortNames()
{
Console.Write("Getting Port Names..");
ar.Clear();
foreach (String s in SerialPort.GetPortNames())
{
ar.Add(s.Substring(3));
}
ar.Sort();
PrintValues(ar, cboPortNames);
cboPortNames.SelectedIndex = 0;
Console.WriteLine("Done!");
}
void GetBaudRate()
{
Console.Write("Getting BaudRate..");
ar.Clear();
ar.Add(110);
ar.Add(300);
ar.Add(1200);
ar.Add(2400);
ar.Add(4800);
ar.Add(9600);
ar.Add(19200);
ar.Add(38400);
ar.Add(57600);
ar.Add(115200);
ar.Add(230400);
ar.Add(460800);
ar.Add(921600);
PrintValues(ar, cboBaudRate);
cboBaudRate.SelectedIndex = 5;
Console.WriteLine("Done!");
}
void GetDataBits()
{
Console.Write("Getting Data Bits..");
ar.Clear();
for (int i = 5; i <= 8; i++)
{
ar.Add(i);
}
PrintValues(ar, cboDataBits);
cboDataBits.SelectedIndex = 3;
Console.WriteLine("Done!");
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.Write("In Data Received ..");
int i = 0;
string dtString="";
string[] dtArray; // data string saving in here
Thread.Sleep(500); // wait data ready
while (serialPort1.BytesToRead > 0) // if data ready in buffer
{
DataReceived[i] = Convert.ToByte(serialPort1.ReadByte()); // read data serial & saving to array byte
i++; // counter buffer
}
if (i == 15 && DataReceived[14]==15)
{
dtString = ASCIIEncoding.ASCII.GetString(DataReceived); // convert array byte to string
dtArray = dtString.Split((char)44); // parsing string data with separator char(44)
ReceivedData(txtRXAll, dtString); // complete receive data show in here
ReceivedData(txtRXParsing1, dtArray[0]); // data first show in here
}
Console.WriteLine("Done!");
}
private void btnExit_Click(object sender, EventArgs e)
{
Console.Write("Button Exit Pressed..");
if (serialPort1.IsOpen == true)
{
MessageBox.Show("Force quit serial port", "Exit", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
}
else {
Application.Exit();
Console.WriteLine("Serial port closed,quitting app now.");
Thread.Sleep(1000);
}
Console.WriteLine("Done!");
}
private void btnSend_Click(object sender, EventArgs e)
{
Console.Write("Button Send Pressed..");
if (serialPort1.IsOpen)
{
Console.WriteLine("Shoulda write something.");
var collector = new DataCollector("COM6", ProcessMeasurement);
serialPort1.Write(txtTX.Text);
Thread.Sleep(500);
//Console.WriteLine(serialPort1.Read());
}
else {
MessageBox.Show("Not receiving anything", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Console.WriteLine("Done!");
}
private void ProcessMeasurement(List<byte> bytes)
{
Console.WriteLine("In process measurement...");
}
private void GetHandshake()
{
Console.WriteLine("Get Handshake ...");
try
{
ar.Clear();
foreach (String s in Enum.GetNames(typeof(Handshake)))
{
ar.Add(s);
}
PrintValues(ar, cboHandshake);
cboHandshake.SelectedIndex = 0;
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
}
}
private void GetStopBits()
{
Console.WriteLine("Get StopBits ....");
try
{
ar.Clear();
foreach (String s in Enum.GetNames(typeof(StopBits)))
{
if (s != "None") ar.Add(s);
}
PrintValues(ar, cboStopBits);
cboStopBits.SelectedIndex = 0;
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
}
}
private void GetParity()
{
Console.WriteLine("Get Parity ....");
try
{
ar.Clear();
foreach (String s in Enum.GetNames(typeof(Parity)))
{
ar.Add(s);
}
PrintValues(ar, cboParity);
cboParity.SelectedIndex = 0;
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
}
}
}
}
And here is DataCollector class,
namespace serialPort_wengweng
{
class DataCollector
{
private readonly Action<List<byte>> _processMeasurement;
private readonly string _port;
private SerialPort _serialPort;
private const int SizeOfMeasurement = 4;
List<byte> Data = new List<byte>();
public DataCollector(string port, Action<List<byte>> processMeasurement)
{
Console.WriteLine("in Data Collector ..");
_processMeasurement = processMeasurement;
_serialPort = new SerialPort(port);
_serialPort.DataReceived += SerialPortDataReceived;
Console.WriteLine("Done!");
}
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (_serialPort.BytesToRead > 0)
{
var count = _serialPort.BytesToRead;
var bytes = new byte[count];
Console.WriteLine(_serialPort.Read(bytes, 0, count));
AddBytes(bytes);
}
}
private void AddBytes(byte[] bytes)
{
Data.AddRange(bytes);
while (Data.Count > SizeOfMeasurement)
{
var measurementData = Data.GetRange(0, SizeOfMeasurement);
Data.RemoveRange(0, SizeOfMeasurement);
if (_processMeasurement != null) _processMeasurement(measurementData);
}
}
}
}

Real Time Chart with Serial port Data in C#

I want to drawing real time chart in c# with my data that read from serial port Arduino device i didn't know how can i do this with c#.
i want 2d and 3d chart in my program anyone can help me ?
in my program i read data from serial port and time of data has been arrived so my chart be have 2 data one of them is info and another is time.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using port.dbDataSetTableAdapters;
using System.Threading.Tasks;
namespace Factory_Performance
{
public partial class FrmMain : Form
{
int sfs = 0;
string filename;
string line;
string s;
string temp="";
string temp1="";
Series series = new Series();
SerialPort ComPort = new SerialPort();
internal delegate void SerialDataReceivedEventHandlerDelegate(object sender, SerialDataReceivedEventArgs e);
internal delegate void SerialPinChangedEventHandlerDelegate(object sender, SerialPinChangedEventArgs e);
private SerialPinChangedEventHandler SerialPinChangedEventHandler1;
delegate void SetTextCallback(int ReadByte);
int InputData = 0;
private int CountData;
private string StrData;
double[] Values;
public FrmMain()
{
InitializeComponent();
SerialPinChangedEventHandler1 = new SerialPinChangedEventHandler(PinChanged);
ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
}
private double calculate_input(int s2, int s3)
{
return double.Parse(s2.ToString() + "/" + s3.ToString());
}
private void GetAllIDInDB()
{
tblIDTableAdapter.Fill(dbDataSet.TblID);
CmbID.Items.Clear();
for (int i = 0; i < dbDataSet.TblID.Rows.Count; i++)
CmbID.Items.Add(dbDataSet.TblID.Rows[i]["ID"].ToString());
}
private void GetAllID_DetailsInDB(int ID)
{
tblID_DetailsTableAdapter.FillByID(dbDataSet.TblID_Details, ID);
listreadtxt.Items.Clear();
for (int i = 0; i < dbDataSet.TblID_Details.Rows.Count; i++)
listreadtxt.Items.Add(dbDataSet.TblID_Details.Rows[i]["Value"].ToString());
}
private void GetInfoPorts()
{
try
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
cboPorts.Items.Clear();
cboBaudRate.Items.Clear();
cboStopBits.Items.Clear();
cboParity.Items.Clear();
cboHandShaking.Items.Clear();
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(8);
cboDataBits.Items.Add(7);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
catch
{
MessageBox.Show("خطا در گرفتن اطلاعات پورت");
}
}
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadByte();
object firstByte = InputData;
if (ComPort.IsOpen==true)
{
s = Convert.ToString(Convert.ToChar(firstByte));
temp1 += s;
lock (firstByte) {
if (Convert.ToInt32(firstByte) == 13)
{
temp = temp1;
temp1 = "";
ComPort.DiscardInBuffer();
ComPort.DiscardOutBuffer();
LstGetInfo.BeginInvoke(new Action(()=>
{
if (temp !=null)
{
LstGetInfo.Items.Add(temp);
if (LstGetInfo.Items.Count >= 100)
{
LstGetInfo.Items.Clear();
}
FileStream fs = new FileStream(filename, FileMode.Append);
var data = System.Text.Encoding.UTF8.GetBytes(String.Format("{0} {1}", temp, DateTime.Now.ToString("hh mm ss")) +"\r\n");
fs.Write(data, 0, data.Length);
fs.Close();
}
}));
LstGetInfo.BeginInvoke(new Action(() =>
{
LstGetInfo.TopIndex = LstGetInfo.Items.Count - 1;
}));
}
}
}
}
internal void PinChanged(object sender, SerialPinChangedEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = (int)StrData[i];
Array.Reverse(Values);
chart1.Titles.Clear();
chart1.Titles.Add(TxtTitle.Text);
chart1.Series.Clear();
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
chart1.Series.Add(series);
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void CmbPalette_SelectedIndexChanged(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
private void FrmMain_Load(object sender, EventArgs e)
{
chart2.Series.Clear();
// TODO: This line of code loads data into the 'dbDataSet.TblID_Details' table. You can move, or remove it, as needed.
this.tblID_DetailsTableAdapter.Fill(this.dbDataSet.TblID_Details);
// TODO: This line of code loads data into the 'dbDataSet.TblID' table. You can move, or remove it, as needed.
this.tblIDTableAdapter.Fill(this.dbDataSet.TblID);
GetInfoPorts();
CmbPalette.SelectedIndex = 1;
CmbChartType.SelectedIndex = 4;
CountData = 0;
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
GetInfoPorts();
}
private void btnPortState_Click(object sender, EventArgs e)
{
if (sfs == 1) {
try
{
if (btnPortState.Text == "ارتباط با دستگاه")
{
temp1 = "";
temp = "";
btnPortState.Text = "قطع ارتباط با دستگاه";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
LstGetInfo.Items.Clear();
}
else if (btnPortState.Text == "قطع ارتباط با دستگاه")
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
}
}
catch
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
MessageBox.Show("خطا در انجام عملیات");
}
}
else
{
MessageBox.Show("برای ذخیزه فایل محلی را انتخاب کنید");
}
}
private void button1_Click_1(object sender, EventArgs e)
{
savedata();
}
private void savedata()
{
try
{
if (LstGetInfo.Items.Count < 0) return;
int ItemCount = int.Parse(listreadtxt.Items[0].ToString());
int ItemIDCount = 0;
int ItemID = 0;
int ItemValue1 = 0, ItemValue2 = 0;
TblIDTableAdapter tblid = new TblIDTableAdapter();
TblID_DetailsTableAdapter tblid_details = new TblID_DetailsTableAdapter();
tblid.DeleteAllID();
LstGetInfo.Items.RemoveAt(0);
for (int i = 0; i < ItemCount; i++)
{
ItemID = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
tblid.Insert(ItemID);
if (LstGetInfo.Items.Count > 0)
{
ItemIDCount = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
for (int j = 0; j < ItemIDCount; j += 2)
{
ItemValue1 = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
ItemValue2 = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
tblid_details.Insert(ItemID, calculate_input(ItemValue1, ItemValue2));
}
}
}
}
catch
{
// MessageBox.Show("در ساخت نمودار مشکلی پیش آمده است");
try
{
LstGetInfo.Items.RemoveAt(0);
}
catch
{
}
}
finally
{
GetAllIDInDB();
}
ShowChart();
}
private void CmbID_SelectedIndexChanged(object sender, EventArgs e)
{
GetAllID_DetailsInDB(int.Parse(CmbID.Text));
if (listreadtxt.Items.Count > 0)
ShowChart();
}
private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged_1(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
private void ShowChart()
{
CountData =listreadtxt.Items.Count;
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = double.Parse(listreadtxt.Items[i].ToString());
chart1.Titles.Clear();
chart1.Titles.Add(TxtTitle.Text);
chart1.Series.Clear();
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
chart1.Series.Add(series);
}
private void button3_Click_3(object sender, EventArgs e)
{
GetAllIDInDB();
}
private void button4_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = string.Empty;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) {
listreadtxt.Items.Clear();
Stream fs = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(fs);
while ((line = reader.ReadLine()) != null)
{
listreadtxt.Items.Add(line);
}
reader.Close();
}
}
public void button5_Click(object sender, EventArgs e)
{
dateTimePicker1.BeginInvoke(new Action(() =>
{
DialogResult result1 = saveFileDialog1.ShowDialog();
dateTimePicker1.Format = DateTimePickerFormat.Custom;
string formatvalue =Convert.ToString( dateTimePicker1.Value.Date.ToString(" yyyy-MM-dd"));
filename = saveFileDialog1.FileName + formatvalue + ".csv";
if (result1==DialogResult.OK)
{
sfs = 1;
}
}));
}
private void button6_Click(object sender, EventArgs e)
{
try {
ComPort.Close();
CountData = LstGetInfo.Items.Count;
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = double.Parse(LstGetInfo.Items[i].ToString());
chart2.Titles.Clear();
chart2.Titles.Add(TxtTitle.Text);
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(System.DateTime.Now, Values[i]);
chart2.Series.Add(series);
}
catch
{
LstGetInfo.Items.Remove(0);
}
finally
{
ComPort.Open();
}
}
}
}
The problem is that in line
series.Points.AddXY(System.DateTime.Now, Values[i]);
you are adding points with the same X value set to System.DateTime.Now. In result you have only one point on axis X.
I found solution for my problem
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Threading.Tasks;
using System.Threading;
namespace chart
{
public partial class Form1 : Form
{
string s;
int InputData = 0;
private delegate void CanIJust();
Series series = new Series();
private List<int> _valuelist;
private Thread _thread;
private CanIJust _DoIt;
private Random _ran;
private int _interval;
private List<double> _timelist;
private List<int> _customValueList;
SerialPort ComPort = new SerialPort();
int sfs = 0;
string temp = "";
string temp1 = "";
public Form1()
{
InitializeComponent();
chart1.ChartAreas[0].AxisX.IsStartedFromZero = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = false;
chart1.Series[0].XValueType = ChartValueType.Time;
chart1.ChartAreas[0].AxisX.ScaleView.SizeType = DateTimeIntervalType.Seconds;
chart1.ChartAreas[0].AxisX.IntervalAutoMode = IntervalAutoMode.FixedCount;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Seconds;
chart1.ChartAreas[0].AxisX.Interval = 0;
_valuelist = new List<int>();
_ran = new Random();
_interval = 500;
tbupdateinterval.Text = "500";
GoBoy();
_timelist = new List<double>();
_customValueList = new List<int>();
}
private void GetInfoPorts()
{
try
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
cboPorts.Items.Clear();
cboBaudRate.Items.Clear();
cboStopBits.Items.Clear();
cboParity.Items.Clear();
cboHandShaking.Items.Clear();
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(8);
cboDataBits.Items.Add(7);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
catch
{
MessageBox.Show("خطا در گرفتن اطلاعات پورت");
}
}
private void GoBoy()
{
_DoIt += new CanIJust(AddData);
DateTime now = DateTime.Now;
chart1.ChartAreas[0].AxisX.Minimum = now.ToOADate();
chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(10).ToOADate();
_thread = new Thread(new ThreadStart(ComeOnYouThread));
_thread.Start();
}
private void ComeOnYouThread()
{
while (true)
try
{
chart1.Invoke(_DoIt);
Thread.Sleep(_interval);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Exception:" + e.ToString());
}
}
private void AddData()
{
DateTime now = DateTime.Now;
InputData = ComPort.ReadByte();
object firstByte = InputData;
if (ComPort.IsOpen == true)
{
s = Convert.ToString(Convert.ToChar(firstByte));
temp1 += s;
lock (firstByte)
{
if (Convert.ToInt32(firstByte) == 13)
{
temp = temp1;
temp1 = "";
ComPort.DiscardInBuffer();
ComPort.DiscardOutBuffer();
_valuelist.Add(Convert.ToInt32(temp));
chart1.ResetAutoValues();
if (chart1.Series[0].Points.Count > 0)
{
while (chart1.Series[0].Points[0].XValue < now.AddSeconds(-5).ToOADate())
{
chart1.Series[0].Points.RemoveAt(0);
chart1.ChartAreas[0].AxisX.Minimum = chart1.Series[0].Points[0].XValue;
chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(5).ToOADate();
}
}
chart1.Series[0].Points.AddXY(now.ToOADate(), _valuelist[_valuelist.Count - 1]);
chart1.Invalidate();
}
}
}
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (_thread != null)
_thread.Abort();
}
private void btn_2D_Click_1(object sender, EventArgs e)
{
btn_2D.Enabled = false;
btn_3D.Enabled = true;
chart1.ChartAreas[0].Area3DStyle.Enable3D = false;
}
private void btn_3D_Click_1(object sender, EventArgs e)
{
btn_2D.Enabled = true;
btn_3D.Enabled = false;
chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
}
private void btn_add_Click(object sender, EventArgs e)
{
_customValueList.Add(_ran.Next(0, 100));
_timelist.Add(DateTime.Now.ToOADate());
updatesecondChart();
}
private void updatesecondChart()
{
chart2.Series[0].Points.AddXY(_timelist[_timelist.Count - 1], _customValueList[_customValueList.Count-1]);
chart2.Invalidate();
}
private void btn_serialize_Click(object sender, EventArgs e)
{
}
private void btn_updateInterval_Click(object sender, EventArgs e)
{
int interval = 0;
if (int.TryParse(tbupdateinterval.Text, out interval))
{
if (interval > 0)
_interval = interval;
else
MessageBox.Show("بازه زمانی باید بیشتر از 0 باشند");
}
else
{
MessageBox.Show("I nappropriate Data.");
}
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
GetInfoPorts();
}
private void btnPortState_Click(object sender, EventArgs e)
{
//if (sfs == 1)
//{
try
{
if (btnPortState.Text == "ارتباط با دستگاه")
{
temp1 = "";
temp = "";
btnPortState.Text = "قطع ارتباط با دستگاه";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
AddData();
}
else if (btnPortState.Text == "قطع ارتباط با دستگاه")
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
}
}
catch
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
MessageBox.Show("خطا در انجام عملیات");
}
}
//else
//{
// MessageBox.Show("برای ذخیزه فایل محلی را انتخاب کنید");
//}
//}
private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
}
}

c# Serial DataReceived very slow

I've trying to communicate with an Arduino Due in C#. The communikation works quite well, but my DataReceived handler needs about 1 second to react. This is my problem because I have to send up to 1 billion (1*10E9) commands.
If I activate a DEBUG Setting in the Arduino, it tells me that it's need 64 Milliseconds for a command. I think the C# the App should get it no later than 80 Milliseconds after sending it.
Here is a Part of the Code:
StopWatch s1 = new StopWatch();
private void Open_Port()
{
string port = null;
int baud = 0;
bool ERR = false;
if ((COM_cb.SelectedItem != null) | (BAUD_cb.SelectedItem != null))
{
port = this.COM_cb.GetItemText(this.COM_cb.SelectedItem);
baud = Convert.ToInt32(this.BAUD_cb.GetItemText(this.BAUD_cb.SelectedItem));
ERR = false;
}
else
{
ERR = true;
System.Windows.Forms.MessageBox.Show("Error Msg");
}
if (ERR == false)
{
serialPort1.PortName = port;
serialPort1.BaudRate = baud;
serialPort1.Open();
}
if (serialPort1.IsOpen)//Kalibrieren der Buttons
{
OPEN_btn.Enabled = false;
CLOSE_btn.Enabled = true;
textBox1.ReadOnly = false;
ERR = true;
}
}
private void Print_Click(object sender, EventArgs e) // start
{
Thread t = new Thread(transmit_pic);
t.Start();
}
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
s1.Stop();
//Till this line it take 1 Second after sending
//string t = "";
int byt = serialPort1.BytesToRead;
byte[] buffer = new byte[1];
for (int i = 0; i < byt; i++)
{
serialPort1.Read(buffer, 0, 1);
if(buffer[0] == '0') {
got_answer = true;
}
//t += (char)buffer[0];
}
//RxString= t;
//this.Invoke(new EventHandler(DisplayText));
}
private void sendAktion(int[,] data)
{
string s = int_to_string(data, false);
Console.Write("Send->");
serialPort1.Write(s);
s1.Start();
got_answer = false;
int i = 0;
while (!got_answer) { i++; } //wait for answer
i = 0;
Console.WriteLine("back again ");
}
private void transmit_pic()
{
stop = false;
Bitmap bm = new Bitmap(img);
if (!serialPort1.IsOpen)
{
MessageBox.Show("Open the Serial Port first!");
}
else
{
int size_X = bm.Width;
int size_Y = bm.Height;
for (int h = 0; h < size_Y; h++)
{
for (int w = 0; w < size_X; w++)
{
if(/*somthing happend*/){
//get data...
sendAktion(data)
}
}
}
Console.WriteLine("DONE");
}
}
Does anyone an Idea why c# needs so long to call the datahandler?
Sincere regards,
Fabian Harmsen
UPDATE
- Added comment to DataHandler (24.02.2016 16:30 Europa/Berlin)
The problem lies in the serialPort1_DataReceived received data handler.
I ran a separate thread with a while(true) loop and serial.ReadLine(), all works perfectly.
Hope someone else doesn't need to spend 3 hours fixing this.
using System.Threading;
public void main()
{
setup();
Thread readThread = new Thread(Read);
readThread.Start();
}
public void Read()
{
while(true)
{
try
{
string message = serialPort1.ReadLine();
}
catch (Exception)
{ }
}

How to add realtime data from OPC client to user control using c#

I created an OPC client to connect to KepServerEX, I got realtime data from KepServerEX and now I want to add realtime data to user control that contains a textbox.
Realtime data will be updated via value_changed event.
I created Windows Form Application and added textbox to Form to display realtime value, I can not post images here.
This is my code:
namespace OPC_Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OPCServer KepServer;
OPCGroups KepGroups;
OPCGroup KepGroup;
OPCItems KepItems;
OPCItem KepItem;
string strHostIP = "";
string strHostName = "";
bool opc_connected = false;
int itmHandleClient = 0;
int itmHandleServer = 0;
private bool CreateGroup()
{
try
{
KepGroups = KepServer.OPCGroups;
KepGroup = KepGroups.Add("OPCDOTNETGROUP");
SetGroupProperty();
KepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
KepGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete);
KepItems = KepGroup.OPCItems;
}
catch (Exception)
{
return false;
}
return true;
}
private void SetGroupProperty()
{
KepServer.OPCGroups.DefaultGroupIsActive = true;
KepServer.OPCGroups.DefaultGroupDeadband = 0;
KepGroup.UpdateRate = 1000;
KepGroup.IsActive = true;
KepGroup.IsSubscribed = true;
}
private void RecurBrowse(OPCBrowser OPCBrowser)
{
OPCBrowser.ShowBranches();
OPCBrowser.ShowLeafs(true);
listBox1.Items.Clear();
foreach (object turn in OPCBrowser)
{
bool bl = turn.ToString().Contains("System") ;
if (bl == false)
{
if (!Regex.IsMatch(turn.ToString(), #"^(\w+\.\w+\.\w+)$"))
{
}
else
{
listBox1.Items.Add(turn.ToString());
}
}
}
}
private bool ConnectRemoteServer(string remoteServerIP, string remoteServerName)
{
try
{
KepServer.Connect(remoteServerName, remoteServerIP);
}
catch (Exception ex)
{
MessageBox.Show(""+ex);
return false;
}
return true;
}
// Write the TAG value when executed event
void KepGroup_AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)
{
lblState.Text = "";
for (int i = 1; i <= NumItems; i++)
{
lblState.Text += "Tran:" + TransactionID.ToString() + " CH:" + ClientHandles.GetValue(i).ToString() + "Error:" + Errors.GetValue(i).ToString();
}
}
void KepGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
for (int i = 1; i <= NumItems; i++)
{
if (Qualities.GetValue(i).ToString() == "192")
{
// add realtime value to texbox to display
txtTagValue.Text = ItemValues.GetValue(i).ToString();
txtQualities.Text = Qualities.GetValue(i).ToString();
txtTimeStamps.Text = TimeStamps.GetValue(i).ToString();
}
else
{
MessageBox.Show("disconnected to opc server");
txtQualities.Text = Qualities.GetValue(i).ToString();
txtTimeStamps.Text = TimeStamps.GetValue(i).ToString();
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (itmHandleClient != 0)
{
Array Errors;
OPCItem bItem = KepItems.GetOPCItem(itmHandleServer);
int[] temp = new int[2] { 0, bItem.ServerHandle };
Array serverHandle = (Array)temp;
KepItems.Remove(KepItems.Count, ref serverHandle, out Errors);
}
itmHandleClient = 1;
KepItem = KepItems.AddItem(listBox1.SelectedItem.ToString(), itmHandleClient);
itmHandleServer = KepItem.ServerHandle;
}
catch (Exception err)
{
itmHandleClient = 0;
txtTagValue.Text = "Error ox";
txtQualities.Text = "Error ox";
txtTimeStamps.Text = "Error ox";
MessageBox.Show("The reserved for system entry:" + err.Message, "message");
}
}
private void Form1_Load(object sender, EventArgs e)
{
//GetLocalServer();
KepServer = new OPCServer();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!opc_connected)
{
return;
}
if (KepGroup != null)
{
KepGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
}
if (KepServer != null)
{
KepServer.Disconnect();
KepServer = null;
}
opc_connected = false;
}
private void btnSetGroupPro_Click(object sender, EventArgs e)
{
SetGroupProperty();
}
private void btnConnLocalServer_Click(object sender, EventArgs e)
{
try
{
if (!ConnectRemoteServer(txtRemoteServerIP.Text.Trim(), "KEPware.KEPServerEx.V5"))
{
return;
}
btnSetGroupPro.Enabled = true;
opc_connected = true;
GetServerInfo();
RecurBrowse(KepServer.CreateBrowser());
if (!CreateGroup())
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
OPCItem bItem = KepItems.GetOPCItem(itmHandleServer);
int[] temp = new int[2] { 0, bItem.ServerHandle };
Array serverHandles = (Array)temp;
Object[] valueTemp = new Object[] { "", txtWriteTagValue.Text };
Array values = (Array)valueTemp;
Array Errors;
int cancelID;
KepGroup.AsyncWrite(1, ref serverHandles, ref values, out Errors, 2009, out cancelID);
GC.Collect();
}
}
}
Now I want to create some User Controls to display some tag values.What should I do?
This is a pretty big topic in itself, but I have implemented such a beast a few years back in C#, also using KepServerEx.
Without seeing your code it's a bit difficult for me to understand what you have done so far, but the general idea is that you want to handle the OPCGroup.DataChange event. From there you have to "dispatch" the changed value to the proper TextBox.
Of course, you have to setup your OPCServer, your OPCGroup(s) and so on.
I created a library for this, and it was some extensive work required, so I'm afraid it can't really be answered in one Q&A like here.
If you have a very specific question, please open another one and I'll try to answer more specifically.
Cheers

My application won't run under .net 2.0 , works on 3.5

I made this windows forms application in .net 3.5 (VS c# express) .
Now I want to convert it so it can run with just .net 2.0 installed. SO in my project properties: I selected "target framework " as 2.0 , fixed the errors that I got.
After this the app runs fine with .net 3.0 installed , but won't run on a fresh install of xp with with .net 2.0 installed. "Application has crashed. send error report"
What do I do ? I want this thing to run under 2.0.
here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int numberOfMatches = 0;
string[,] data;
bool update = true ;
string fileToParse = Path.GetTempPath() + "cricketfile.xml";
int matchToShow = 0;
bool showschedule = true ;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public Form1()
{
InitializeComponent();
if (Environment.OSVersion.Version.Major <= 5)
{
// MessageBox.Show("xp");
}
else
{
label1.Top = 1;
pictureBox1.Top = 1;
}
// label1.Left = 1;
int X = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;
this.Location = new System.Drawing.Point(X, -5);
if (rkApp.GetValue("cricketscore") == null)
{
startWithWindowsToolStripMenuItem.Checked = false ;
}
else
{
startWithWindowsToolStripMenuItem.Checked = true ;
}
this.Region = new Region(new Rectangle(10, 10, 197, 17));
ToolTip tooltip = new ToolTip();
// MessageBox.Show(" F" + tooltip.AutomaticDelay);
tooltip.AutomaticDelay = 0;
tooltip.InitialDelay = 0;
tooltip.SetToolTip(pictureBox1, " right click for settings, left click to move");
tooltip.SetToolTip(label1, " right click for settings, left click to move");
fetchData();
addContextEntries();
chooseIndia();
updateScore();
// MessageBox.Show(data.GetLength(0).ToString());
//foreach (string s in data)
//{
// Console.WriteLine(s);
//}
timer1.Interval = 20 * 1000;
timer1.Enabled = true;
}
public void addContextEntries()
{
// MessageBox.Show("num- " + numberOfMatches);
List<ToolStripMenuItem> Mylist1 = new List<ToolStripMenuItem>();
for (int i = 0; i < numberOfMatches; i++)
{
Mylist1.Add( new ToolStripMenuItem() );
this.contextMenuStrip1.Items.Add(Mylist1[i]);
Mylist1[i].Text = "See Match " + (i + 1) + "'s score";
switch(i)
{
case 0:
Mylist1[i].Click += new System.EventHandler(this.match1);
break;
case 1:
Mylist1[i].Click += new System.EventHandler(this.match2);
break;
case 2:
Mylist1[i].Click += new System.EventHandler(this.match3);
break;
case 3:
Mylist1[i].Click += new System.EventHandler(this.match4);
break;
case 4:
Mylist1[i].Click += new System.EventHandler(this.match5);
break;
}
}
}
public void match1(object sender, EventArgs e)
{
// MessageBox.Show("match 1");
matchToShow = 0;
label1.Text = data[0, 0] + " " + data[0, 1];
}
public void match2(object sender, EventArgs e)
{
// MessageBox.Show("match 2");
matchToShow = 1;
label1.Text = data[1, 0] + " " + data[1, 1];
}
public void match3(object sender, EventArgs e)
{
matchToShow = 2;
label1.Text = data[2, 0] + " " + data[2, 1];
}
public void match4(object sender, EventArgs e)
{
matchToShow = 3;
label1.Text = data[3, 0] + " " + data[3, 1];
}
public void match5(object sender, EventArgs e)
{
matchToShow = 4;
label1.Text = data[4, 0] + " " + data[4, 1];
}
public void chooseIndia()
{
try
{
for (int i = 0; i < data.GetLength(0); i++)
{
// MessageBox.Show("i - " + i);
if (data[i, 3].ToLower().Contains("india"))
{
matchToShow = i;
// MessageBox.Show("i - " + i);
break;
}
}
}
catch (NullReferenceException ne)
{
}
}
public void updateScore()
{
fetchData();
if (update == true)
{
try
{
label1.Text = data[matchToShow, 0] + " " + data[matchToShow, 1];
}
catch (Exception e)
{
}
}
}
public void fetchData()
{
int matchnumber = -1;
numberOfMatches = 0;
WebClient Client = new WebClient();
try
{
Client.DownloadFile("http://synd.cricbuzz.com/score-gadget/gadget-scores-feed.xml", fileToParse);
}
catch (WebException we)
{
// if (we.ToString().ToLower().Contains("connect to"))
// MessageBox.Show("sdf");
label1.Text = "No Internet";
update = false ;
this.Update();
// System.Threading.Thread.Sleep(1000);
}
try
{
XmlTextReader xmlreader0 = new XmlTextReader(fileToParse);
while (xmlreader0.Read())
{
if (xmlreader0.Name.ToString() == "match" && xmlreader0.NodeType == XmlNodeType.Element)
{
++numberOfMatches;
}
}
data = new string[numberOfMatches, 4];
// numberOfMatches = 0;
// MessageBox.Show("matchnumbers - " + numberOfMatches);
// MessageBox.Show("asd");
XmlTextReader xmlreader = new XmlTextReader(fileToParse);
while (xmlreader.Read())
{
// MessageBox.Show("READING");
if (xmlreader.Name.ToString() == "header" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 0] = xmlreader.Value;
// MessageBox.Show(xmlreader.Value);
}
if (xmlreader.Name == "description" && xmlreader.NodeType == XmlNodeType.Element)
{
// MessageBox.Show(xmlreader.Value);
xmlreader.Read();
// MessageBox.Show("matched - " + xmlreader.Value);
data[matchnumber, 1] = xmlreader.Value;
}
if (xmlreader.Name == "url-text" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
// MessageBox.Show(xmlreader.Value);
data[matchnumber, 2] = xmlreader.Value;
}
if (xmlreader.Name == "url-link" && xmlreader.NodeType == XmlNodeType.Element)
{
xmlreader.Read();
data[matchnumber, 3] = xmlreader.Value;
}
if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
{
matchnumber++;
showFullScorecardToolStripMenuItem.Text = "Show full scorecard";
showschedule = true;
update = true;
}
if (xmlreader.Name.ToString() == "nextlive" && xmlreader.NodeType == XmlNodeType.Element)
{
label1.Text = "No current match";
showFullScorecardToolStripMenuItem.Text = "Show Schedule";
showschedule = false;
update = false;
break;
}
}
xmlreader.Close();
xmlreader0.Close();
}
catch (FileNotFoundException fe)
{
// MessageBox.Show("no internet");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
updateScore();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void switchColrosToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( label1.ForeColor == System.Drawing.Color.Black)
label1.ForeColor = System.Drawing.Color.White ;
else
label1.ForeColor = System.Drawing.Color.Black;
}
private void startWithWindowsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startWithWindowsToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
if (startWithWindowsToolStripMenuItem.Checked == true)
{
rkApp.SetValue("cricketscore", Application.ExecutablePath.ToString());
}
else
{
rkApp.DeleteValue("cricketscore", false);
}
}
private void showFullScorecardToolStripMenuItem_Click(object sender, EventArgs e)
{
if ( showschedule == true )
System.Diagnostics.Process.Start(data[matchToShow, 3]);
else
System.Diagnostics.Process.Start("http://www.cricbuzz.com/component/cricket_schedule/");
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
//public void findNumberOfMatches()
//{
// if (xmlreader.Name.ToString() == "match" && xmlreader.NodeType == XmlNodeType.Element)
// {
// matchnumber++;
// }
//}
}
}
Thanks
The way it closes doesn't look like need to upgrade the framework but lets see those:
Try to test it under .NET 2.0 with latest .NET 2.0 service pack installed
Try to check the references in your project whether they're all clean to .NET 2.0 or not, sometimes this is not done correctly. Press F4 of every assembly that has 2.0 and 3.x versions to see properties and confirm (and remove/add if needed). If you see anything like LINQ or so, this needs to be removed.
Try to bring Visual C# 2005 Express or similar and see if the code compiles under it. Or create new .NET 2.0 project and copy your code to it.

Categories