NullReferenceException WIA C# - c#

When I run the code below I get this error
NullreferenceException was unhandled..
below is my code
private void showScannerDialog()
{
this.scanner = null;
this.imageItem = null;
this.getScanner();
WIA.CommonDialog dialog = new WIA.CommonDialog();
Items imageItems = dialog.ShowSelectItems(this.scanner, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
if (imageItems != null)
{
foreach (Item item in imageItems)
{
imageItem = item;
break;
}
}
}
thanks
// complete code
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 System.IO;
using System.Collections;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string scannerName;
private Device scanner;
private Item imageItem;
private const int ADF = 1;
private const int FLATBED = 2;
private const int DEVICE_NAME_PROPERTY_ID = 7;
private const int DOCUMENT_HANDLING_PROPERTY_ID = 3088;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
showScannerDialog();
}
public static string[] GetScannerList()
{
ArrayList scannerList = new ArrayList();
DeviceManager deviceManager = new DeviceManager();
if (deviceManager.DeviceInfos.Count == 0)
{
return new string[0]; // return an empty string array
}
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = deviceInfo.Connect();
scannerList.Add(getDeviceProperty(device, DEVICE_NAME_PROPERTY_ID));
}
}
return (string[])scannerList.ToArray(typeof(string));
}
public int Init(string scannerName)
{
this.scannerName = scannerName;
this.showScannerDialog();
if (this.imageItem == null)
{
return 0;
}
else
{
return 1;
}
}
public int Scan(string filePath)
{
Tiff tiff = new Tiff(filePath);
bool adf = false;
int numScans = 0;
ArrayList tempFiles = new ArrayList();
// determine if the scanner is set to use an ADF
string docHandlingSelect = getDeviceProperty(this.scanner, DOCUMENT_HANDLING_PROPERTY_ID);
if (docHandlingSelect != "")
{
try
{
if ((int.Parse(docHandlingSelect) & ADF) == ADF)
{
adf = true;
}
}
catch { }
}
while (true)
{
string tempFile = Path.GetTempFileName();
tempFiles.Add(tempFile);
File.Delete(tempFile);
ImageFile wiaFile = (ImageFile)imageItem.Transfer(FormatID.wiaFormatTIFF);
wiaFile.SaveFile(tempFile);
Image tempImage = Image.FromFile(tempFile);
tiff.AddImage(tempImage);
tempImage.Dispose();
numScans++;
if (!adf)
{
DialogResult result =
MessageBox.Show("Do you wish to scan another page and save it to the same file?",
"Scanner Message", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
break;
}
this.showScannerDialog();
if (this.imageItem == null)
{
break;
}
}
}
tiff.Close();
foreach (string f in tempFiles.ToArray(typeof(string)))
{
File.Delete(f);
}
Marshal.ReleaseComObject(imageItem);
if (numScans == 0)
{
throw new Exception("Nothing was scanned.");
}
return 1;
}
private void getScanner()
{
DeviceManager deviceManager = new DeviceManager();
foreach (DeviceInfo deviceInfo in deviceManager.DeviceInfos)
{
if (deviceInfo.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = deviceInfo.Connect();
if (this.scannerName == getDeviceProperty(device, DEVICE_NAME_PROPERTY_ID))
{
this.scanner = device;
}
}
}
}
private void showScannerDialog()
{
this.scanner = null;
this.imageItem = null;
this.getScanner();
WIA.CommonDialog dialog = new WIA.CommonDialog();
Items imageItems = dialog.ShowSelectItems(this.scanner, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, false, true, false);
if (imageItems != null)
{
foreach (Item item in imageItems)
{
imageItem = item;
break;
}
}
}
private static string getDeviceProperty(Device device, int propteryID)
{
string retVal = "";
foreach (Property prop in device.Properties)
{
if (prop.PropertyID == propteryID)
{
retVal = prop.get_Value().ToString();
break;
}
}
return retVal;
}
}
}

