I have a small application which reads 17 meter via mod-bus open-source industrial networks library.
In C# I am using to Read the Holding Registers from 17 meters simultaneously via Serial Port as seen in the code.
But in some instances to read the holding register the write command to the serial port is given and there is no reply from that command and the script continues to the next holding register to read. But the skipped register value retrieved is nothing, but still the array read from the previous command value.
I have tried to mark the array to null still when the port is not read the previous command for read holding is carry forwarded and in this case i.e.
Meter 1 is read and Meter 2 is not read the Value of Meter1 is shown in Meter 2 textbox and stream file.
How can I avoid the carry forwarding in this case in a timer loop.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IndustrialNetwork.Modbus.RTU;
using IndustrialNetwork.Modbus.ASCII;
using IndustrialNetwork.Modbus.TCP;
using IndustrialNetwork.Modbus.DataType;
using IndustrialNetwork.Modbus.Comm;
using System.IO.Ports;
using System.IO;
namespace ModbusTCP_Example
{
public partial class SecureMeterReaderMPPGCL : Form
{
private IModbusMaster modbusMaster = null;
private SerialPort serialPort = null;
private const int DELAYS = 500;// delay 100 ms
public SecureMeterReaderMPPGCL()
{
InitializeComponent();
aboutToolStripMenuItem.Click += new EventHandler(aboutToolStripMenuItem_Click);
}
private void SecureMeterReaderMPPGCL_Load(object sender, EventArgs e)
{
try
{
// Mode: MODBUS RTU
serialPort = new SerialPort();
serialPort.ReadBufferSize = 4096;
serialPort.WriteBufferSize = 4096;
serialPort.BaudRate = 9600;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
serialPort.Handshake = Handshake.None;
serialPort.RtsEnable = true;
serialPort.DtrEnable = true;
//serialPort.ReadTimeout = 0;
serialPort.PortName = "COM3";
//serialPort.WriteTimeout = 0;
//serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
ModbusSerialPortAdapter serialAdapter = new ModbusSerialPortAdapter(serialPort);
modbusMaster = new ModbusRTUMaster();
modbusMaster.sModbusSerialPortAdapter(serialAdapter);
//// Mode: MODBUS ASCII
//serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
//ModbusSerialPortAdapter serialAdapter = new ModbusSerialPortAdapter(serialPort);
//master = new ModbusASCIIMaster();
//master.sModbusSerialPortAdapter(serialAdapter);
//// Mode: MODBUS TCP/IP.
//master = new ModbusTCPMaster("127.0.0.1", 502);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
modbusMaster.Connection(); // Connect to Modbus Slave.
btnConnect.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
modbusMaster.Disconnection(); // Connect to Modbus Slave.
btnConnect.Enabled = true;
timerPoll.Stop();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnReadHoldingRegisters_Click(object sender, EventArgs e)
{
try
{
if (!btnConnect.Enabled) timerPoll.Start();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timerPoll_Tick(object sender, EventArgs e)
{
try
{
////Mode:Integer
//ushort startAddress = 1;
//byte[] temp = modbusMaster.ReadHoldingRegisters(1, string.Format("{0}", startAddress), 20);
//short[] data = IndustrialNetwork.Modbus.DataType.Int.ToArray(temp);
////show.
//Dictionary<ushort, short> result = new Dictionary<ushort, short>();
//foreach (short value in data)
//{
// result.Add(startAddress++, value);
//}
//dataGridView1.DataSource = result.ToArray();
////Mode:Float
//ushort startAddress = 1;
//byte[] temp = modbusMaster.ReadHoldingRegisters(1, string.Format("{0}", startAddress), 20);
//float[] data = IndustrialNetwork.Modbus.DataType.Real.ToArrayInverse(temp);
////show.
//Dictionary<ushort, float> result = new Dictionary<ushort, float>();
//foreach (float value in data)
//{
// result.Add(startAddress++, value);
//}
//dataGridView1.DataSource = result.ToArray();
//Mode:Float
ushort startAddress = 2122;
byte[] temp = null;
temp = modbusMaster.ReadHoldingRegisters(1, string.Format("{0}", startAddress), 2);
if (temp != null && temp.Length > 0)
{
float[] data = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp);
//
//Meter 1 File Write
using (StreamWriter sw = new StreamWriter("FREQ.txt", true))
{
float datar = float.Parse(string.Join(" ", data));
sw.WriteLine(datar);
textBox1.Text = datar.ToString();
Array.Clear(data, 0, data.Length);
Array.Clear(temp, 0, temp.Length);
//data = null;
}
}
////show.
//Dictionary<ushort, float> result = new Dictionary<ushort, float>();
//foreach (float value in data)
//{
// result.Add(startAddress++, value);
// startAddress += 1;
// //Write
// //using (StreamWriter sw1 = new StreamWriter("MPPGCL.txt", true))
// //{
// // sw1.WriteLine(value);
// //}
//}
//dataGridView1.DataSource = result.ToArray();
System.Threading.Thread.Sleep(DELAYS);
////1 Register
ushort startAddress1 = 2114;
byte[] temp1 = null;
temp1 = modbusMaster.ReadHoldingRegisters(1, string.Format("{0}", startAddress1), 2);
if (temp1 != null && temp1.Length > 0)
{
float[] data1 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp1);
//
//Meter 1 File Write
using (StreamWriter sw1 = new StreamWriter("MPPGCL_SGTPS_MTR1.txt", true))
{
float datar1 = float.Parse(string.Join(" ", data1)) / 1000;
sw1.WriteLine(datar1);
textBox3.Text = datar1.ToString();
Array.Clear(data1, 0, data1.Length);
Array.Clear(temp1, 0, temp1.Length);
//data = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////2 Register
ushort startAddress2 = 2114;
byte[] temp2 = null;
temp2 = modbusMaster.ReadHoldingRegisters(2, string.Format("{0}", startAddress2), 2);
if (temp2 != null && temp2.Length > 0)
{
float[] data2 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp2);
//
//Meter 2 File Write
using (StreamWriter sw2 = new StreamWriter("MPPGCL_SGTPS_MTR2.txt", true))
{
//var datar2 = int.Parse(string.Join(" ", data2))/1000;
//int myInt = int.Parse(datar2)/1000;
//int myInt2 = int.Parse(datar2);
float datar2 = float.Parse(string.Join(" ", data2)) / 1000;
sw2.WriteLine(datar2);
textBox4.Text = datar2.ToString();
Array.Clear(data2, 0, data2.Length);
Array.Clear(temp2, 0, temp2.Length);
//data2 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////3 Register
ushort startAddress3 = 2114;
byte[] temp3 = null;
temp3 = modbusMaster.ReadHoldingRegisters(3, string.Format("{0}", startAddress3), 2);
if (temp3 != null && temp3.Length > 0)
{
float[] data3 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp3);
//
//Meter 3 File Write
using (StreamWriter sw3 = new StreamWriter("MPPGCL_SGTPS_MTR3.txt", true))
{
float datar3 = float.Parse(string.Join(" ", data3)) / 1000;
sw3.WriteLine(datar3);
textBox6.Text = datar3.ToString();
Array.Clear(data3, 0, data3.Length);
Array.Clear(temp3, 0, temp3.Length);
//data3 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////4 Register
ushort startAddress4 = 2114;
byte[] temp4 = null;
temp4 = modbusMaster.ReadHoldingRegisters(4, string.Format("{0}", startAddress4), 2);
if (temp4 != null && temp4.Length > 0)
{
float[] data4 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp4);
//
//Meter 4 File Write
using (StreamWriter sw4 = new StreamWriter("MPPGCL_SGTPS_MTR4.txt", true))
{
float datar4 = float.Parse(string.Join(" ", data4)) / 1000;
sw4.WriteLine(datar4);
textBox5.Text = datar4.ToString();
Array.Clear(data4, 0, data4.Length);
Array.Clear(temp4, 0, temp4.Length);
//data4 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////5 Register
ushort startAddress5 = 2114;
byte[] temp5 = null;
temp5 = modbusMaster.ReadHoldingRegisters(5, string.Format("{0}", startAddress5), 2);
if (temp5 != null && temp5.Length > 0)
{
float[] data5 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp5);
//
//Meter 5 File Write
using (StreamWriter sw5 = new StreamWriter("MPPGCL_SGTPS_MTR5.txt", true))
{
float datar5 = float.Parse(string.Join(" ", data5)) / 1000;
sw5.WriteLine(datar5);
textBox8.Text = datar5.ToString();
Array.Clear(data5, 0, data5.Length);
Array.Clear(temp5, 0, temp5.Length);
//data5 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////6 Register
ushort startAddress6 = 2114;
byte[] temp6 = null;
temp6 = modbusMaster.ReadHoldingRegisters(6, string.Format("{0}", startAddress6), 2);
if (temp6 != null && temp6.Length > 0)
{
float[] data6 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp6);
//
//Meter 6 File Write
using (StreamWriter sw6 = new StreamWriter("MPPGCL_SGTPS_MTR6.txt", true))
{
float datar6 = float.Parse(string.Join(" ", data6)) / 1000;
sw6.WriteLine(datar6);
textBox7.Text = datar6.ToString();
Array.Clear(data6, 0, data6.Length);
Array.Clear(temp6, 0, temp6.Length);
//data6 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////7 Register
ushort startAddress7 = 2114;
byte[] temp7 = null;
temp7 = modbusMaster.ReadHoldingRegisters(7, string.Format("{0}", startAddress7), 2);
if (temp7 != null && temp7.Length > 0)
{
float[] data7 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp7);
//
//Meter 7 File Write
using (StreamWriter sw7 = new StreamWriter("MPPGCL_SGTPS_MTR7.txt", true))
{
float datar7 = float.Parse(string.Join(" ", data7)) / 1000;
sw7.WriteLine(datar7);
textBox14.Text = datar7.ToString();
Array.Clear(data7, 0, data7.Length);
Array.Clear(temp7, 0, temp7.Length);
//data7 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////8 Register
ushort startAddress8 = 2114;
byte[] temp8 = null;
temp8 = modbusMaster.ReadHoldingRegisters(8, string.Format("{0}", startAddress8), 2);
if (temp8 != null && temp8.Length > 0)
{
float[] data8 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp8);
//
//Meter 8 File Write
using (StreamWriter sw8 = new StreamWriter("MPPGCL_SGTPS_MTR8.txt", true))
{
float datar8 = float.Parse(string.Join(" ", data8)) / 1000;
sw8.WriteLine(datar8);
textBox13.Text = datar8.ToString();
Array.Clear(data8, 0, data8.Length);
Array.Clear(temp8, 0, temp8.Length);
//data8 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////9 Register
ushort startAddress9 = 2114;
byte[] temp9 = null;
temp9 = modbusMaster.ReadHoldingRegisters(9, string.Format("{0}", startAddress9), 2);
if (temp9 != null && temp9.Length > 0)
{
float[] data9 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp9);
//
//Meter 9 File Write
using (StreamWriter sw9 = new StreamWriter("MPPGCL_SGTPS_MTR9.txt", true))
{
float datar9 = float.Parse(string.Join(" ", data9)) / 1000;
sw9.WriteLine(datar9);
textBox12.Text = datar9.ToString();
Array.Clear(data9, 0, data9.Length);
Array.Clear(temp9, 0, temp9.Length);
//data9 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////10 Register
ushort startAddress10 = 2114;
byte[] temp10 = null;
temp10 = modbusMaster.ReadHoldingRegisters(10, string.Format("{0}", startAddress10), 2);
if (temp10 != null && temp10.Length > 0)
{
float[] data10 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp10);
//
//Meter 10 File Write
using (StreamWriter sw10 = new StreamWriter("MPPGCL_SGTPS_MTR10.txt", true))
{
float datar10 = float.Parse(string.Join(" ", data10)) / 1000;
sw10.WriteLine(datar10);
textBox11.Text = datar10.ToString();
Array.Clear(data10, 0, data10.Length);
Array.Clear(temp10, 0, temp10.Length);
//data10 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////11 Register
ushort startAddress11 = 2114;
byte[] temp11 = null;
temp11 = modbusMaster.ReadHoldingRegisters(11, string.Format("{0}", startAddress11), 2);
if (temp11 != null && temp11.Length > 0)
{
float[] data11 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp11);
//
//Meter 11 File Write
using (StreamWriter sw11 = new StreamWriter("MPPGCL_SGTPS_MTR11.txt", true))
{
float datar11 = float.Parse(string.Join(" ", data11)) / 1000;
sw11.WriteLine(datar11);
textBox10.Text = datar11.ToString();
Array.Clear(data11, 0, data11.Length);
Array.Clear(temp11, 0, temp11.Length);
//data11 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////12 Register
ushort startAddress12 = 2114;
byte[] temp12 = null;
temp12 = modbusMaster.ReadHoldingRegisters(12, string.Format("{0}", startAddress12), 2);
if (temp12 != null && temp12.Length > 0)
{
float[] data12 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp12);
//
//Meter 12 File Write
using (StreamWriter sw12 = new StreamWriter("MPPGCL_SGTPS_MTR12.txt", true))
{
float datar12 = float.Parse(string.Join(" ", data12)) / 1000;
sw12.WriteLine(datar12);
textBox9.Text = datar12.ToString();
Array.Clear(data12, 0, data12.Length);
Array.Clear(temp12, 0, temp12.Length);
//data12 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////13 Register
ushort startAddress13 = 2114;
byte[] temp13 = null;
temp13 = modbusMaster.ReadHoldingRegisters(13, string.Format("{0}", startAddress13), 2);
if (temp13 != null && temp13.Length > 0)
{
float[] data13 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp13);
//
//Meter 13 File Write
using (StreamWriter sw13 = new StreamWriter("MPPGCL_SGTPS_MTR13.txt", true))
{
float datar13 = float.Parse(string.Join(" ", data13)) / 1000;
sw13.WriteLine(datar13);
textBox20.Text = datar13.ToString();
Array.Clear(data13, 0, data13.Length);
Array.Clear(temp13, 0, temp13.Length);
//data13 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////14 Register
ushort startAddress14 = 2114;
byte[] temp14 = null;
temp14 = modbusMaster.ReadHoldingRegisters(14, string.Format("{0}", startAddress14), 2);
if (temp14 != null && temp14.Length > 0)
{
float[] data14 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp14);
//
//Meter 14 File Write
using (StreamWriter sw14 = new StreamWriter("MPPGCL_SGTPS_MTR14.txt", true))
{
float datar14 = float.Parse(string.Join(" ", data14)) / 1000;
sw14.WriteLine(datar14);
textBox19.Text = datar14.ToString();
Array.Clear(data14, 0, data14.Length);
Array.Clear(temp14, 0, temp14.Length);
//data14 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////15 Register
ushort startAddress15 = 2114;
byte[] temp15 = null;
temp15 = modbusMaster.ReadHoldingRegisters(15, string.Format("{0}", startAddress15), 2);
if (temp15 != null && temp15.Length > 0)
{
float[] data15 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp15);
//
//Meter 15 File Write
using (StreamWriter sw15 = new StreamWriter("MPPGCL_SGTPS_MTR15.txt", true))
{
float datar15 = float.Parse(string.Join(" ", data15)) / 1000;
sw15.WriteLine(datar15);
textBox18.Text = datar15.ToString();
Array.Clear(data15, 0, data15.Length);
Array.Clear(temp15, 0, temp15.Length);
//data15 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////16 Register
ushort startAddress16 = 2114;
byte[] temp16 = null;
temp16 = modbusMaster.ReadHoldingRegisters(16, string.Format("{0}", startAddress16), 2);
if (temp16 != null && temp16.Length > 0)
{
float[] data16 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp16);
//
//Meter 16 File Write
using (StreamWriter sw16 = new StreamWriter("MPPGCL_SGTPS_MTR16.txt", true))
{
float datar16 = float.Parse(string.Join(" ", data16)) / 1000;
sw16.WriteLine(datar16);
textBox17.Text = datar16.ToString();
Array.Clear(data16, 0, data16.Length);
Array.Clear(temp16, 0, temp16.Length);
//data16 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////17 Register
ushort startAddress17 = 2114;
byte[] temp17 = null;
temp17 = modbusMaster.ReadHoldingRegisters(17, string.Format("{0}", startAddress17), 2);
if (temp17 != null && temp17.Length > 0)
{
float[] data17 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp17);
//
//Meter 17 File Write
using (StreamWriter sw17 = new StreamWriter("MPPGCL_SGTPS_MTR17.txt", true))
{
float datar17 = float.Parse(string.Join(" ", data17)) / 1000;
sw17.WriteLine(datar17);
textBox16.Text = datar17.ToString();
Array.Clear(data17, 0, data17.Length);
Array.Clear(temp17, 0, temp17.Length);
//data17 = null;
}
}
//dataGridView1.DataSource = result.ToArray();
}
catch (Exception ex)
{
//MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void mainScreenToolStripMenuItem_Click(object sender, EventArgs e)
{
panelMeter1.Visible = true;
panelFlash.Visible = false;
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("This Tool has been created by Charles Felix for Reading Meter at MPPGCL");
}
private void timerDate_Tick(object sender, EventArgs e)
{
textBox2.Text = DateTime.Now.ToString();
}
}
}
Here is the part in which my meter 5 data is carry forwarded to meter 6 data in case the meter 6 holding register is not read, I want no value to be written in the stream writer file and even in the textbox for 6th meter i want the previous read value for meter 6.
////5 Register
ushort startAddress5 = 2114;
byte[] temp5 = null;
temp5 = modbusMaster.ReadHoldingRegisters(5, string.Format("{0}", startAddress5), 2);
if (temp5 != null && temp5.Length > 0)
{
float[] data5 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp5);
//
//Meter 5 File Write
using (StreamWriter sw5 = new StreamWriter("MPPGCL_SGTPS_MTR5.txt", true))
{
float datar5 = float.Parse(string.Join(" ", data5)) / 1000;
sw5.WriteLine(datar5);
textBox8.Text = datar5.ToString();
Array.Clear(data5, 0, data5.Length);
Array.Clear(temp5, 0, temp5.Length);
//data5 = null;
}
}
System.Threading.Thread.Sleep(DELAYS);
////6 Register
ushort startAddress6 = 2114;
byte[] temp6 = null;
temp6 = modbusMaster.ReadHoldingRegisters(6, string.Format("{0}", startAddress6), 2);
if (temp6 != null && temp6.Length > 0)
{
float[] data6 = IndustrialNetwork.Modbus.DataType.Real.ToArray(temp6);
//
//Meter 6 File Write
using (StreamWriter sw6 = new StreamWriter("MPPGCL_SGTPS_MTR6.txt", true))
{
float datar6 = float.Parse(string.Join(" ", data6)) / 1000;
sw6.WriteLine(datar6);
textBox7.Text = datar6.ToString();
Array.Clear(data6, 0, data6.Length);
Array.Clear(temp6, 0, temp6.Length);
//data6 = null;
}
}
I am using threads to upload images on a FTP. Now I have a problem in limiting the number of threads. when I am creating same number of threads equal to images then it's fine i.e. it is working fine. But now I want to create only suppose maximum of 5 number of threads to upload 100 or more images. I have a datatable in which these 100 images are with a unique field ID which stores suppose 0,1,2,3....and so on for every images. Now I want to start only five threads once so that it may start uploading 5 images parallely. On a Timer, I am checking the status of threads and if I found a thread which is not live now, I want to assign it the 6th Image for uploading and in the same way, if I found other thread which finished its uploading/work, I want to give it 7th image to upload and so on. i.e. this process will run until 100 images are uploaded.
Can you please suggest me a structure by using which I may achieve this? Currently I am creating 100 threads for 100 images and it is working perfect. But I am afraid of creating that much number of threads. Will that affect performance?
My Current Code is:
// A page level variable
Thread [] tr=null;
//On Load of the Control
tr = new Thread[dt.Rows.Count];
//tr = new Thread[MaxID];
for (int i = 0; i < dt.Rows.Count; i++)
//for (int i = 0; i < MaxID; i++)
{
tr[i] = new Thread(new ThreadStart(ProcessItems));
tr[i].Name = Convert.ToString(dt.Rows[i]["Id"]);
tr[i].IsBackground = true;
}
//Start each thread
foreach (Thread x in tr)
{
x.Start();
}
//The method which is used to upload images
public object tLock = new object();
private void ProcessItems()
{
//if (dict.Count == 0)
// pthread.Suspend();
//ArrayList toRemove = new ArrayList();
lock (tLock)
{
try
{
//int NoofAttempts = 0;
//foreach (DictionaryEntry e in dict)
//{
//Thread.Sleep(500);
dr = dt.Select("Is_Uploaded=0 And Id=" + Thread.CurrentThread.Name).FirstOrDefault();
uxImageAndProgress pbCtl = panelControl1.Controls[dr["Image_ID"].ToString()] as uxImageAndProgress;
//NoofAttempts = 0;
string Path = "";
if (ftpPath == "")
{
Path = Global.FTPRemotePath + "/ProductImages/" + dr["Image_ID"] + dr["Extension"].ToString();
}
else
{
Path = ftpPath + dr["Image_ID"] + dr["Extension"].ToString();
}
//object[] loader = e.Value as object[];
int length = (int)(dr["ActualData"] as byte[]).Length;
Stream stream = new MemoryStream(dr["ActualData"] as byte[]);
byte[] rBuffer = ReadToEnd(stream);
int d = length - (int)stream.Length;
d = Math.Min(d, rnd.Next(10) + 1);
if (ftpRequest == null)
{
try
{
#region New Code
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path));
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(Global.FTPLogIn, Global.FTPPassword);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = true;
ftpRequest.Timeout = 20000;
ftpRequest.ContentLength = length;
byte[] buffer = new byte[length > 4097 ? 4097 : length];
int bytes = 0;
int total_bytes = (int)length;
System.IO.Stream rs = ftpRequest.GetRequestStream();
while (total_bytes > 0)
{
bytes = stream.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
dr["Is_Uploaded"] = 1;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
rs.Close();
#endregion
}
catch (Exception eeex)
{
ftpRequest = null;
if (ErrorText == "")
ErrorText = eeex.Message.ToString();
else
ErrorText = ErrorText + "," + eeex.Message.ToString();
if (Image_IDsToDelete == "")
Image_IDsToDelete = dr["Image_ID"].ToString();
else
Image_IDsToDelete = Image_IDsToDelete + "," + dr["Image_ID"].ToString();
if (NotUploadedFiles == "")
NotUploadedFiles = Convert.ToString(dr["FileName"]);//dr["Image_ID"] + dr["Extension"].ToString();
else
NotUploadedFiles = NotUploadedFiles + ", " + Convert.ToString(dr["FileName"]);
dr["Is_Uploaded"] = true;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
pbCtl.Is_WithError = true;
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), Global.Header, MessageBoxButtons.OK);
//pthread.Suspend();
}
}
}
//The Timer Event on which I am checking the Status of threads and taking appropriate action
private void timer1_Tick(object sender, EventArgs e)
{
bool Is_AllFinished=true;
//Start each thread
foreach (Thread x in tr)
{
if (x.IsAlive == true)
{
Is_AllFinished = false;
break;
}
else
{
//DataRow[] drs = dt.Select("Is_Uploaded=0");
//if (drs.Count() > 0)
//{
//x. = Convert.ToString(MaxID + 1);
//x.Start();
//MaxID = MaxID + 1;
//}
}
}
if (Is_AllFinished == true)
{
timer1.Enabled = false;
if (Image_IDsToDelete != "")
{
RetailHelper.ExecuteNonQuery("Delete from images where Image_ID in (" + Image_IDsToDelete + ")");
}
if (ErrorText != "")
{
NotUploadedFiles = NotUploadedFiles + ".";
XtraMessageBox.Show("Unable to connect to server. The following files were not uploaded:" + System.Environment.NewLine + NotUploadedFiles + ".", Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Is_Done = true;
}
}
Now, I want to convert this code to use a fixed number of threads. Please help me.
Thanking you!
Use a Semaphore it is good enough. You can polish the code yourself.
const int maxThreads = 5;
Semaphore sm = new Semaphore(maxThreads, maxThreads); // maximum concurrent threads
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
sm.WaitOne();
Thread tr = new Thread(new ThreadStart(ProcessItems));
tr.Name = Convert.ToString(dt.Rows[i]["Id"]);
tr.IsBackground = true;
tr.Start();
}
finally
{
sm.Release();
}
}
// You don't need the timer anymore
// Wait for the semaphore to be completely released
for (int i=0; i<maxThreads ; i++)
sm.WaitOne();
sm.Release(maxThreads);
if (Image_IDsToDelete != "")
{
RetailHelper.ExecuteNonQuery("Delete from images where Image_ID in (" + Image_IDsToDelete + ")");
}
if (ErrorText != "")
{
NotUploadedFiles = NotUploadedFiles + ".";
XtraMessageBox.Show("Unable to connect to server. The following files were not uploaded:" + System.Environment.NewLine + NotUploadedFiles + ".", Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//The method which is used to upload images
private void ProcessItems()
{
//if (dict.Count == 0)
// pthread.Suspend();
//ArrayList toRemove = new ArrayList();
try
{
sm.WaitOne();
try
{
//int NoofAttempts = 0;
//foreach (DictionaryEntry e in dict)
//{
//Thread.Sleep(500);
dr = dt.Select("Is_Uploaded=0 And Id=" + Thread.CurrentThread.Name).FirstOrDefault();
uxImageAndProgress pbCtl = panelControl1.Controls[dr["Image_ID"].ToString()] as uxImageAndProgress;
//NoofAttempts = 0;
string Path = "";
if (ftpPath == "")
{
Path = Global.FTPRemotePath + "/ProductImages/" + dr["Image_ID"] + dr["Extension"].ToString();
}
else
{
Path = ftpPath + dr["Image_ID"] + dr["Extension"].ToString();
}
//object[] loader = e.Value as object[];
int length = (int)(dr["ActualData"] as byte[]).Length;
Stream stream = new MemoryStream(dr["ActualData"] as byte[]);
byte[] rBuffer = ReadToEnd(stream);
int d = length - (int)stream.Length;
d = Math.Min(d, rnd.Next(10) + 1);
if (ftpRequest == null)
{
try
{
#region New Code
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(Path));
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(Global.FTPLogIn, Global.FTPPassword);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = true;
ftpRequest.Timeout = 20000;
ftpRequest.ContentLength = length;
byte[] buffer = new byte[length > 4097 ? 4097 : length];
int bytes = 0;
int total_bytes = (int)length;
System.IO.Stream rs = ftpRequest.GetRequestStream();
while (total_bytes > 0)
{
bytes = stream.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
dr["Is_Uploaded"] = 1;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
rs.Close();
#endregion
}
catch (Exception eeex)
{
ftpRequest = null;
if (ErrorText == "")
ErrorText = eeex.Message.ToString();
else
ErrorText = ErrorText + "," + eeex.Message.ToString();
if (Image_IDsToDelete == "")
Image_IDsToDelete = dr["Image_ID"].ToString();
else
Image_IDsToDelete = Image_IDsToDelete + "," + dr["Image_ID"].ToString();
if (NotUploadedFiles == "")
NotUploadedFiles = Convert.ToString(dr["FileName"]);//dr["Image_ID"] + dr["Extension"].ToString();
else
NotUploadedFiles = NotUploadedFiles + ", " + Convert.ToString(dr["FileName"]);
dr["Is_Uploaded"] = true;
dt.AcceptChanges();
ftpRequest = null;
pbCtl.Is_Uploaded = true;
pbCtl.Is_WithError = true;
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), Global.Header, MessageBoxButtons.OK);
//pthread.Suspend();
}
}
finally
{
sm.Release();
}
}
It sounds like a producer / consumer queue is the structure you are looking for. Take a look a this answer and the others in the thread for examples of how to employ it.
I have finally, successfully, figured out how to fill a PDF with an XFA Form with my custom data using iTextSharp.
The problem is that I've lost the code that I had that let me make the XFA read-only. I have made the horrible mistake of changing my code before committing a working version to my source control. And now, after searching Google for like an hour I still can't find it :( If someone could remind me of the code that would be much appreciated.
PdfReader.unethicalreading = true;
PdfReader reader = new PdfReader(pdfFileName);
PdfStamper stamper = new PdfStamper(reader, ms);
XfaForm xfa = new XfaForm(reader);
XmlDocument doc = new XmlDocument();
doc.LoadXml(CreateXmaData(XDocument.Parse(xfa.DomDocument.InnerXml)));
xfa.DomDocument = doc;
xfa.Changed = true;
XfaForm.SetXfa(xfa, stamper.Reader, stamper.Writer);
PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
stamper.Writer.SetOpenAction(action);
// Somewhere here I had the code that made my XFA form read only...
stamper.Writer.CloseStream = false;
stamper.Close();
reader.Close();
byte[] buffer = new byte[ms.Position];
ms.Position = 0;
ms.Read(buffer, 0, buffer.Length);
return buffer;
Not sure if I was dreaming that I had the read-only working or what, and I doubt that this is the best way, but here is how I was finally able to do it:
...
doc.LoadXml(CreateXmaData(XDocument.Parse(xfa.DomDocument.InnerXml)));
PdfAction readOnlyAction = PdfAction
.JavaScript(MakeReadOnly(xfa.DomDocument.InnerXml), stamper.Writer);
stamper.Writer.AddJavaScript(readOnlyAction);
xfa.DomDocument = doc;
...
private string MakeReadOnly(string xml)
{
string formName = string.Empty;
int subFormStart = xml.IndexOf("<subform", 0);
if (subFormStart > -1)
{
int nameTagStart = xml.IndexOf("name", subFormStart);
int nameStart = xml.IndexOf("\"", nameTagStart);
int nameEnd = xml.IndexOf("\"", nameStart + 1);
formName = xml.Substring(nameStart + 1, (nameEnd - nameStart) - 1);
}
string readOnlyFunction = "ProcessAllFields(xfa.form." + formName + ");";
readOnlyFunction += "function ProcessAllFields(oNode) {";
readOnlyFunction += " if (oNode.className == \"exclGroup\" || oNode.className == \"subform\" || oNode.className == \"subformSet\" || oNode.className == \"area\") { ";
readOnlyFunction += " for (var i = 0; i < oNode.nodes.length; i++) {";
readOnlyFunction += " var oChildNode = oNode.nodes.item(i); ProcessAllFields(oChildNode);";
readOnlyFunction += " }";
readOnlyFunction += " } else if (oNode.className == \"field\") {";
readOnlyFunction += " oNode.access = \"readOnly\"";
readOnlyFunction += " }";
readOnlyFunction += "}";
return readOnlyFunction;
}
This worked for me
String script = "for (var nPageCount = 0; nPageCount < xfa.host.numPages; nPageCount++) { var oFields = xfa.layout.pageContent(nPageCount, \"subform\"); var nNodesLength = oFields.length;";
script += "for (var nNodeCount = 0; nNodeCount < nNodesLength; nNodeCount++) { oFields.item(nNodeCount).access = \"readOnly\"; } } ";
I am trying to split the incoming data from a Serial Port, and update text boxes with subsequent data. I first see if a split on '$' is possible, and if the next word after splitting is "GPGGA". If yes, I would like to extract data from this sentence where ',' serves as the separator.
Now, as you see, I update the entire data read by the Serial Port first, and this works fine. The full sentence containing the "GPGGA" line is displayed. But after I split it, the part of the sentence that contains the "GPGGA" looks something like this"GPGGA,1\0\0\0\0\0..." when really the sentence that was just updated to the text box before was "GPGGA,160333,,,......". I am absolutely certain that there is a value after GPGGA in the sentence but when i try to look at it in the debug mode, the string 'ser_data', and hence its subsequent substrings all show the same junk. So, the final text box that I want to update inevitably ends up displaying just 1.
Could anyone tell me why this is happening, and how I can correct it. I need it urgently for my thesis work.
Thanks,
Brett
P.S: I've attached the code below.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] bData = null;
bData = new byte[40];
serialPort.Read(bData, 0, 40);
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData);
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = null;
str = new string[40];
string[] str_ack = null;
str = ser_data.Split('$');
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = null;
temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
string[] temp2 = null;
temp2 = temp1.Split(',');
StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
string Text = "." + '\n';
objWriter.WriteLine(Text);
objWriter.Close();
temp2 = null;
flag_status = 0;
}
temp1 = null;
}
}
str = null;
SerialPort.Read does not necessarily read the number of characters you ask for.
You need to save the return value, which is the number of characters read.
// nBytesRead will be between 0 and 40, depending on how many bytes were waiting.
int nBytesRead = serialPort.Read(bData, 0, 40);
// Only decode the number of bytes actually retrieved.
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData, 0, nBytesRead);
Fixed and majorly cleaned up. This assumes two things: that your encoding is really UTF-8, and that your lines end with newline characters.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
serialPort.Encoding = ASCIIEncoding.UTF8;
string ser_data = serialPort.ReadLine();
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = ser_data.Split(new char[] { '$' }, 2);
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
StreamWriter objWriter = new StreamWriter(#"D:\Server.txt", true);
try
{
string[] temp2 = temp1.Split(',');
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
objWriter.WriteLine(".\n");
}
finally
{
objWriter.Close();
}
flag_status = 0;
}
}
}
}