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;
Related
I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.
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();
}
}
Following Code snippet is sending PIN to another Self Hosted WCF service inside Windows Service which further then makes a call to SMPP server. But that only happens when i am in debug mode. In normal mode it does not work.
$
ChannelFactory<IServiceWCF> pipeFactory =
new ChannelFactory<IServiceWCF>(
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/MyService/PipeForMyService"));
pipeProxy = pipeFactory.CreateChannel();
pipeProxy.Connect();
pipeProxy.SendPin(pin);
ServiceWCF
$
public class ServiceWCF : IServiceWCF
{
PINComposer pinComposer = new PINComposer();
public bool SendPin(string pin)
{
Library.WriteErrorLog("Call Hits. Pin is " + pin);
PINComposer pinComposer = new PINComposer();
pinComposer.Connect();
pinComposer._client.SendSpeedLimit = 0;
DataCodings coding = (DataCodings)Enum.Parse(typeof(DataCodings), "Default");
byte srcTon = byte.Parse("0");
byte srcNpi = byte.Parse("0");
string srcAdr = "2378";
byte dstTon = byte.Parse("1");
byte dstNpi = byte.Parse("1");
string dstAdr = "03347823422";
IList<SubmitSmResp> resp = pinComposer._client.Submit(SMS.ForSubmit()
.From(srcAdr, srcTon, srcNpi)
.To(dstAdr, dstTon, dstNpi)
.Coding(coding)
.Text(pin + " " + "is your pin code")
.ExpireIn(TimeSpan.FromDays(2))
.DeliveryReceipt()
);
Library.WriteErrorLog("SMS Sent");
return true;
}
public bool Connect()
{
pinComposer.Connect();
return true;
}
}
PINComposer.CS
$
class PINComposer
{
public readonly SmppClient _client;
private readonly MessageComposer _messageComposer = new MessageComposer();
public PINComposer()
{
_client = new SmppClient();
_client.Timeout = 60000;
_client.NeedEnquireLink = true;
_client.EnquireInterval = 20;
_client.RaiseEventsInMainThread = true;
_client.evConnected += new Inetlab.SMPP.Common.ConnectedEventHandler(client_evConnected);
_client.evDisconnected += new Inetlab.SMPP.Common.DisconnectedEventHandler(client_evDisconnected);
_client.evBindComplete += new Inetlab.SMPP.Common.BindRespEventHandler(client_evBindComplete);
_client.evDeliverSm += new Inetlab.SMPP.Common.DeliverSmEventHandler(client_evDeliverSm);
_client.evEnquireLink += new Inetlab.SMPP.Common.EnquireLinkEventHandler(client_evEnquireLink);
_client.evGenericNack += new Inetlab.SMPP.Common.GenericNackEventHandler(client_evGenericNack);
_client.evUnBind += new Inetlab.SMPP.Common.UnBindEventHandler(client_evUnBind);
_client.evDataSm += new Inetlab.SMPP.Common.DataSmEventHandler(client_evDataSm);
_client.evSubmitComplete += new Inetlab.SMPP.Common.SubmitSmRespEventHandler(client_evSubmitComplete);
_client.evQueryComplete += new Inetlab.SMPP.Common.QuerySmRespEventHandler(client_evQueryComplete);
_messageComposer.evFullMessageReceived += OnFullMessageReceived;
_messageComposer.evFullMessageTimedout += OnFullMessageTimedout;
}
public void Connect()
{
if (_client.Status == ConnectionStatus.Closed)
{
_client.AddrNpi = Convert.ToByte(0);
_client.AddrTon = Convert.ToByte(0);
_client.EnabledSslProtocols = SslProtocols.None;
_client.ConnectAsync("172.16.53.39", 2775);
}
}
void client_evConnected(object sender, bool bSuccess)
{
if (bSuccess)
{
_client.BindAsync("radius", "rad12", ConnectionMode.Transceiver);
Library.WriteErrorLog("SMPP Service has been connected to server...");
}
}
private void client_evEnquireLink(object sender, EnquireLink data)
{
Library.WriteErrorLog("Link with server is alive...");
}
private void client_evGenericNack(object sender, GenericNack data)
{
Library.WriteErrorLog("GenericNack received with status " + data.Status.ToString());
}
private void client_evUnBind(object sender, UnBind data)
{
Library.WriteErrorLog("UnBind request received");
}
void client_evSubmitComplete(object sender, SubmitSmResp data)
{
Library.WriteErrorLog("SubmitSmResp received." + " Status: " + data.Status + ", Message Id: " + data.MessageId + ", Sequence: " + data.Sequence);
}
void client_evQueryComplete(object sender, QuerySmResp data)
{
Library.WriteErrorLog("QuerySmResp received." + " Status: " + data.Status + ", Message Id: " + data.MessageId + ", Sequence: " + data.Sequence + ", Message State: " + data.MessageState);
}
private void client_evDeliverSm(object sender, DeliverSm data)
{
try
{
//Check if we received Delivery Receipt
if (data.MessageType == MessageTypes.SMSCDeliveryReceipt)
{
//Get MessageId of delivered message
string messageId = data.Receipt.MessageId;
MessageState deliveryStatus = data.Receipt.State;
}
else
{
// Receive incoming message and try to concatenate all parts
if (data.Concatenation != null)
{
_messageComposer.AddMessage(data);
Library.WriteErrorLog(
string.Format(
"DeliverSm part received : Sequence : {0} SourceAddr : {1} Concatenation ( {2} )" +
" Coding : {3} Text : {4}",
data.Sequence, data.SourceAddr, data.Concatenation, data.DataCoding, data.MessageText));
}
else
{
Library.WriteErrorLog("DeliverSm received : "
+ " Sequence : " + data.Sequence
+ " SourceAddr : " + data.SourceAddr
+ " Coding : " + data.DataCoding
+ " MessageText : " + data.MessageText);
}
}
}
catch (Exception ex)
{
data.Response.Status = CommandStatus.ESME_RX_T_APPN;
Library.WriteErrorLog("Failed to process DeliverSm" + ex);
}
}
private void client_evDataSm(object sender, DataSm data)
{
string messageText = data.Client.GetMessageText(data);
Library.WriteErrorLog("DataSm received :"
+ " Sequence: " + data.Sequence
+ ", SourceAddr: " + data.SourceAddr
+ ", DestAddr: " + data.DestAddr
+ ", Coding: " + data.DataCoding
+ ", Text: " + messageText);
}
void client_evDisconnected(object sender)
{
Library.WriteErrorLog("SmppClient disconnected");
}
private void OnFullMessageTimedout(object sender, MessageEventHandlerArgs args)
{
Library.WriteErrorLog(string.Format("Incomplete message received from {0}", args.Parts[0].SourceAddr));
}
private void OnFullMessageReceived(object sender, MessageEventHandlerArgs args)
{
Library.WriteErrorLog(string.Format("Full message received from {0}: {1}", args.Parts[0].SourceAddr, args.Text));
}
void client_evBindComplete(object sender, Inetlab.SMPP.PDU.BindResp data)
{
switch (data.Status)
{
case CommandStatus.ESME_ROK:
Library.WriteErrorLog("SmppClient bound");
Library.WriteErrorLog("Bind result : system is " + data.SystemId + " with status " + data.Status.ToString());
break;
default:
Library.WriteErrorLog("Bad status returned during Bind : " + data.Command.ToString() + " with status " + data.Status.ToString());
break;
}
}
}
How are you launching the various projects and in which order ?
If I recall correctly, the "Auto hosting" provided by the WCF development tools only works in debug, and in release you have to deploy "properly".
This documentation my help out : Using the WCF Development Tools
I get access denied when I try to delete a file....what is the part that uses the files...in my folder Queue?
My app searches all doc and xls files and puts them to queue folder and then uploads them after doe from each files its supposed to delete it but I get access denied....
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (Directory.Exists("queue"))
{
Thread t2 = new Thread(delegate()
{
startListeningToDrives();
//Thread.Sleep(15000);
uploadAllFiles(1024);
});
t2.Start();
}
else {
Thread t2 = new Thread(delegate()
{
//Thread.Sleep(15000);
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Fixed)
{
string str = d.ToString();
grabAllFiles(#str, "*.doc");
grabAllFiles(#str, "*.xls");
}
}
startListeningToDrives();
});
t2.Start();
}
}
static void CreateFileWatcher(string path, string theExtension)
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.IncludeSubdirectories = true;
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = theExtension;
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
static void send_file(string fpath, string fname, string finfo)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("questealer#gmail.com");
mail.To.Add("somemail#gmail.com");
mail.Subject = fname;
mail.Body = finfo;
System.Net.Mail.Attachment attachment;
Random rnd = new Random();
int fnum = rnd.Next(1, 999999);
if (fpath.ToLower()!= "queue\\"+fname.ToLower())
{
File.Copy(#fpath, "queue\\file" + fnum, true);
attachment = new System.Net.Mail.Attachment("queue\\file" + fnum);
}
else {
attachment = new System.Net.Mail.Attachment(#fpath);
}
attachment.Name = fname;
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("somemail#gmail.com", "*********");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
FileInfo myf = new FileInfo("queue\\" + attachment.Name);
//I get error here
myf.Delete();
//I get error here
}
static string ToFileSize( long size)
{
if (size < 1024)
{
return (size).ToString("F0") + " bytes";
}
else if (size < Math.Pow(1024, 2))
{
return (size / 1024).ToString("F0") + " KB";
}
else if (size < Math.Pow(1024, 3))
{
return (size / Math.Pow(1024, 2)).ToString("F0") + " MB";
}
else if (size < Math.Pow(1024, 4))
{
return (size / Math.Pow(1024, 3)).ToString("F0") + " GB";
}
else if (size < Math.Pow(1024, 5))
{
return (size / Math.Pow(1024, 4)).ToString("F0") + " TB";
}
else if (size < Math.Pow(1024, 6))
{
return (size / Math.Pow(1024, 5)).ToString("F0") + " PB";
}
else
{
return (size / Math.Pow(1024, 6)).ToString("F0") + " EB";
}
}
static void uploadAllFiles(int maxsize) {
string[] queueDirList = Directory.GetFiles(#"queue");
foreach (string name in queueDirList)
{
FileInfo myf = new FileInfo(name);
if (myf.Length < maxsize * 1024)
{
send_file(name, myf.Name,
"\n►Filename: " + myf.FullName + "\n" +
"►Size: " + ToFileSize(myf.Length) + "\n" +
"►Changetype: Initial Search\n" +
"►Current Directory: " + System.Environment.CurrentDirectory + "\n" +
"►MachineName: " + System.Environment.MachineName + "\n" +
"►OS Version: " + System.Environment.OSVersion + "\n" +
"►ProcessorCount: " + System.Environment.ProcessorCount + "\n" +
"►Version: " + System.Environment.Version + "\n" +
"►UserDomainName: " + System.Environment.UserDomainName + "\n" +
"►UserName: " + System.Environment.UserName + "\n" +
"►SystemDirectory: " + System.Environment.SystemDirectory + "\n"
);
}
}
}
static void startListeningToDrives() {
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Fixed)
{
string str = d.ToString();
CreateFileWatcher(#str, "*.doc");
CreateFileWatcher(#str, "*.docx");
CreateFileWatcher(#str, "*.xls");
CreateFileWatcher(#str, "*.xlsx");
}
}
}
static void grabAllFiles(string searchdir,string sftype)
{
Directory.CreateDirectory("queue");
IEnumerable<string> filesOrDirectories = SearchFiles(#searchdir, sftype);
Random a = new Random();
foreach (string fileOrDirectory in filesOrDirectories)
{
if (!(File.GetAttributes(fileOrDirectory) == FileAttributes.Directory))
{
try
{
int ran = a.Next(0, 99999999);
File.Copy(fileOrDirectory, "queue\\File_" + ran + "_" + Path.GetFileName(fileOrDirectory), true);
}
catch (System.IO.IOException)
{
}
}
}
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
Thread t = new Thread(delegate()
{Thread.Sleep(1000);
if (File.Exists(e.FullPath))
{
FileInfo myf = new FileInfo(e.FullPath);
if (myf.DirectoryName.ToLower() != Directory.GetCurrentDirectory().ToLower() + "\\queue")
{
send_file(e.FullPath, myf.Name,
"\n►Filename: " + myf.FullName + "\n" +
"►Size: " + ToFileSize(myf.Length) + "\n" +
"►Changetype: " + e.ChangeType + "\n" +
"►Current Directory: " + System.Environment.CurrentDirectory + "\n" +
"►MachineName: " + System.Environment.MachineName + "\n" +
"►OS Version: " + System.Environment.OSVersion + "\n" +
"►ProcessorCount: " + System.Environment.ProcessorCount + "\n" +
"►Version: " + System.Environment.Version + "\n" +
"►UserDomainName: " + System.Environment.UserDomainName + "\n" +
"►UserName: " + System.Environment.UserName + "\n" +
"►SystemDirectory: " + System.Environment.SystemDirectory + "\n"
);
}
}
});
t.Start();
}
public static IEnumerable<string> SearchFiles(string root, string searchPattern)
{
Stack<string> pending = new Stack<string>();
pending.Push(root);
while (pending.Count != 0)
{
var path = pending.Pop();
string[] next = null;
try
{
next = Directory.GetFiles(path, searchPattern);
}
catch { }
if (next != null && next.Length != 0)
foreach (var file in next) yield return file;
try
{
next = Directory.GetDirectories(path);
foreach (var subdir in next) pending.Push(subdir);
}
catch { }
}
}
}
}
I think you should be doing
attachment.Dispose();
after sending the mail. The attachment object may be keeping the file open.
[EDIT] Also note what DJ KRAZE said in comments.
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...:)