this.scanner is set to null when you pass it to dialog.ShowSelectItems(). The function may be trying to use it without checking if it is null.

Related

Why when reporting progress with backgroundworker it's never get to the progresschanged event?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace Search_Text_In_Files
{
public partial class Form1 : Form
{
StreamWriter w = new StreamWriter(#"e:\textresults.txt");
ProgressBarWithText pbt = new ProgressBarWithText();
public Form1()
{
InitializeComponent();
pbt.Size = new Size(984, 23);
pbt.Location = new Point(12, 358);
this.Controls.Add(pbt);
backgroundWorker1.RunWorkerAsync();
}
bool result = false;
public List<string> FindLines(string DirName, string TextToSearch)
{
int counter = 0;
List<string> findLines = new List<string>();
DirectoryInfo di = new DirectoryInfo(DirName);
List<FileInfo> l = new List<FileInfo>();
CountFiles(di, l, count =>
{
backgroundWorker1.ReportProgress(count, "Counting Files");
});
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
countFiles++;
System.Threading.Thread.Sleep(1);
if (string.Compare(fi.Extension, ".cs", true) == 0)
{
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains(TextToSearch))
{
counter++;
findLines.Add(s);
result = true;
backgroundWorker1.ReportProgress(0, fi.FullName);
}
}
}
}
}
}
}
return findLines;
}
private void CountFiles(DirectoryInfo di, List<FileInfo> l, Action<int> CurrentCount) {
foreach (DirectoryInfo dir in di.GetDirectories())
CountFiles(dir, l, currentCount=> {
CurrentCount(l.Count);
});
}
private bool CheckForAccess(string PathName)
{
if (File.Exists(PathName) == true)
return CheckFileForAccess(PathName);
if (Directory.Exists(PathName) == true)
return CheckFolderForAccess(PathName);
return false;
}
private bool CheckFileForAccess(string FileName)
{
FileSecurity fs = new FileSecurity(FileName, AccessControlSections.Access);
if (fs == null)
return false;
AuthorizationRuleCollection TheseRules = fs.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckFolderForAccess(string FolderName)
{
DirectoryInfo di = new DirectoryInfo(FolderName);
if (di == null)
return false;
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.Access);
if (acl == null)
return false;
AuthorizationRuleCollection TheseRules = acl.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckACL(AuthorizationRuleCollection TheseRules)
{
foreach (FileSystemAccessRule ThisRule in TheseRules)
{
if ((ThisRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
{
if (ThisRule.AccessControlType == AccessControlType.Deny)
return false;
}
}
return true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(#"d:\c-sharp", "FileShellExtension");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Counting Files")
label2.Text = e.UserState.ToString();
pbt.Value = e.ProgressPercentage;
pbt.Text = e.ProgressPercentage.ToString() + "%";
pbt.Invalidate();
label2.Text = e.UserState.ToString();
if (result == true)
{
listView1.Items.Add(e.UserState.ToString());
result = false;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
}
else if (e.Error != null)
{
}
else
{
}
}
public class ProgressBarWithText : ProgressBar
{
const int WmPaint = 15;
SizeF TextSize;
PointF TextPos;
bool dontpaint = false;
public ProgressBarWithText()
{
this.DoubleBuffered = true;
this.TextChanged += ProgressBarWithText_TextChanged;
this.SizeChanged += ProgressBarWithText_SizeChanged;
}
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
void RecalcTextPos()
{
if (this.IsDisposed == true)
return;
if (string.IsNullOrEmpty(base.Text))
return;
using (var graphics = Graphics.FromHwnd(this.Handle))
{
TextSize = graphics.MeasureString(base.Text, this.Font);
TextPos.X = (this.Width / 2) - (TextSize.Width / 2);
TextPos.Y = (this.Height / 2) - (TextSize.Height / 2);
}
}
void ProgressBarWithText_SizeChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
void ProgressBarWithText_TextChanged(object sender, EventArgs e)
{
RecalcTextPos();
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (dontpaint == false)
{
switch (m.Msg)
{
case WmPaint:
using (var graphics = Graphics.FromHwnd(Handle))
graphics.DrawString(base.Text, base.Font, Brushes.Black, TextPos.X, TextPos.Y);
break;
}
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams result = base.CreateParams;
result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED
return result;
}
}
}
}
}
The method FindLines i call it form the dowork event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(#"d:\c-sharp", "FileShellExtension");
}
And in the FindLines method i'm using the reportprogress in two places:
CountFiles(di, l, count =>
{
backgroundWorker1.ReportProgress(count, "Counting Files");
});
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
But it's never get to the progresschanged event.
I checked in the designer the property: WorkerReportsProgress is set to true.

How to find items in a ListBox?

I am creating an application where I have a ListBox which has items that are read in from a text file using StreamReader. I have created a search form but I'm not sure what to do next. Can anyone give me some suggestions please? Here is my code:
My code for the ListBox (sorry it's so long)
public partial class frmSwitches : Form
{
public static ArrayList switches = new ArrayList();
public static frmSwitches frmkeepSwitches = null;
public static string inputDataFile = "LeckySafe.txt";
const int numSwitchItems = 6;
public frmSwitches()
{
InitializeComponent();
frmkeepSwitches = this;
}
private void btnDevices_Click(object sender, EventArgs e)
{
frmDevices tempDevices = new frmDevices();
tempDevices.Show();
frmkeepSwitches.Hide();
}
private bool fileOpenForReadOK(string readFile, ref StreamReader dataIn)
{
try
{
dataIn = new StreamReader(readFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when reading data in) - File could not be found.\n"
+ notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when reading data in) - Operation failed.\n"
+ e.Message);
return false;
}
}
private bool getNextSwitch(StreamReader inNext, string[] nextSwitchData)
{
string nextLine;
int numDataItems = nextSwitchData.Count();
for (int i = 0; i < numDataItems; i++)
{
try
{
nextLine = inNext.ReadLine();
if (nextLine != null)
nextSwitchData[i] = nextLine;
else
{
return false;
}
}
catch (Exception e)
{
MessageBox.Show("ERROR Reading from file.\n" + e.Message);
return false;
}
}
return true;
}
private void readSwitches()
{
StreamReader inSwitches = null;
Switch tempSwitch;
bool anyMoreSwitches = false;
string[] switchData = new string[numSwitchItems];
if (fileOpenForReadOK(inputDataFile, ref inSwitches))
{
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
while (anyMoreSwitches == true)
{
tempSwitch = new Switch(switchData[0], switchData[1], switchData[2], switchData[3], switchData[4], switchData[5]);
switches.Add(tempSwitch);
anyMoreSwitches = getNextSwitch(inSwitches, switchData);
}
}
if (inSwitches != null) inSwitches.Close();
}
public static bool fileOpenForWriteOK(string writeFile, ref StreamWriter dataOut)
{
try
{
dataOut = new StreamWriter(writeFile);
return true;
}
catch (FileNotFoundException notFound)
{
MessageBox.Show("ERROR Opening file (when writing data out)" +
"- File could not be found.\n" + notFound.Message);
return false;
}
catch (Exception e)
{
MessageBox.Show("ERROR Opening File (when writing data out)" +
"- Operation failed.\n" + e.Message);
return false;
}
}
public static void writeSwitches()
{
StreamWriter outputSwitches = null;
if (fileOpenForWriteOK(inputDataFile, ref outputSwitches))
{
foreach (Switch currSwitch in switches)
{
outputSwitches.WriteLine(currSwitch.getSerialNo());
outputSwitches.WriteLine(currSwitch.getType());
outputSwitches.WriteLine(currSwitch.getInsDate());
outputSwitches.WriteLine(currSwitch.getElecTest());
outputSwitches.WriteLine(currSwitch.getPatId());
outputSwitches.WriteLine(currSwitch.getNumDevice());
}
outputSwitches.Close();
}
if (outputSwitches != null) outputSwitches.Close();
}
private void showListOfSwitches()
{
lstSwitch.Items.Clear();
foreach (Switch b in switches)
lstSwitch.Items.Add(b.getSerialNo()
+ b.getType() + b.getInsDate()
+ b.getElecTest() + b.getPatId() + b.getNumDevice());
}
My code for the search form:
private void btnSearch_Click(object sender, EventArgs e)
{
frmSearchSwitch tempSearchSwitch = new frmSearchSwitch();
tempSearchSwitch.Show();
frmkeepSwitches.Hide();
}
If using a List<T> and lambda is not possible for you then go no farther.
Here I use a List<T> for the data source of a ListBox and mocked up data as where the data comes from is not important but here I am focusing on searching on a property within a class where a select is used to index the items then the where searches in this case) for a specific item, if found the index is used to move to the item. No code present for if not located as this is easy for you to do if the code here is something that is doable for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace ListBoxSearch_cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var results =
((List<Item>)ListBox1.DataSource)
.Select((data, index) => new
{ Text = data.SerialNumber, Index = index })
.Where((data) => data.Text == "BB1").FirstOrDefault();
if (results != null)
{
ListBox1.SelectedIndex = results.Index;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var items = new List<Item>() {
new Item {Identifier = 1, SerialNumber = "AA1", Type = "A1"},
new Item {Identifier = 2, SerialNumber = "BB1", Type = "A1"},
new Item {Identifier = 3, SerialNumber = "CD12", Type = "XD1"}
};
ListBox1.DisplayMember = "DisplayText";
ListBox1.DataSource = items;
}
}
/// <summary>
/// Should be in it's own class file
/// but done here to keep code together
/// </summary>
public class Item
{
public string SerialNumber { get; set; }
public string Type { get; set; }
public int Identifier { get; set; }
public string DisplayText
{
get
{
return SerialNumber + " " + this.Type;
}
}
}
}

