Method not found: 'IntPtr System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(!!0) - c#

I am using visual studio 2010 professional on windows 7 (32 bit) to connect to RFID reader LRU3000 and i encounterd this exception
Method not found: 'IntPtr
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(!!0)
kindly download the sample from the following link.
I searched the web much but i failed to know what is wrong.
Thanks In advance
NotificationSample.zip
and this is the code of the sample
this is the code of the sample :
the exception occurs at the line of code :
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
public partial class NotificationSample : Form,FedmTaskListener
{
FedmIscReader reader;
FedmTaskOption taskOpt;
long count=1;
//declaration from delegatetyp
public delegate void DelegateDisplayRecSets(int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip);
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NotificationSample());
}
//Constructor
public NotificationSample()
{
InitializeComponent();
try
{
reader = new FedmIscReader();
reader.SetTableSize(FedmIscReaderConst.BRM_TABLE, 255); // max 255 tag with each notification
taskOpt = new FedmTaskOption();
}
catch(FedmException ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
//Actualy Time propertie
private string Time
{
get
{
DateTime d;
d = DateTime.Now;
string t;
// Get the Date
if (d.Month.ToString().Trim().Length == 1)
{
t = "0" + d.Month.ToString().Trim() + "/";
}
else
{
t = d.Month.ToString().Trim() + "/";
}
if (d.Day.ToString().Trim().Length == 1)
{
t += "0" + d.Day.ToString().Trim() + "/";
}
else
{
t += d.Day.ToString().Trim() + "/";
}
t += d.Year.ToString().Trim() + " ";
// Get the time
if (d.Hour.ToString().Trim().Length == 1)
{
t += "0" + d.Hour.ToString().Trim() + ":";
}
else
{
t += d.Hour.ToString().Trim() + ":";
}
if (d.Minute.ToString().Trim().Length == 1)
{
t += "0" + d.Minute.ToString().Trim() + ":";
}
else
{
t += d.Minute.ToString().Trim() + ":";
}
if (d.Second.ToString().Trim().Length == 1)
{
t += "0" + d.Second.ToString().Trim() + ".";
}
else
{
t += d.Second.ToString().Trim() + ".";
}
if (d.Millisecond.ToString().Trim().Length == 1)
{
t += "00" + d.Millisecond.ToString().Trim() + ".";
}
else if (d.Millisecond.ToString().Trim().Length == 2)
{
t += "0" + d.Millisecond.ToString().Trim() + ".";
}
else
{
t += d.Millisecond.ToString().Trim() + ".";
}
return t;
}
}
/*****************************Methods from interface FedmTaskListener*******************/
public void OnNewNotification(int iError,string IP,uint PortNr)
{
int i;
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
//declaration from delegateobject
DelegateDisplayRecSets DisplayRecSetMethod = new DelegateDisplayRecSets(DisplayRecSets);
object[] obj = new object[11];
IAsyncResult result;
if(brmItems == null)
{
return;
}
string[] serialnumber = new string[brmItems.Length];
string[] dataBlock = new string[brmItems.Length];
string[] date = new string[brmItems.Length];
string[] time = new string[brmItems.Length];
byte[] type = new byte[brmItems.Length];
byte[] antennaNr = new byte[brmItems.Length];
byte[] input = new byte[brmItems.Length];
byte[] state = new byte[brmItems.Length];
byte[] dbsize = new byte[brmItems.Length];
Dictionary<byte, FedmIscRssiItem>[] dicRSSI = new Dictionary<byte, FedmIscRssiItem>[brmItems.Length];
long dbn;
byte dbadr;
string db;
for (i = 0; i < brmItems.Length; i++)
{ // serial number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_SNR, out serialnumber[i]);
}
// data blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_DBN, out dbn);
brmItems[i].GetData(FedmIscReaderConst.DATA_DB_ADR, out dbadr);
int j;
for (j = dbadr; j < dbn; j++)
{
brmItems[i].GetData(FedmIscReaderConst.DATA_RxDB, j, out db);
dataBlock[i] = dataBlock[i] + db + "\r\n"+"\t\t";
}
}
// Transponder Type
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TRTYPE))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_TRTYPE, out type[i]);
}
// Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
date[i] = brmItems[i].GetReaderTime().GetDate();
}
// Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
time[i] = brmItems[i].GetReaderTime().GetTime();
}
// Antenna number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_ANT_NR, out antennaNr[i]);
}
// RSSI value
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_RSSI))
{
dicRSSI[i] = brmItems[i].GetRSSI();
}
else
{
dicRSSI[i] = new Dictionary<byte, FedmIscRssiItem>();
}
// Input
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_INPUT, out input[i]);
brmItems[i].GetData(FedmIscReaderConst.DATA_STATE, out state[i]);
}
}
obj[0] = brmItems.Length;
obj[1] = type;
obj[2] = serialnumber;
obj[3] = dataBlock;
obj[4] = date;
obj[5] = time;
obj[6] = antennaNr;
obj[7] = dicRSSI;
obj[8] = input;
obj[9] = state;
obj[10] = IP;
result = (IAsyncResult)Invoke(DisplayRecSetMethod, obj);
}
public void OnNewApduResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewQueueResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewSAMResponse(int iError, byte[] responseData)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewReaderDiagnostic(int iError,string IP,uint PortNr)
{
}
public int OnNewMaxAccessEvent(int iError, string maxEvent, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public int OnNewMaxKeepAliveEvent(int iError, uint uiErrorFlags, uint TableSize, uint uiTableLength, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewTag(int iError)
{
}
public void onNewPeopleCounterEvent(uint counter1, uint counter2, uint counter3, uint counter4, string ip, uint portNr, uint busAddress)
{
throw new Exception("The method or operation is not implemented.");
}
/************************************ENDE***********************************************/
/******************************************************Asynchrone method*****************************************************************************************************/
public void DisplayRecSets( int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip)
{
Dictionary<byte, FedmIscRssiItem> RSSIval;
FedmIscRssiItem RSSIitem;
int i;
bool bcheck;
byte antNo;
string dr;
string tr = "";
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
tr += "-----------------------------------------------------------------" + "\r\n";
tr += "DATE/TIME: " + Time.ToString() + "\r\n";
tr += "-----------------------------------------------------------------" + "\r\n";
count = 1;
for (i = 0; i < recSets; i++)
{
tr += (count).ToString().Trim() + "." + " TRANSPONDER" + "\r\n";
count = count + 1;
if (type[i] >= 0)
{
//just the two last bit
dr = "0x" + FeHexConvert.IntegerToHexString(type[i]).Substring(FeHexConvert.IntegerToHexString(type[i]).Length - 2, 2);
tr += "TR-TYPE:" + "\t" + dr.ToString() + "\r\n";
}
// Output SeriaNo.
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
if (serialNumber[i] != null)
{
tr += "SNR:" + "\t\t" + serialNumber[i].ToString() + "\r\n";
}
}
// Output Data Blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
if (dataBlock[i] != null)
{
tr += "DB:" + "\t\t" + dataBlock[i].ToString() + "\r\n";
}
}
// Output Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER) || brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
if (date[i] != null)
{
tr += "DATE:" + "\t\t" + date[i].ToString() + "\r\n";
}
}
// Output Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
if (time[i] != null)
{
tr += "TIME:" + "\t\t" + time[i].ToString() + "\r\n";
}
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output ANT_NR
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
tr += "ANT. NR:"+"\t\t" + (antennaNr[i].ToString()).Trim() + "\r\n";
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output RSSI
if (dicRSSI.Length > 0)
{
if (dicRSSI[i] != null)
{
RSSIval = dicRSSI[i];
for(antNo = 1; antNo<FedmBrmTableItem.TABLE_MAX_ANTENNA; antNo++)
{
bcheck = RSSIval.TryGetValue(antNo, out RSSIitem);
if (!bcheck)
continue;
tr += "RSSI of AntNr. " + "\t" + antNo.ToString() + " is " + "-" + RSSIitem.RSSI.ToString() + "dBm" + "\r\n";
}
}
}
// Output INPUT
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
tr += "INPUT:" + "\t\t" + (input[i].ToString()).Trim() + "\r\n";
tr += "STATE:" + "\t\t" + (state[i].ToString()).Trim() + "\r\n";
}
// Output IP where notification data comes from
tr += "FROM:" + "\t\t" + ip + "\r\n";
tr += "" + "\r\n";
tr += "" + "\r\n";
}
this.textBoxData.AppendText(tr);
tr = "";
}
/**********************************************************ENDE***************************************************************************************************************/
/**************************************************Buttons**********************************************/
private void buttonListen_Click(object sender, EventArgs e)
{
if(this.buttonListen.Text == "Listen")
{
this.buttonListen.Text = "Cancel";
taskOpt.IPPort = Convert.ToInt16(this.textBoxPortNr.Text);
if(this.checkBoxAkn.Checked)
{
taskOpt.NotifyWithAck = 1;
}
else
{
taskOpt.NotifyWithAck = 0;
}
//Start from intern Thread
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
this.buttonListen.Text = "Listen";
//End from intern thread
int val;
reader.ResetTable(FedmIscReaderConst.BRM_TABLE);
val=reader.CancelAsyncTask();
//case Deadlocks ->-4084
if (val < 0)
{
reader.CancelAsyncTask();
}
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
this.textBoxData.Clear();
count = 1;
}
/***********************************************************Ende******************************************/
private void NotificationSample_FormClosing(object sender, FormClosingEventArgs e)
{
reader.CancelAsyncTask();
Application.Exit();
}
}