Emulating console in winforms, the hard way how to make it better

Im trying to emulate the console in a windows forms applicaton. I have made it possible by using two extra threads and a delegate to be able to interact with my multiline textbox.
This somehow seems like I complicate things to much. So my questions.
Is there a better way of doing this?
When i press enter the command does not get sent, first if i press again it get sent? WHy is that? I ahve treid to debug it but failed to find the solution.
EDIT! Im using CsharpSSH, to do the SSH connection. Also I have included my full code now!
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 Tamir.SharpSsh;
using System.IO;
using System.Threading;
using System.Timers;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public string mHost;
SshShell mShell;
public string mInput;
string pattern = "";
bool mInputHolder = false;
string mPattern = "";
int mValue = 0;
bool mStatus = false;
private Thread thrdtwo = null;
private Thread thrdone = null;
public string mKorv;
string mString = "";
delegate void SetTextCallback(string text);
bool clientopen = true;
public Form1()
{
InitializeComponent();
txthost.Text = "sdf.org";
txtuser.Text = "kalle82";
txtpass.Text = "kattsand";
string pattern = "sdf:";
mPattern = pattern;
}
public void button1_Click(object sender, EventArgs e)
{
mShell = new SshShell(Host, User);
mShell.Password = Pass;
//WRITING USER MESSAGE
txtOutput.AppendText("Connecting...");
mShell.Connect();
txtOutput.AppendText("OK");
mShell.ExpectPattern = mPattern;
mShell.RemoveTerminalEmulationCharacters = true;
this.SetText(mShell.Expect(pattern));
txtInput.Focus();
thrdone = new Thread(new ThreadStart(appengine));
thrdone.Start();
}
private void appengine()
{
this.txtInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(checkforenter);
// MessageBox.Show("Appengine started");
while (mShell.ShellOpened)
{
thrdtwo = new Thread(new ThreadStart(startthread2));
thrdtwo.Start();
thrdtwo.Join();
// this.SetText(mShell.Expect(pattern));
if (clientopen == false) break;
}
// MessageBox.Show("Appengine stopped");
}
private void startthread2()
{
//Wait for answer
while (mStatus == false)
{
}
}
//Recieves keypressevent
public void checkforenter(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
mStatus = true;
mString = txtInput.Text;
mShell.WriteLine(mString);
this.SetText(mShell.Expect(pattern));
txtOutput.AppendText(txtInput.Text + "\n");
}
mStatus = false;
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtOutput.Text = text.ToString();
}
}
public int checkfortrue()
{
if (mInputHolder != true)
{
mValue = 0;
}
if (mInputHolder == false)
{
mValue = -1;
}
return mValue;
}
public string userInput()
{
while (mInputHolder == true)
{
}
mInputHolder = true;
return txtInput.Text;
}
//Properties
public string Host
{
get
{
return txthost.Text;
}
set
{
txthost.Text = value;
}
}
public string User
{
get
{
return txtuser.Text;
}
set
{
txtuser.Text = value;
}
}
public string Pass
{
get
{
return txtpass.Text;
}
set
{
txtpass.Text = value;
}
}
public string Pattern
{
get
{
return pattern;
}
set
{
pattern = value;
}
}
private void button2_Click(object sender, EventArgs e)
{
clientopen = false;
}
}
}

Saving to File in C#, visual studio 2010, errors

g'day guys,
i have a small error with my program where when i try to save to file an error occurs which says "A required privilege is not held by the client." I not sure how to fix this as i am running it off of my laptop which only i use and unless i have set up administrator status correctly i dont know what is going on.
I posted my code below just to be sure
Cheers.
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 System.IO;
using System.IO.Ports;
using System.Threading;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
delegate void addlistitemcallback(string value);
public static string inputdata;
public static int MaximumSpeed, maximumRiderInput, RiderInput, Time, CurrentSpeed, DistanceTravelled, MaximumMotorOutput, MotorOutput, InputSpeed;
public static string SaveDataString;
public Thread Serial;
public static SerialPort SerialData;
public static string[] portlist = SerialPort.GetPortNames();
public static string[] SaveData = new string[4];
public static string directory = "C:\\";
public Form1()
{
Serial = new Thread(ReadData);
InitializeComponent();
int Count = 0;
for (Count = 0; Count < portlist.Length; Count++)
{
ComPortCombo.Items.Add(portlist[Count]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void StartDataButton_Click(object sender, EventArgs e)
{
SerialData = new SerialPort(ComPortCombo.Text, 19200, Parity.None, 8, StopBits.One);
SerialData.Open();
SerialData.WriteLine("P");
Serial.Start();
StartDataButton.Enabled = false;
EndDataButton.Enabled = true;
ComPortCombo.Enabled = false;
CurrentSpeed = 0;
MaximumSpeed = 0;
Time = 0;
DistanceTravelled = 0;
MotorOutput = 0;
RiderInput = 0;
SaveData[0] = "";
SaveData[1] = "";
SaveData[2] = "";
SaveData[3] = "";
SaveDataButton.Enabled = false;
if (SerialData.IsOpen)
{
ComPortStatusLabel.Text = "OPEN";
SerialData.NewLine = "/n";
SerialData.WriteLine("0");
SerialData.WriteLine("/n");
}
}
private void EndDataButton_Click(object sender, EventArgs e)
{
SerialData.Close();
SaveDataButton.Enabled = true;
//SerialData.WriteLine("1");
//SerialData.WriteLine("0");
if (!SerialData.IsOpen)
{
ComPortStatusLabel.Text = "CLOSED";
}
int i = 0;
for (i = 0; i < 4; i++)
{
if (i == 0)
{
SaveDataString = "MaximumSpeed during the Ride was = " + Convert.ToString(MaximumSpeed) + "m/h";
SaveData[i] = SaveDataString;
}
if (i == 1)
{
SaveDataString = "Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "m";
SaveData[i] = SaveDataString;
}
if (i == 2)
{
SaveDataString = "Maximum Rider Input Power = " + Convert.ToString(maximumRiderInput) + "Watts";
SaveData[i] = SaveDataString;
}
if (i == 3)
{
SaveDataString = "Maximum Motor Output Power = " + Convert.ToString(MaximumMotorOutput) + "Watts";
SaveData[i] = SaveDataString;
}
}
}
private void SaveDataButton_Click(object sender, EventArgs e)
{
//File.WriteAllBytes(directory + "image" + imageNO + ".txt", ); //saves the file to Disk
File.WriteAllLines("C:\\" + "BikeData.txt", SaveData);
}
public void updateSpeedtextbox(string value)
{
if (SpeedTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateSpeedtextbox);
Invoke(d, new object[] { value });
}
else
{
SpeedTextBox.Text = value;
}
}
public void updatePowertextbox(string value)
{
if (RiderInputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updatePowertextbox);
Invoke(d, new object[] { value });
}
else
{
RiderInputTextBox.Text = value;
}
}
public void updateDistancetextbox(string value)
{
if (DistanceTravelledTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateDistancetextbox);
Invoke(d, new object[] { value });
}
else
{
DistanceTravelledTextBox.Text = value;
}
}
public void updateMotortextbox(string value)
{
if (MotorOutputTextBox.InvokeRequired)
{
addlistitemcallback d = new addlistitemcallback(updateMotortextbox);
Invoke(d, new object[] { value });
}
else
{
MotorOutputTextBox.Text = value;
}
}
public void ReadData()
{
int counter = 0;
while (SerialData.IsOpen)
{
if (counter == 0)
{
try
{
InputSpeed = Convert.ToInt16(SerialData.ReadChar());
if (CurrentSpeed > MaximumSpeed)
{
MaximumSpeed = CurrentSpeed;
}
updateSpeedtextbox("Current Wheel Speed = " + Convert.ToString(InputSpeed) + "Km/h");
DistanceTravelled = DistanceTravelled + (Convert.ToInt16(InputSpeed) * Time);
updateDistancetextbox("Total Distance Travelled = " + Convert.ToString(DistanceTravelled) + "Km");
}
catch (Exception) { }
}
if (counter == 1)
{
try
{
RiderInput = Convert.ToInt16(SerialData.ReadChar());
if (RiderInput > maximumRiderInput)
{
maximumRiderInput = RiderInput;
}
updatePowertextbox("Current Rider Input Power =" + Convert.ToString(RiderInput) + "Watts");
}
catch (Exception) { }
}
if (counter == 2)
{
try
{
MotorOutput = Convert.ToInt16(SerialData.ReadChar());
if (MotorOutput > MaximumMotorOutput)
{
MaximumMotorOutput = MotorOutput;
}
updateMotortextbox("Current Motor Output = " + Convert.ToString(MotorOutput) + "Watts");
}
catch (Exception) { }
}
counter++;
if (counter == 3)
{
counter = 0;
}
}
}
private void Form1_Closed(object sender, EventArgs e)
{
if (SerialData.IsOpen)
{
SerialData.Close();
}
}
private void ComPortCombo_SelectedIndexChanged(object sender, EventArgs e)
{
StartDataButton.Enabled = true;
}
private void DistanceTravelledTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
You probably don't have write access to C:\. Try changing the save path to "C:\Users\{YouName}\Documents\BikeData.txt" instead.
Or start Visual Studio with administrative privileges by right clicking on its icon and choosing "Run as Administrator"
File.WriteAllLines("C:\" + "BikeData.txt", SaveData);
File.WriteAllLine(string,string[]), through "SecurityException" when user does not have rights to write in a particular directrory or drive so you have to give write permission, refer this link File.WriteAllLines

Symbol.WPAN.Bluetooth example that transfers data

I am trying to use Symbol.WPAN.Bluetooth that comes with the EMDK for Symbol devices.
Does anyone happen to have a working example that transfers data?
Symbol's example just pairs the devices. (They apparently think that transfering data is not really needed in a Personal Area network example.)
Anyway, I know this is a long shot, but if anyone has gotten this to work I would love to see some code.
This is what I have tried. I have one device press button1 and another device press button2. The read value is always a zero length byte array.
using System.Text;
using System.Windows.Forms;
using Symbol.WPAN;
using Symbol.WPAN.Bluetooth;
namespace SmartDeviceProject1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Bluetooth bluetooth = new Bluetooth();
if (bluetooth.IsEnabled != true)
{
bluetooth.Enable();
bluetooth.RadioMode = BTH_RADIO_MODE.BTH_DISCOVERABLE_AND_CONNECTABLE;
}
RemoteDevice connectedDevice = null;
foreach (RemoteDevice remoteDevice in MakeEnumerable(bluetooth.RemoteDevices))
{
if ((remoteDevice.Name == "WM_Dan") && (remoteDevice.IsPaired == false))
{
remoteDevice.Pair();
connectedDevice = remoteDevice;
}
}
string test;
test = "Testing this out";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] encTest = encoding.GetBytes(test);
if (connectedDevice != null)
{
connectedDevice.WriteTimeout = 20000;
connectedDevice.Write(encTest);
}
}
public static IEnumerable<RemoteDevice> MakeEnumerable(RemoteDevices devices)
{
for (var i = 0; i < devices.Length; i++)
{
yield return devices[i];
}
}
private void button2_Click(object sender, EventArgs e)
{
Bluetooth bluetooth = new Bluetooth();
if (bluetooth.IsEnabled != true)
{
bluetooth.Enable();
bluetooth.RadioMode = BTH_RADIO_MODE.BTH_DISCOVERABLE_AND_CONNECTABLE;
}
RemoteDevice connectedDevice = null;
foreach (RemoteDevice remoteDevice in MakeEnumerable(bluetooth.RemoteDevices))
{
if ((remoteDevice.Name == "WM_Dan2") && (remoteDevice.IsPaired == false))
{
remoteDevice.Pair();
connectedDevice = remoteDevice;
}
}
string test;
test = "Testing this out";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] encTest = encoding.GetBytes(test);
byte[] encTest2;
string test2;
if (connectedDevice != null)
{
connectedDevice.ReadTimeout = 20000;
encTest2 = connectedDevice.Read(encTest.Length);
test2 = encoding.GetString(encTest2, 0, encTest2.Length);
MessageBox.Show(test2);
}
}
}
}
I gave up on using the built in com port connection and opened a SerialPort object on the connection.
SerialPort sp = new SerialPort();
sp.PortName = "COM" + connectedDevice.LocalComPort.ToString();
sp.BaudRate = 9600;
sp.DataBits = 8;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.Open();
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.ErrorReceived += new SerialErrorReceivedEventHandler(sp_ErrorReceived);
sp.WriteLine(textBoxSend.Text);
I also found that even though their docs said that LocalComPort was auto assigned, this was not always the truth. It was best to use their BTExplorer to set it first.
As well, there OpenComPort would work in situations where is should not -- using Reflector it is pretty obviously wrong. There are checking the return of ::CreateFile("COM" + port...) against 0 instead of -1 (INVALID_HANDLE_VALUE)
I don't know if this can ever help anyone, but here is an old piece of code that I wrote a few years back.
You'll have to clean it up so that it works for your application. My app had a TextBox control that it read from and logged errors to a Global class. Change that to work with what you have, and it should basically be good.
static class Scanner {
const string _CODEFILE = "Scanner.cs - Scanner::";
static int _baud = 9600;
static int _bits = 8;
static string _dataIn = null;
static string _port = "COM1";
static Parity _parity = Parity.None;
static StopBits _stop = StopBits.One;
static SerialPort _com1 = null;
static TextBox _textbox = null;
public enum ControlType { None, BadgeID, PartNumber, SerialNumber, WorkOrder };
static ControlType _control;
public static bool Available { get { return ((_com1 != null) && (_com1.IsOpen)); } }
public static bool Close {
get {
if (_com1 == null) return true;
try {
if (_com1.IsOpen) {
_com1.Close();
}
return (!_com1.IsOpen);
} catch { }
return false;
}
}
public static string Open() {
const string na = "Not Available";
if (_com1 == null) {
string reset = Reset();
if (!String.IsNullOrEmpty(reset)) return reset;
}
try {
_com1.Open();
return (_com1.IsOpen) ? null : na;
} catch (Exception err) {
return err.Message;
}
}
static void ProcessData(string incoming) {
_dataIn += incoming;
if ((_control != ControlType.None) && (_textbox != null)) {
bool ok = false;
string testData = _dataIn.Trim();
switch (_control) {
case ControlType.BadgeID:
if (testData.Length == 6) {
if (testData != BarCode.LOGOFF) {
Regex pattern = new Regex(#"[0-9]{6}");
ok = (pattern.Matches(testData).Count == 1);
} else {
ok = true;
}
}
break;
case ControlType.PartNumber:
if (testData.Length == 7) {
Regex pattern = new Regex(#"[BCX][P057][0-9]{5}");
ok = (pattern.Matches(testData).Count == 1);
}
break;
case ControlType.SerialNumber:
if (testData.Length == 15) {
Regex pattern = new Regex(#"[BCX][P057][0-9]{5} [0-9]{4} [0-9]{2}");
ok = (pattern.Matches(testData).Count == 1);
}
break;
case ControlType.WorkOrder:
if (testData.Length == 6) {
Regex pattern = new Regex(#"[0-9]{6}");
ok = (pattern.Matches(testData).Count == 1);
}
break;
}
if (ok) {
_textbox.Text = testData;
_textbox.ScrollToCaret();
_dataIn = null;
}
}
}
static string Reset() {
if (_com1 != null) {
try {
if (_com1.IsOpen) {
_com1.DiscardInBuffer();
_com1.Close();
}
} catch (Exception err) {
return err.Message;
}
Global.Dispose(_com1);
_com1 = null;
}
try {
_com1 = new SerialPort(_port, _baud, _parity, _bits, _stop);
_com1.DataReceived += new SerialDataReceivedEventHandler(Serial_DataReceived);
_com1.Open();
} catch (Exception err) {
return err.Message;
}
return null;
}
public static void ScanSource(ref TextBox objTextBox, ControlType objType) {
_textbox = objTextBox;
_control = objType;
_dataIn = null;
}
static void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e) {
ProcessData(_com1.ReadExisting());
}
public static void Settings(string ComPort, int BaudRate, Parity ParityValue, int Bits, StopBits StopBit) {
_port = ComPort;
_baud = BaudRate;
_parity = ParityValue;
_bits = Bits;
_stop = StopBit;
}
/// <summary>
/// Closes the COM Port
/// COM Port routines are ready to add as soon as I am
/// </summary>
static bool ComPortClose {
get {
if (_com1 == null) ComPortReset();
return ((_com1 == null) ? true : _com1.IsOpen ? false : true);
}
set {
if (_com1 == null) ComPortReset();
else if (_com1.IsOpen) {
_com1.DiscardInBuffer();
_com1.Close();
}
}
}
/// <summary>
/// Opens the COM Port
/// </summary>
static bool ComPortOpen {
get {
if (_com1 == null) ComPortReset();
return (_com1 == null) ? false : _com1.IsOpen;
}
set {
if (_com1 == null) ComPortReset();
if ((_com1 != null) && (!_com1.IsOpen)) _com1.Open();
}
}
/// <summary>
/// Initialized the Serial Port on COM1
/// </summary>
static void ComPortReset() {
if ((_com1 != null) && (_com1.IsOpen)) {
_com1.Close();
_com1 = null;
}
try {
_com1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
} catch (IOException err) {
Global.LogError(_CODEFILE + "ComPortReset", err);
}
}
}

Categories