Related

How to fix 'The name 'k' does not exist in the current context' error?

I only get the System.IndexOutOfRangeException error when running the solution normally but is all okay when stepping into through the whole loop.
I have tried the to catch the exception but no joy.
private void button1_Click(object sender, EventArgs e)
{
for (int j = 0; j < jobs.Length; j++)
{
if (jobs[j].JobID == false)
{
for (int k = 0; k < threads.Length; k++)
{
if (threads[k] != null)
{
if (!(threads[k].ThreadState == ThreadState.Stopped) | !(threads[k].ThreadState == ThreadState.Unstarted))
{
continue;
}
}
try
{
threads[k] = new Thread(() => CountUp("ftp://ftp.net" + jobs[j].FTPFolder, HomePath + jobs[j].localFolder, j));
threads[k].Name = "Thread " + j + "¦ ID: " + threads[k].ManagedThreadId.ToString();
jobs[j].JobID = true;
//threads[k].Start();
break;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
}
StartThreads();
}
I expect all threads in the threads[] array to be initialised if jobs[].JobID is false.
Below is the CountUp() method:
private void CountUp(string ftppath,string localFile, int jobsID)
{
//string conf="";
NumberThreads++;
//string ftpPath = "ftp://ftp.Rxsystems.net" + conf.Split('¦')[1];
//string downloadPath = HomePath + conf.Split('¦')[0] + "\\";
string ftpPath = ftppath;
string downloadPath = localFile;
List<string> MSI = new List<string>(KD.FTP.Class.ListFiles(ftpPath,
FTPuser, FTPpass));
if (MSI.Count > 0)
{
KD.File.Class.Logger(Thread.CurrentThread.Name + ", " + MSI.Count + " Files in " + ftpPath, CurDir + "\\log.txt");
this.textBox1.AppendText(Thread.CurrentThread.Name + ", " + MSI.Count + " Files in " + ftpPath);
//this.textBox1.AppendText("\n\r");
int count = 0;
foreach (string ftpFile in MSI)
{
KD.FTP.Class.Download(ftpPath + ftpFile,downloadPath + "\\" + ftpFile, FTPuser,FTPpass);
count++;
KD.File.Class.Logger(Thread.CurrentThread.Name + ", " + "Downloaded " + count + "/" + MSI.Count + " Files - " + ftpFile, CurDir + "\\log.txt");
this.textBox1.AppendText(Thread.CurrentThread.Name + ", " + "Downloaded " + count + "/" + MSI.Count + " Files - " + ftpFile);
//this.textBox1.AppendText("\n\r");
}
}
NumberThreads--;
jobs[jobsID].JobID = false;
}
The below initialises threads[] and jobs[]:
private void Form1_Load(object sender, EventArgs e)
{
Form1.CheckForIllegalCrossThreadCalls = false;
if (File.Exists(CurDir + "\\FTPpaths.config"))
{
foreach (string line in File.ReadAllLines(CurDir + "\\FTPpaths.config"))
{
if (!string.IsNullOrEmpty(line))
{
ConfigPaths.Add(line.Split('¦')[0] + "¦" + line.Split('¦')[1]);
}
}
if (ConfigPaths.Count > 0)
{
jobs = new Jobs[ConfigPaths.Count];
for (int j = 0; j < ConfigPaths.Count; j++)
{
jobs[j] = new Jobs();
jobs[j].FTPFolder = ConfigPaths[j].Split('¦')[1];
jobs[j].localFolder = ConfigPaths[j].Split('¦')[0];
jobs[j].JobID = false;
}
threads = new Thread[jobs.Length];
}
timer1.Enabled = true;
}
else
{
Application.Exit();
}
}
From what I can see the problem is with j variable which is captured from closure into delegate passed to new Thread. It's well know problem when actual delegate execution references the variable in state after the loop execution so it's supposed to effectively contain jobs.Length value which is out of range. To fix you need to introduce a local variable inside the loop to copy j value in, and then use this variable instead of j as index of jobs inside the delegate passed to the Thread constructor:
try
{
var jobIdx = j;
threads[k] = new Thread(() => CountUp("ftp://ftp.net" + jobs[jobIdx].FTPFolder, HomePath + jobs[jobIdx].localFolder, jobIdx));
...
// other stuff
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}

I'm not able to start a SqliteTransaction inside a thread

Well, I already created a functional insert on sqlite script. The problem is when i try to do it on a thread. I have no error message and the code is not passing the line "using (_dbTransaction = dbConnection.BeginTransaction())". Here follows the code (OBS: I'm using Unity 5.3.2p1):
private void CheckExistingDataThread(string p_tableName, List<Dictionary<string, string>> p_listData, string[] p_whereKeys)
{
Debug.Log("CheckExistingDataThread");
using (_dbConnection = new SqliteConnection(_dbURI))
{
Debug.Log("Database Loaded");
using (_dbCommand = _dbConnection.CreateCommand())
{
Debug.Log("Command Created");
using (_dbTransaction = _dbConnection.BeginTransaction())
{
Debug.Log("Transaction Started");
_dbCommand.Connection = _dbConnection;
_dbCommand.Transaction = _dbTransaction;
for (int i = 0; i < p_listData.Count; i ++)
{
string __sql = string.Empty;
__sql = "SELECT COUNT() FROM " + p_tableName + " WHERE ";
for (int k = 0; k < p_whereKeys.Length; k ++)
{
if (k < p_whereKeys.Length - 1)
{
__sql += p_whereKeys[k] + " = \"" + p_listData[i][p_whereKeys[k]] + "\" AND ";
}
else
{
__sql += p_whereKeys[k] + " = \"" + p_listData[i][p_whereKeys[k]] + "\"";
}
}
//Debug.Log(__sql);
_dbCommand.CommandText = __sql;
try
{
using (_dbReader = _dbCommand.ExecuteReader())
{
while(_dbReader.Read())
{
int __value = _dbReader.GetInt32(0);
if (__value > 0)
{
UpdateTableData(p_tableName, p_listData[i], p_whereKeys);
}
else
{
InsertTableData(p_tableName, p_listData[i]);
}
}
}
}
catch(SqliteException sqle)
{
Debug.Log("Exception " + sqle);
}
}
}
_dbTransaction.Commit();
}
_dbConnection.Close();
}
}

Null Reference : Object reference not set to an instance of an object

I have a code for serial communication, with this code im sending values from textboxes to an device or when im testing to another PC. But when I press my "Program" button I get this error.
System.NullReferenceException was unhandled
Object reference not set to an instance of an object.
And i can catch the exception with an try catch but then i wont send my values to the device connected to my port.
This is my code:
public partial class MainForm : Form
{
private Settings _settings;
private SettingsIniFile _settingsIniFile = new SettingsIniFile();
private StringList _baudratelist = new StringList();
private StringList _systemPorts = new StringList();
private StringList _comportList = new StringList();
private Timer _comtimer = new Timer();
private ComPort _comport;
public MainForm()
{
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
//var portname = GetCurrentComPort();
}
private String GetCurrentComPort()
{
int index = _comPortComboBox.SelectedIndex;
if (index < 0)
return null;
return _comportList[index];
}
private void OnComtimerOnTick(object sender, EventArgs args)
{
foreach (var item in SerialPort.GetPortNames())
{
if (!_systemPorts.Contains(item))
{
_comtimer.Stop();
_systemPorts.Add(item);
LoadComportName();
//MessageBox.Show("The new device is connected to" + item);
_comtimer.Start();
}
}
}
private void LoadSettings(bool defaults)
{
SettingsIniFile iniFile = new SettingsIniFile();
_settings = iniFile.LoadSettings(defaults);
}
private void SaveSettings()
{
SaveTextBoxes();
_settingsIniFile.Save(_settings);
}
private void LoadTextBoxes()
{
//ACR
_startRemovalTextBox.Text = _settings.AcrStartRemoval11;
_removalTimeTextBox.Text = _settings.AcrRemovalTime12;
_removalDelayTextBox.Text = _settings.AcrRemovalDelay13;
//CLEANING
_durCleaningTextbox.Text = _settings.CleanDurCleaning21;
_timeValveOnTextbox.Text = _settings.CleanTimeValveOn22;
_timeValveOffTextBox.Text = _settings.CleanTimeValveOff23;
//CALIBRATE
_contentLeftTextBox.Text = _settings.CalibrateContentLeft31;
_calibrateLeftTextBox.Text = _settings.CalibrateCalibrateLeft33;
_contentRightTextBox.Text = _settings.CalibrateContentRight32;
_calibrateRightTextBox.Text = _settings.CalibrateCalibrateRight34;
//CONDUCTIVITY
_factorLeftTextBox.Text = _settings.ConductFactorLeft41;
_offsetLeftTextBox.Text = _settings.ConductOffsetleft42;
_factorRightTextBox.Text = _settings.ConductFactorRight43;
_offsetRightTextBox.Text = _settings.ConductOffsetRight44;
_levelLeftTextBox.Text = _settings.ConductLevelLeft45;
_levelRightTextBox.Text = _settings.ConductLevelRight46;
//GENERAL
_typeOfValveTextBox.Text = _settings.GeneralTypeOfValve51;
_indicatorTextBox.Text = _settings.GeneralIndicator52;
_inverseOutputTextBox.Text = _settings.GeneralInverseOutput53;
_restartTimeTextBox.Text = _settings.GeneralRestartTime54;
_waterTimeTextBox.Text = _settings.GeneralWaterTime55;
_gateDelayTextbox.Text = _settings.GeneralGateDelay56;
//PULSATION
_pulsationTextBox.Text = _settings.PulsationPulsationPm61;
_ratioFrontTextBox.Text = _settings.PulsationSrRatioFront62;
_ratioBackTextBox.Text = _settings.PulsationSrRatioBack63;
_stimulationTextBox.Text = _settings.PulsationStimulationPm64;
_stimFrontTextBox.Text = _settings.PulsationSrStimFront65;
_stimBackTextBox.Text = _settings.PulsationSrStimBack66;
_stimulationDurTextBox.Text = _settings.PulsationStimulationDur67;
//return _settings;
}
private void SaveTextBoxes()
{
//ACR
_settings.AcrStartRemoval11 = _startRemovalTextBox.Text;
_settings.AcrRemovalTime12 = _removalTimeTextBox.Text;
_settings.AcrRemovalDelay13 = _removalDelayTextBox.Text;
//CLEANING
_settings.CleanDurCleaning21 = _durCleaningTextbox.Text;
_settings.CleanTimeValveOn22 = _timeValveOnTextbox.Text;
_settings.CleanTimeValveOff23 = _timeValveOffTextBox.Text;
//CALIBRATE
_settings.CalibrateContentLeft31 = _contentLeftTextBox.Text;
_settings.CalibrateCalibrateLeft33 = _calibrateLeftTextBox.Text;
_settings.CalibrateContentRight32 = _contentRightTextBox.Text;
_settings.CalibrateCalibrateRight34 = _calibrateRightTextBox.Text;
//CONDUCTIVITY
_settings.ConductFactorLeft41 = _factorLeftTextBox.Text;
_settings.ConductOffsetleft42 = _offsetLeftTextBox.Text;
_settings.ConductFactorRight43 = _factorRightTextBox.Text;
_settings.ConductOffsetRight44 = _offsetRightTextBox.Text;
_settings.ConductLevelLeft45 = _levelLeftTextBox.Text;
_settings.ConductLevelRight46 = _levelRightTextBox.Text;
//GENERAL
_settings.GeneralTypeOfValve51 = _typeOfValveTextBox.Text;
_settings.GeneralIndicator52 = _indicatorTextBox.Text;
_settings.GeneralInverseOutput53 = _inverseOutputTextBox.Text;
_settings.GeneralRestartTime54 = _restartTimeTextBox.Text;
_settings.GeneralWaterTime55 = _waterTimeTextBox.Text;
_settings.GeneralGateDelay56 = _gateDelayTextbox.Text;
//PULSATION
_settings.PulsationPulsationPm61 = _pulsationTextBox.Text;
_settings.PulsationSrRatioFront62 = _ratioFrontTextBox.Text;
_settings.PulsationSrRatioBack63 = _ratioBackTextBox.Text;
_settings.PulsationStimulationPm64 = _stimulationTextBox.Text;
_settings.PulsationSrStimFront65 = _stimFrontTextBox.Text;
_settings.PulsationSrStimBack66 = _stimBackTextBox.Text;
_settings.PulsationStimulationDur67 = _stimulationDurTextBox.Text;
}
private void DefaultSettingButtonClick(object sender, System.EventArgs e)
{
LoadSettings(true);
LoadTextBoxes();
SaveSettings();
LoadComportName();
}
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void LoadComportName()
{
var availablePorts = _systemPorts;
_comPortComboBox.DataSource = null;
if (availablePorts != null && availablePorts.Any())
{
_comPortComboBox.DataSource = availablePorts;
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void SetBaudrate()
{
_baudratelist.Add("4600");
_baudratelist.Add("9600");
_baudratelist.Add("19200");
}
private void SendMessageTest()
{
var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
+ _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
_removalDelayTextBox.Text + "\r\n";
var Cleaningcontent ="["+ _cleaningNamelLabel.Text+"]" +"\r\n"+_cleaningIdLabel21.Text+
_durCleaningTextbox.Text + "\r\n"+ _cleaningLabelId22.Text+
_timeValveOnTextbox.Text + "\r\n"+ _cleaningLabelId23.Text+_timeValveOffTextBox.Text+"\r\n";
var Calibratecontent = "[" +_calibrateNameLabel.Text+ "]"+"\r\n"+_calibrateIDLabel31.Text+_contentLeftTextBox.Text+
"\r\n"+ _calibrateIDLabel32.Text+_calibrateLeftTextBox.Text+"\r\n"+_calibrateIDLabel33.Text+_contentRightTextBox.Text+
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
try
{
_comport.WriteBytes(array);
}
catch(Exception exc)
{
MessageBox.Show("Error {1}: "+ exc);
}
try
{
_comport.ReadBytes(array, array.Length, 1000);
}
catch(Exception exc)
{
MessageBox.Show("Error {2}" + exc);
}
//string result = Encoding.ASCII.GetString(array);
//MessageBox.Show(result);
}
}
This is my code for the communication:
namespace Communication
{
public class ComPort
{
private readonly SerialPort _serialPort;
public ComPort(string portname, int baudRate)
{
_serialPort = new SerialPort();
_serialPort.PortName = portname; <-----
_serialPort.BaudRate = baudRate;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.Handshake = Handshake.None;
// _serialPort.WriteBufferSize = 1;
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
_serialPort.Open();
_serialPort.ReadTimeout = 20000;
_serialPort.WriteTimeout = 20000;
}
public void Clear()
{
while (ReadByte() != -1)
continue;
}
private byte[] _array = new byte[] {0};
public void WriteByte(byte value)
{
_array[0] = value;
_serialPort.Write(_array, 0, 1);
// _serialPort.BaseStream.WriteByte(value);
_serialPort.BaseStream.Flush();
}
public void WriteBytes(byte[] array)
{
_serialPort.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length )
{
_serialPort.Write(array, index, length);
}
private int _readTimeOut = -1;
public int ReadByte(int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
return _serialPort.ReadByte();
// _serialPort.Read(array, 0, 1);
// return array[0];
}
catch (TimeoutException)
{
return -1;
}
}
public int ReadBytes(byte[] array, int length, int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
int bytesRead = 0;
while ( bytesRead < length )
bytesRead += _serialPort.Read(array, bytesRead, length - bytesRead);
// _serialPort.Read(array, 0, 1);
// return array[0];
return bytesRead;
}
catch (TimeoutException)
{
return -1;
}
}
/// <summary>
/// sends string followed by CR - LF
/// </summary>
/// <param name="line"></param>
public void WriteLine(String line)
{
WriteBytes(StringToBytes(line + "\r\n"));
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
public void Close()
{
try
{
_serialPort.DtrEnable = false;
_serialPort.RtsEnable = false;
_serialPort.Close();
}
catch(IOException)
{
}
}
public bool Dtr
{
get { return _serialPort.DtrEnable; }
set { _serialPort.DtrEnable = value; }
}
public bool Rts
{
get { return _serialPort.RtsEnable; }
set { _serialPort.RtsEnable = value; }
}
}
}
Can someone explain to me what the problem is?
Thanks in advance
Possible anwser:
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
_comport = new ComPort("COM6", 9600);
But when i do this another error comes around the corner:
Value cannot be null.
Parameter name: PortName
This comes in the second piece of code where the arrow is.
Probably there is not comport selected at startup, so the _comport never gets created, you should check if the comport is created before you use is: if (_comport != null) ...
Update:
I think you should create a button instead of default connecting on a combobox selection change.
public void buttonConnect_Click(object sender, EventArgs e)
{
// check if the comport is created, else show a message and return,
TryDisconnect();
var portname = GetCurrentComPort();
if (portname == null)
return;
try
{
_comport = new ComPort(portname, 9600);
}
catch(Exception exception)
{
// try to create a better message here :-)
MessageBox.Show("Something went wrong....");
}
}
public void buttonDisconnect_Click(object sender, EventArgs e)
{
TryDisconnect();
}
public void TryDisconnect()
{
if( _comport != null)
{
_comport.Dispose();
_comport = null;
}
}
Also for this:
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
// check the _comPort instance first, if not assigned, leave a message..
if(_comPort == null)
{
MessageBox.Show("The comport is not initialized");
return;
}
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
I got a tip for you, try to separate the markup/construction of the message, here how you could do.
I did not change all the code, only some examples:
I would create a struct/class to hold all information
public struct AcrContentInfo
{
public string AcrName;
public string AcrId11;
public string StartRemoval;
public string AcrId12;
public string RemovalTime;
public string AcrId13;
public string RemovalDelay;
// markup the information:
public override string ToString()
{
return string.Format(
"[{0}]\r\n{1}{2}\r\n{3}{4}\r\n{5}{6}\r\n",
AcrName,
AcrId11, StartRemoval,
AcrId12, RemovalTime,
AcrId13, RemovalDelay);
}
}
private void SendMessageTest()
{
// Instead of:
//var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
// + _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
// _removalDelayTextBox.Text + "\r\n";
// I would use this instead, this way it wil be easier to maintain different versions.
// The code using the struct isn't responsible for markup
// Create the struct and fillin the fields.
AcrContentInfo acrContentInfo = new AcrContentInfo
{
AcrName = _acrNameLabel.Text,
AcrId11 = _acrIdLabel11.Text,
StartRemoval = _startRemovalTextBox.Text,
AcrId12 = _acrIdLabel12.Text,
RemovalTime = _removalTimeTextBox.Text,
AcrId13 = _acrIdLabel13.Text,
RemovalDelay = _removalDelayTextBox.Text
};
// if there is a new version of the protocol, you can create something like this
// AcrContentInfoV2 acrContentInfo = new AcrContentInfoV2
// call the tostring, (create a markup)
var Acrcontent = acrContentInfo.ToString();
// --- old code ---
var Cleaningcontent = "[" + _cleaningNamelLabel.Text + "]" + "\r\n" + _cleaningIdLabel21.Text +
_durCleaningTextbox.Text + "\r\n" + _cleaningLabelId22.Text +
_timeValveOnTextbox.Text + "\r\n" + _cleaningLabelId23.Text + _timeValveOffTextBox.Text + "\r\n";
var Calibratecontent = "[" + _calibrateNameLabel.Text + "]" + "\r\n" + _calibrateIDLabel31.Text + _contentLeftTextBox.Text +
"\r\n" + _calibrateIDLabel32.Text + _calibrateLeftTextBox.Text + "\r\n" + _calibrateIDLabel33.Text + _contentRightTextBox.Text +
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
// instad of:
//byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
// I always try not to make very long lines of code.
// A stringbuilder is much more efficient building strings.
// I would:
StringBuilder sb = new StringBuilder();
sb.AppendLine("2");
sb.AppendLine("Acrcontent");
sb.AppendLine("Cleaningcontent");
sb.AppendLine("Calibratecontent");
sb.AppendLine("Conductcontent");
sb.AppendLine("Generalcontent");
sb.AppendLine("Pulsationcontent");
sb.AppendLine("3");
// why make the comport class responsible for the encoding type. _ComPort.StringToBytes_
byte[] array = Encoding.UTF8.GetBytes(sb.ToString());
try
{
_comport.WriteBytes(array);
// only read when write was succeed?
_comport.ReadBytes(array, array.Length, 1000);
}
catch (Exception exc)
{
MessageBox.Show("Error {1}: " + exc);
}
}
These are only my ideas, and meant to be constructive. (other point of view) Happy codeing..
You have to instantiate _comport before calling a method or accessing a property on it.
maybe in
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
portname is null then _comport not instantiated. you can trace it and check that if it has a value or not.
Yes assign a value to _comport like
_comport=null;

MSMQ System.Messaging high resource usage

I have make C# console application which uses timer which connects to MSMQ every 10 seconds get data insert into Oracle database. But the issue is that it log in and log off to domain and create high CPU also create security audit log very much which waste my resources.
My console application runs with task schedule. Code is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Xml;
using System.IO;
using System.Timers;
using Oracle.DataAccess.Client;
using System.Data;
namespace MSMQ_News
{
class Program
{
private static System.Timers.Timer aTimer;
static void Main(string[] args)
{
try
{
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(60000);//10000
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
//aTimer.Interval = 10000;
aTimer.Enabled = true;
aTimer.Start();
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
catch (Exception ex)
{
Log(" From Main -- " + ex.Message);
}
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Just in case someone wants to inherit your class and lock it as well ...
object _padlock = new object();
try
{
aTimer.Stop();
lock (_padlock)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
ProcessQueueMsgs();
}
}
catch (Exception ex)
{
Log(" From OnTimedEvent -- " + ex.Message);
}
finally
{
aTimer.Start();
}
}
private static void ProcessQueueMsgs()
{
try
{
while ((DateTime.Now.Hour >= 06)
&& (DateTime.Now.Hour <= 16))
{
DateTime dt = DateTime.Now;
ReceiveNewsDetail(dt);
ReceiveNewsHeader(dt);
}
CloseApp();
}
catch (Exception ex)
{
Log(" From ProcessQueueMsgs -- " + ex.Message);
}
}
static bool QueueExist(string QueueName)
{
try
{
if (MessageQueue.Exists(QueueName))
return true;
else
return false;
}
catch (Exception ex)
{
Log(" From QueueExist -- " + ex.Message);
return false;
}
}
private static void ReceiveNewsHeader(DateTime dt)
{
try
{
MessageQueue mqNewsHeader = null;
string value = "", _tmp = "";
_tmp = "<newsHeader></newsHeader> ";
/*if (QueueExist(#".\q_ws_ampnewsheaderrep"))*/
mqNewsHeader = new MessageQueue(#".\q_ws_ampnewsheaderrep");
int MsgCount = GetMessageCount(mqNewsHeader, #".\q_ws_ampnewsheaderrep");
for (int i = 0; i < MsgCount; i++)
{
Message Msg = mqNewsHeader.Receive();
Msg.Formatter = new ActiveXMessageFormatter();
//need to do this to avoid ??? for arabic characters
using (StreamReader strdr = new StreamReader(Msg.BodyStream, System.Text.Encoding.Default))
{
value = strdr.ReadToEnd();
}
value = value.Replace("\0", String.Empty);
if (value != _tmp)
{
LoadNewsHeader(value, dt);
}
}
}
catch (Exception ex)
{
Log("From ReceiveNewsHeader -- " + ex.Message);
}
}
private static void ReceiveNewsDetail(DateTime dt)
{
try
{
MessageQueue mqNewsDetails = null;
string value = "", _tmp = "";
_tmp = "<news></news> ";
/*if (QueueExist(#".\q_ws_ampnewsrep"))*/
mqNewsDetails = new MessageQueue(#".\q_ws_ampnewsrep");
int MsgCount = GetMessageCount(mqNewsDetails, #".\q_ws_ampnewsrep");
for (int i = 0; i < MsgCount; i++)
{
Message Msg = mqNewsDetails.Receive();
Msg.Formatter = new ActiveXMessageFormatter();
//need to do this to avoid ??? for arabic characters
using (StreamReader strdr = new StreamReader(Msg.BodyStream, System.Text.Encoding.Default))
{
value = strdr.ReadToEnd();
}
value = value.Replace("\0", String.Empty);
if (value != _tmp)
{
LoadNewsDetail(value, dt);
}
}
}
catch (Exception ex)
{
Log("From ReceiveNewsDetail -- " + ex.Message);
}
}
private static void LoadNewsHeader(string text , DateTime dt)
{
try
{
//text = ReplaceSpecialCharacters(text);
//text = Clean(text);
//XmlDocument _xmlDoc = new XmlDocument();
//_xmlDoc.LoadXml(text);
//string fileName = "NewsHeader.xml";
text = text.Replace("<arabicFields>", "<arabicFields>\n\t\t");
//createXMLFile(fileName, text);
XmlDocument _xmlDoc = LoadXMLDoc(text);
string SQL = "";
XmlNodeList newsHeaderList = _xmlDoc.SelectNodes("newsHeader/newsHeaderRep");
if (newsHeaderList.Count > 0)
{
OracleParameter pTRUNCATE = new OracleParameter("P_TABLE_NAME", OracleDbType.Varchar2);
pTRUNCATE.Value = "COMPANIES_NEWS";
DatabaseOperation(CommandType.StoredProcedure, "TRUNCATE_TABLE", pTRUNCATE);
}
foreach (XmlNode news in newsHeaderList)
{
XmlNodeList newsIdList = news.SelectNodes("newsId");
SQL = "Insert into COMPANIES_NEWS(NewsID, NewsID_SEQNO, NEWSSTATUS, LANGUAGE_CD, SEC_CD, RELEASEDATE, RELEASETIME, TITLE, STG_TIME) Values(";
foreach (XmlNode newsId in newsIdList)
{
SQL += "'" + newsId["id"].InnerText + "',";
SQL += "" + newsId["seqNo"].InnerText + ",";
}
SQL += "'" + news["newsStatus"].InnerText + "',";
XmlNodeList newsItemList = news.SelectNodes("newsItem");
foreach (XmlNode newsItem in newsItemList)
{
SQL += "'" + newsItem["languageId"].InnerText + "',";
if (newsItem["reSecCode"] != null)
SQL += "'" + newsItem["reSecCode"].InnerText + "',";
else
SQL += "' ',";
XmlNodeList releaseTimeList = newsItem.SelectNodes("releaseTime");
foreach (XmlNode releaseTime in releaseTimeList)
{
SQL += "TO_DATE('" + releaseTime["date"].InnerText + "','YYYYMMDD'),";
SQL += "" + releaseTime["time"].InnerText + ",";
}
}
XmlNodeList arabicFieldsList = news.SelectNodes("arabicFields");
foreach (XmlNode arabicFields in arabicFieldsList)
{
SQL += "'" + RevertSpecialCharacters(arabicFields["title_AR"].InnerText) + "',";
}
SQL += "TO_DATE('" + dt.ToString() + "','MM/DD/YYYY HH12:MI:SS PM'))";
DatabaseOperation(CommandType.Text, SQL, null);
Console.WriteLine("Header : " + DateTime.Now.ToString());
}
if (SQL != "") //RecordCount("Select Count(*) from COMPANIES_NEWS_DETAILS") > 0
{
OracleParameter pREFRESH = new OracleParameter("P_TABLE_NAMEs", OracleDbType.Varchar2);
pREFRESH.Value = "COMPANIES_NEWS";
DatabaseOperation(CommandType.StoredProcedure, "REFRESH_VW_ALL", pREFRESH);
}
}
catch (Exception ex)
{
Log("From LoadNewsHeader -- " + ex.Message);
}
}
private static void LoadNewsDetail(string text, DateTime dt)
{
try
{
//string fileName = "NewsDetail.xml";
text = text.Replace("<arabicFields>", "<arabicFields>\n\t\t");
//text = createXMLFile(fileName);
//text = text.Replace("<arabicFields>", "<arabicFields>\n\t\t");
XmlDocument _xmlDoc = LoadXMLDoc(text);
string SQL = "";
XmlNodeList newsList = _xmlDoc.SelectNodes("news/newsRep");
if (newsList.Count > 0)
{
OracleParameter pTRUNCATE = new OracleParameter("P_TABLE_NAME", OracleDbType.Varchar2);
pTRUNCATE.Value = "COMPANIES_NEWS_DETAILS";
DatabaseOperation(CommandType.StoredProcedure, "TRUNCATE_TABLE", pTRUNCATE);
}
foreach (XmlNode news in newsList)
{
XmlNodeList newsIdList = news.SelectNodes("newsId");
SQL = "Insert into Companies_news_details(NewsID_ID, NewsID_SEQNO, NewsText_1,NewsText_2,STG_TIME) Values(";
foreach (XmlNode newsId in newsIdList)
{
SQL += "" + newsId["id"].InnerText + ",";
SQL += "" + newsId["seqNo"].InnerText + ",";
}
XmlNodeList arabicFieldsList = news.SelectNodes("arabicFields");
foreach (XmlNode arabicFields in arabicFieldsList)
{
// Log(" Before Arabic Text Data -- :" + arabicFields["newsText_AR"].InnerText);
if (arabicFields["newsText_AR"].InnerText.Length > 4000)
{
SQL += "'" + RevertSpecialCharacters(arabicFields["newsText_AR"].InnerText.Substring(0, 3999)).Replace("\n",Environment.NewLine) + "',";
SQL += "'" + RevertSpecialCharacters(arabicFields["newsText_AR"].InnerText.Substring(3999, arabicFields["newsText_AR"].InnerText.Length)).Replace("\n", Environment.NewLine) + "',";
SQL += "TO_DATE('" + dt.ToString() + "','MM/DD/YYYY HH12:MI:SS PM')";
}
else
{
SQL += "'" + RevertSpecialCharacters(arabicFields["newsText_AR"].InnerText).Replace("\n", Environment.NewLine) + "','',";
SQL += "TO_DATE('" + dt.ToString() + "','MM/DD/YYYY HH12:MI:SS PM')";
}
SQL += ")";
DatabaseOperation(CommandType.Text, SQL, null);
Console.WriteLine("Detail : " + DateTime.Now.ToString());
}
}
if (SQL != "") //RecordCount("Select Count(*) from COMPANIES_NEWS_DETAILS") > 0
{
OracleParameter pREFRESH = new OracleParameter("P_TABLE_NAMEs", OracleDbType.Varchar2);
pREFRESH.Value = "COMPANIES_NEWS_DETAILS";
DatabaseOperation(CommandType.StoredProcedure, "REFRESH_VW_ALL", pREFRESH);
}
}
catch (Exception ex)
{
Log("From LoadNewsDetail -- " + ex.Message);
}
}
private static void CloseApp()
{
System.Environment.Exit(0);
}
protected static int GetMessageCount(MessageQueue q, string queueName)
{
var _messageQueue = new MessageQueue(queueName, QueueAccessMode.Peek);
_messageQueue.Refresh(); //done to get the correct count as sometimes it sends 0
var x = _messageQueue.GetMessageEnumerator2();
int iCount = 0;
while (x.MoveNext())
{
iCount++;
}
return iCount;
}
private static void DatabaseOperation(CommandType cmdType, string SQL, OracleParameter param)
{
string oracleConnectionString = System.Configuration.ConfigurationSettings.AppSettings["OracleConnectionString"];
using (OracleConnection con = new OracleConnection())
{
con.ConnectionString = oracleConnectionString;
con.Open();
OracleCommand command = con.CreateCommand();
command.CommandType = cmdType;
command.CommandText = SQL;
if (param != null)
command.Parameters.Add(param);
command.ExecuteNonQuery();
command.Dispose();
con.Close();
}
}
private static String RevertSpecialCharacters(string pValue)
{
string _retVal = String.Empty;
_retVal = pValue.Replace("'", "''");
return _retVal;
}
public static void Log(string Message)
{
// Create a writer and open the file:
StreamWriter log;
//C:\Software\MSMQ_New_News_Fix
if (!File.Exists(#"C:\MSMQ_New_News_Fix\log.txt"))
{
log = new StreamWriter(#"C:\MSMQ_New_News_Fix\log.txt");
}
else
{
log = File.AppendText(#"C:\MSMQ_New_News_Fix\log.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now.ToString() + " : " + Message);
// Close the stream:
log.Close();
}
public static XmlDocument LoadXMLDoc(string xmlText)
{
XmlDocument doc = new XmlDocument();
try
{
string xmlToLoad = ParseXMLFile(xmlText);
doc.LoadXml(xmlToLoad);
}
catch (Exception ex)
{
Log("From LoadXMLDoc -- " + ex.Message);
}
return doc;
}
private static string ParseXMLFile(string xmlText)
{
StringBuilder formatedXML = new StringBuilder();
try
{
StringReader xmlReader = new StringReader(xmlText);
while (xmlReader.Peek() >= 0)
formatedXML.Append(ReplaceSpecialChars(xmlReader.ReadLine()) + "\n");
}
catch (Exception ex)
{
Log("From ParseXMLFile -- " + ex.Message);
}
return formatedXML.ToString();
}
private static string ReplaceSpecialChars(string xmlData)
{
try
{
//if (xmlData.Contains("objectRef")) return "<objectRef></objectRef>";
int grtrPosAt = xmlData.IndexOf(">");
int closePosAt = xmlData.IndexOf("</");
int lenthToReplace = 0;
if (grtrPosAt > closePosAt) return xmlData;
lenthToReplace = (closePosAt <= 0 && grtrPosAt <= 0) ? xmlData.Length : (closePosAt - grtrPosAt) - 1;
//get the string between xml element. e.g. <ContactName>Hanna Moos</ContactName>,
//you will get 'Hanna Moos'
string data = xmlData.Substring(grtrPosAt + 1, lenthToReplace);
string formattedData = data.Replace("&", "&").Replace("<", "<")
.Replace(">", ">").Replace("'", "&apos;");
if (lenthToReplace > 0) xmlData = xmlData.Replace(data, formattedData);
return xmlData;
}
catch (Exception ex)
{
Log("From ReplaceSpecialChars -- " + ex.Message);
return "";
}
}
}
}
How can i solve above issue
Why not host your queue reader process in a windows service. This will continually poll the queue each 10 seconds.
Then use the windows scheduler to start/stop the service at relevant times to create your service window.
This means you won't need to do anything complicated in your scheduled task, and you won't be loading and unloading all the time.
Well from logic you are very correct that I should make windows service not timer service and Task schedule.
But my question was why It is login / log out frequently, which waste the resource of my Domain server. After intense investigation, I found that calling QueueExits is resource critical. Another thing what I found is that when you connect MSMQ queue you are login to share resource, which will login to Domain. As my code was running every 10-20 seconds it was wasting my Domain server resources.
For resolution, I make my MessageQueue object globally in following way
private static MessageQueue mqNewsHeader = new MessageQueue(#".\q_ws_ampnewsheaderrep");
private static MessageQueue mqNewsDetails = new MessageQueue(#".\q_ws_ampnewsrep");
So it will create Once in the life of the Application and we will log in and log out only once. Then I will pass this object to the function as parameter. I see also that my MessageQueue count function was also resource critical, So I change it to following
protected static int GetMessageCount(MessageQueue q)
{
//var _messageQueue = new MessageQueue(queueName, QueueAccessMode.Peek);
//_messageQueue.Refresh(); //done to get the correct count as sometimes it sends 0
// var x = _messageQueue.GetMessageEnumerator2();
int iCount = q.GetAllMessages().Count();
// while (x.MoveNext())
// {
// iCount++;
// }
return iCount;
}
Hope this clear my answer and will help others also.

Images extracted from pdf file is inverted/negative image.(C#)

Hi i am working on pdf to xhtml conversion using pdf clown library(C#).I am extracting the pdf content,the images which i extracted is inverted image.I want the real images,please any suggestions?..
The code is pasted below,
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 it.stefanochizzolini.clown.documents;
using it.stefanochizzolini.clown.files;
using it.stefanochizzolini.clown.documents.contents;
using it.stefanochizzolini.clown.documents.contents.objects;
using it.stefanochizzolini.clown.tools;
using it.stefanochizzolini.clown.documents.contents.composition;
using it.stefanochizzolini.clown.documents.contents.fonts;
using System.IO;
using it.stefanochizzolini.clown.bytes;
using it.stefanochizzolini.clown.objects;
namespace Test1
{
public partial class Form1 : Form
{
public int index;
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files|*.pdf";
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnProcess_Click(object sender, EventArgs e)
{
InitiateProcess(txtFileName.Text.Trim());
}
private void InitiateProcess(string FileName)
{
it.stefanochizzolini.clown.files.File file;
Document document;
try
{
// Open the PDF file!
file = new it.stefanochizzolini.clown.files.File(FileName);
// Get the PDF document!
document = file.Document;
//file.Dispose();
}
catch
{
MessageBox.Show("Sorry. Error in File");
return;
}
//Page stamper is used to draw contents on existing pages.
PageStamper stamper = new PageStamper();
foreach (Page page in document.Pages)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + "\nScanning page " + (page.Index + 1) + "...\n";
stamper.Page = page;
// Wraps the page contents into a scanner.
Extract(new ContentScanner(page), stamper.Foreground, page );
stamper.Flush();
this.Refresh();
}
}
private void Extract(ContentScanner level, PrimitiveFilter builder, Page page)
{
string ctype = string.Empty;
if (level == null)
return;
while (level.MoveNext())
{
ContentObject content = level.Current;
//TextExtractor extractor = new TextExtractor();
string aa = content.GetType().ToString();
/*if(content is Text)
{
txtOutput.Text = txtOutput.Text + aa + Environment.NewLine;
List<ITextString> textStrings = extractor.Extract(page)[TextExtractor.DefaultArea];
foreach(ITextString textstring in textStrings)
{
RectangleF textstringbox=textstring.Box.Value;
txtOutput.Text = txtOutput.Text + "x:" + Math.Round(textstringbox.X);
txtOutput.Text = txtOutput.Text + "y:" + Math.Round(textstringbox.Y) + ",";
txtOutput.Text = txtOutput.Text + "w:" + Math.Round(textstringbox.Width) + ",";
txtOutput.Text = txtOutput.Text + "h:" + Math.Round(textstringbox.Height);
txtOutput.Text=txtOutput.Text+ "]: " + textstring.Text.ToString();
}
}*/
if (content is Text)
{
ContentScanner.TextWrapper text = (ContentScanner.TextWrapper)level.CurrentWrapper;
//ContentScanner.GraphicsState test = level.getState();
foreach (ContentScanner.TextStringWrapper textString in text.TextStrings)
{
RectangleF rf = (RectangleF)textString.Box;
/*txtOutput.Text = txtOutput.Text + Environment.NewLine + "Text [font size: " + textString.Style.FontSize + " ],[font Name: " +
textString.Style.Font.Name + " ]: " + textString.Text + "[position = left :" + rf.Left.ToString() + " & Top: " + rf.Top.ToString() + "X:" + rf.X.ToString() + "Y:" + rf.Y.ToString();*/
txtOutput.Text = txtOutput.Text + Environment.NewLine + textString.Text;
}
}
//else if (content is MarkedContent)
//{
// //MarkedContent mc = (MarkedContent) content
//}
else if (content is ShowText)
{
it.stefanochizzolini.clown.documents.contents.fonts.Font font = level.State.Font;
txtOutput.Text = txtOutput.Text + (font.Decode(((ShowText)content).Text));
}
else if (content is ContainerObject)
{
// Scan the inner level!
Extract(level.ChildLevel, builder, page);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.InlineImage)
{
ContentScanner.InlineImageWrapper img = (ContentScanner.InlineImageWrapper)level.CurrentWrapper;
ExportImage(
img.InlineImage.Body.Value,
txtOutputPath.Text.Trim() + System.IO.Path.DirectorySeparatorChar + "ImageExtractionSample_" + (index++) + ".jpg"
);
}
else if (content is it.stefanochizzolini.clown.documents.contents.objects.GraphicsObject)
{
/*=============================================================================
* TO EXTRACT THE GRAPHICAL OBJECT WITHIN THE PDF
=============================================================================*/
ContentScanner.GraphicsObjectWrapper objectWrapper = level.CurrentWrapper;
if (objectWrapper == null)
{
continue;
}
/*
NOTE: Images can be represented on a page either as
external objects (XObject) or inline objects.
*/
SizeF? imageSize = null; // Image native size.
/*if (objectWrapper is PdfDataObject)
{
ContentScanner.GraphicsObjectWrapper gobjectwrapper=(ContentScanner.GraphicsObjectWrapper)gobjectwrapper;
it.stefanochizzolini.clown.objects.PdfDataObject pdobjt=gobjectwrapper
}*/
//if(objectWrapper is Image)
//{
// }
if (objectWrapper is ContentScanner.XObjectWrapper)
{
ContentScanner.XObjectWrapper xObjectWrapper = (ContentScanner.XObjectWrapper)objectWrapper;
it.stefanochizzolini.clown.documents.contents.xObjects.XObject Xobject = xObjectWrapper.XObject;
// Is the external object an image?
if (Xobject is it.stefanochizzolini.clown.documents.contents.xObjects.ImageXObject)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine +
"External Image '" + xObjectWrapper.Name + "' (" + Xobject.BaseObject + ")"; // Image key and indirect reference.
imageSize = Xobject.Size; // Image native size.
PdfDataObject dataObject = Xobject.BaseDataObject;
;
PdfDictionary header = ((PdfStream)dataObject).Header;
if (header.ContainsKey(PdfName.Type) && header[PdfName.Type].Equals(PdfName.XObject) && header[PdfName.Subtype].Equals(PdfName.Image))
{
if (header[PdfName.Filter].Equals(PdfName.Image)) // JPEG image.
{
// Get the image data (keeping it encoded)!
IBuffer body1 = ((PdfStream)dataObject).GetBody(false);
//object h1 = PdfName.ColorSpace;
// Export the image!
ExportImage(
body1,
txtOutputPath.Text + System.IO.Path.DirectorySeparatorChar + "Image_" + (index++) + ".png"
);
}
}
}
else if (content is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
Dictionary<RectangleF?, List<ITextString>> textStrings = null;
PageAnnotations annotations = page.Annotations;
TextExtractor extractor = new TextExtractor();
if (annotations == null)
{
Console.WriteLine("No annotations here.");
continue;
}
foreach (it.stefanochizzolini.clown.documents.interaction.annotations.Annotation annotation in annotations)
{
if (annotation is it.stefanochizzolini.clown.documents.interaction.annotations.Link)
{
if (textStrings == null)
{ textStrings = extractor.Extract(page); }
it.stefanochizzolini.clown.documents.interaction.annotations.Link link = (it.stefanochizzolini.clown.documents.interaction.annotations.Link)annotation;
RectangleF linkBox = link.Box;
StringBuilder linkTextBuilder = new StringBuilder();
foreach (ITextString linkTextString in extractor.Filter(textStrings, linkBox))
{ linkTextBuilder.Append(linkTextString.Text); }
string bb = linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + "Link '" + linkTextBuilder.ToString();
txtOutput.Text = txtOutput.Text + " Position: "
+ "x:" + Math.Round(linkBox.X) + ","
+ "y:" + Math.Round(linkBox.Y) + ","
+ "w:" + Math.Round(linkBox.Width) + ","
+ "h:" + Math.Round(linkBox.Height);
}
}
}
else if (objectWrapper is ContentScanner.InlineImageWrapper)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + "Inline Image";
InlineImage inlineImage = ((ContentScanner.InlineImageWrapper)objectWrapper).InlineImage;
imageSize = inlineImage.Size; // Image native size.
}
if (imageSize.HasValue)
{
RectangleF box = objectWrapper.Box.Value; // Image position (location and size) on the page.
txtOutput.Text = txtOutput.Text + Environment.NewLine +
" on page " + (page.Index + 1) + " (" + page.BaseObject + ")"; // Page index and indirect reference.
txtOutput.Text = txtOutput.Text + Environment.NewLine + " Coordinates:";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " x: " + Math.Round(box.X);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " y: " + Math.Round(box.Y);
txtOutput.Text = txtOutput.Text + Environment.NewLine + " width: " + Math.Round(box.Width) + " (native: " + Math.Round(imageSize.Value.Width) + ")";
txtOutput.Text = txtOutput.Text + Environment.NewLine + " height: " + Math.Round(box.Height) + " (native: " + Math.Round(imageSize.Value.Height) + ")";
}
/*=============================================================================*/
}
}
}
}
private void ExportImage(IBuffer data, string outputPath)
{
FileStream outputStream;
try
{ outputStream = new FileStream(outputPath, FileMode.CreateNew); }
catch (Exception e)
{ throw new Exception(outputPath + " file couldn't be created.", e); }
try
{
BinaryWriter writer = new BinaryWriter(outputStream);
//ImageConverter ic = new ImageConverter();
//Image img = (Image)ic.ConvertFrom(data);
writer.Write(data.ToByteArray());
writer.Close();
outputStream.Close();
}
catch (Exception e)
{ throw new Exception(outputPath + " file writing has failed.", e); }
Console.WriteLine("Output: " + outputPath);
}
private void txtOutputPath_TextChanged(object sender, EventArgs e)
{
if (txtFileName.Text.Trim().Length > 0 && txtOutputPath.Text.Trim().Length > 0)
{
btnProcess.Enabled = true;
}
else { btnProcess.Enabled = false; }
}
private void btnBrowseOutput_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
txtOutputPath.Text = folderBrowserDialog1.SelectedPath;
}
private void btnsave_Click(object sender, EventArgs e)
{
if(txtOutput.Text=="")
{
MessageBox.Show("text box is empty");
}
else
{
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter yaz = new StreamWriter(saveFileDialog1.FileName.ToString());
string yasoutput = txtOutput.Text;
yaz.Write(yasoutput);
}
}
}
private void btncancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnclear_Click(object sender, EventArgs e)
{
txtFileName.Text = "";
txtOutput.Text = "";
txtOutputPath.Text = "";
}
}
}
You would need to invert the image buffer i.e copy the image buffer that you receive to a new buffer starting from the last byte of the image buffer to the first byte of the image buffer. This should take care of the inverted image. The for each pixel data, assuming 24-bit RGB values, swap the R and B values such that RGB becomes BGR. This should get rid of the 'negative' effect and save this new buffer.
Pass your bitmap image to the below function...
private byte[] BmpToBytes_Unsafe (Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0,0,IMAGE_WIDTH,IMAGE_HEIGHT),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
int lineSize = bData.Width * 3;
int byteCount = lineSize * bData.Height;
byte[] bmpBytes = new byte[byteCount];
byte[] tempLine = new byte[lineSize];
int bmpIndex = 0;
IntPtr scan = new IntPtr(bData.Scan0.ToInt32() + (lineSize * (bData.Height-1)));
for (int i = 0; i < bData.Height; i++)
{
Marshal.Copy(scan, tempLine, 0, lineSize);
scan = new IntPtr(scan.ToInt32()-bData.Stride);
tempLine.CopyTo(bmpBytes, bmpIndex);
bmpIndex += lineSize;
}
bmp.UnlockBits(bData);
return bmpBytes;
}
Happy coding...:)

Categories

Resources