I have a question that I cant come up with a solution for. Its About my application on a motorola MC3190-G Handheld Application on wm 6.5 and Compact Framework 2.0
After implementation of the Symbol Package for using the scanner trigger inside my application, I get the following error everytime I close my application / or a form which has the scanner enabled:
(Even if I never received data from scanning)
I searched for a solution on stackoverflow and other sites with no solutions to fix it.
I am new to mobile application development. I try and catched everything but the error seem to can't be catched with exceptiontype "exception".
sorry for the poor english.
Error:
NullReferenceException
at MainForm.SymbolReader_ReadNotifiy() at Task.Invoke()
at System.Windows.Forms.Control._InvokeAll() at
System.Windows.Forms.Control.WinProc()
Informations:
Motorola EMDK 2.6
Device: MC3190-G
Sourcecode:
Scanner.cs
namespace MyScann
{
/// <summary>
/// Summary description for Scanner.
/// </summary>
public class Scanner
{
public static Symbol.Barcode.Reader SymbolReader = null;
public static Symbol.Barcode.ReaderData SymbolReaderData = null;
public static System.EventHandler SymbolEventHandler = null;
public static DataSet CodeDataSet;
//public static Utils.Sound ReadErrorSound;
public static bool ScannerEnabled = false;
public static void ActivateScanner()
{
// If we have both a reader and a reader-data Object
if ( Scanner.SymbolReader != null &&
Scanner.SymbolReaderData != null &&
! Scanner.SymbolReaderData.IsPending )
{
// Submit 'Read'
try
{
Scanner.SymbolReader.Actions.Read(Scanner.SymbolReaderData);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
if ( err.InnerException != null )
MessageBox.Show(err.InnerException.Message);
}
}
}
public static void DeactivateScanner()
{
// If we have both a reader and a reader-data Object
if ( Scanner.SymbolReader != null &&
Scanner.SymbolReaderData != null &&
Scanner.SymbolReaderData.IsPending )
{
// Submit 'CancelRead'
try
{
Scanner.SymbolReader.Actions.CancelRead(Scanner.SymbolReaderData);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
if ( err.InnerException != null )
MessageBox.Show(err.InnerException.Message);
}
}
}
/// <summary>
/// Initialize the reader.
/// </summary>
/// <returns>False if an error accurs</returns>
public static bool InitSymbolReader()
{
// If reader is already present then fail initialize
if ( SymbolReader != null )
{
return false;
}
// Create new reader, first available reader will be used.
SymbolReader = new Symbol.Barcode.Reader();
// Create reader data
SymbolReaderData = new Symbol.Barcode.ReaderData(
Symbol.Barcode.ReaderDataTypes.Text,
Symbol.Barcode.ReaderDataLengths.DefaultText);
// set scanner read error sound
//ReadErrorSound = new Utils.Sound(ErrorSound);
return true;
}
/// <summary>
/// Stop reading and disable/close reader
/// </summary>
public static void DeinitSymbolReader()
{
try
{
// If we have a reader
if ( SymbolReader != null )
{
//Cancel Incoming Requests
SymbolReader.Actions.Flush();
// Disable the reader
SymbolReader.Actions.Disable();
// Free it up
SymbolReader.Dispose();
// Indicate we no longer have one
SymbolReader = null;
}
// If we have a reader data
if ( SymbolReaderData != null )
{
// Free it up
SymbolReaderData.Dispose();
// Indicate we no longer have one
SymbolReaderData = null;
}
if(SymbolEventHandler!=null){
//SymbolEventHandler(this,null);
SymbolEventHandler = null;
}
}
catch (Exception e){MessageBox.Show(e.StackTrace.ToString());
}
}
/// <summary>
/// Enable most barcode type with no limitation on length
/// </summary>
public static void OpenAllBarcodes()
{
SymbolReader.Decoders.CODABAR.Enabled = true;
SymbolReader.Decoders.CODABAR.MinimumLength = 0;
SymbolReader.Decoders.CODABAR.MaximumLength = 0;
SymbolReader.Decoders.CODE11.Enabled = true;
SymbolReader.Decoders.CODE11.MinimumLength = 0;
SymbolReader.Decoders.CODE11.MaximumLength = 0;
SymbolReader.Decoders.CODE39.Enabled = true;
SymbolReader.Decoders.CODE39.MinimumLength = 0;
SymbolReader.Decoders.CODE39.MaximumLength = 0;
SymbolReader.Decoders.CODE93.Enabled = true;
SymbolReader.Decoders.CODE93.MinimumLength = 0;
SymbolReader.Decoders.CODE93.MaximumLength = 0;
SymbolReader.Decoders.CODE128.Enabled = true;
SymbolReader.Decoders.CODE128.MinimumLength = 0;
SymbolReader.Decoders.CODE128.MaximumLength = 0;
SymbolReader.Decoders.DATAMATRIX.Enabled = true;
SymbolReader.Decoders.DATAMATRIX.MinimumLength = 0;
SymbolReader.Decoders.DATAMATRIX.MaximumLength = 0;
SymbolReader.Decoders.D2OF5.Enabled = true;
SymbolReader.Decoders.D2OF5.MinimumLength = 0;
SymbolReader.Decoders.D2OF5.MaximumLength = 0;
SymbolReader.Decoders.I2OF5.Enabled = true;
SymbolReader.Decoders.I2OF5.MinimumLength = 0;
SymbolReader.Decoders.I2OF5.MaximumLength = 0;
/*
SymbolReader.Decoders.EAN13.Enabled = true;
SymbolReader.Decoders.EAN13.MinimumLength = 0;
SymbolReader.Decoders.EAN13.MaximumLength = 0;
SymbolReader.Decoders.EAN8.Enabled = true;
SymbolReader.Decoders.EAN8.MinimumLength = 0;
SymbolReader.Decoders.EAN8.MaximumLength = 0;
SymbolReader.Decoders.PDF417.Enabled = true;
SymbolReader.Decoders.PDF417.MinimumLength = 0;
SymbolReader.Decoders.PDF417.MaximumLength = 0;
SymbolReader.Decoders.UPCA.Enabled = true;
SymbolReader.Decoders.UPCA.MinimumLength = 0;
SymbolReader.Decoders.UPCA.MaximumLength = 0;
SymbolReader.Decoders.UPCE1.Enabled = true;
SymbolReader.Decoders.UPCE1.MinimumLength = 0;
SymbolReader.Decoders.UPCE1.MaximumLength =0;
SymbolReader.Decoders.UPCE0.Enabled = true;
SymbolReader.Decoders.UPCE0.MinimumLength = 0;
SymbolReader.Decoders.UPCE0.MaximumLength = 0;
*/
SymbolReader.Parameters.CodeIdType = Symbol.Barcode.CodeIdTypes.None;
SymbolReader.Parameters.ScanType = Symbol.Barcode.ScanTypes.Background;
SymbolReader.Parameters.LocalFeedback = Symbol.Barcode.DisabledEnabled.Enabled;
Scanner.SymbolReader.Parameters.Feedback.Success.BeepTime = 0;
}
}
}
}
Inside MainForm.cs
public void InitScanner(byte BatteryLevel)
{
// Create event handler delegate
if (Scanner.MyScann.Scanner.SymbolEventHandler == null)
{
Scanner.MyScann.Scanner.SymbolEventHandler = new EventHandler(this.SymbolReader_ReadNotify);
// Enable reader, with wait cursor
Scanner.MyScann.Scanner.SymbolReader.Actions.Enable();
Scanner.MyScann.Scanner.OpenAllBarcodes();
Scanner.MyScann.Scanner.ScannerEnabled = true;
}
// If we have both a reader and a reader data
if ((Scanner.MyScann.Scanner.SymbolReader != null) &&
(Scanner.MyScann.Scanner.SymbolReaderData != null))
{
// Submit a read
Scanner.MyScann.Scanner.SymbolReader.ReadNotify += Scanner.MyScann.Scanner.SymbolEventHandler;
Scanner.MyScann.Scanner.SymbolReader.Actions.Read(Scanner.MyScann.Scanner.SymbolReaderData);
}
}
public void SymbolReader_ReadNotify(object sender, EventArgs e)
{
Symbol.Barcode.ReaderData TheReaderData = Scanner.MyScann.Scanner.SymbolReader.GetNextReaderData();
if (TheReaderData.Result == Symbol.Results.SUCCESS /*&& (txtBarcode.Focused == true)*/)
{
// if (txtBarcode.Focused == true)
// {
// txtBarcode.Text = TheReaderData.Text.ToString();
MessageBox.Show(TheReaderData.Text.ToString());
SymbolReader_CycleScannerReader();
return;
// }
}
SymbolReader_CycleScannerReader();
}
public void SymbolReader_CycleScannerReader()
{
Scanner.MyScann.Scanner.SymbolReader.Actions.Read(Scanner.MyScann.Scanner.SymbolReaderData);
}
public void StartScanner()
{
bool flag = false;
try
{
Scanner.MyScann.Scanner.SymbolEventHandler = null;
Scanner.MyScann.Scanner.DeinitSymbolReader();
Scanner.MyScann.Scanner.ScannerEnabled = false;
if (!Scanner.MyScann.Scanner.ScannerEnabled)
{
Scanner.MyScann.Scanner.SymbolEventHandler = null;
Scanner.MyScann.Scanner.InitSymbolReader();
InitScanner(100);
flag = true;
}
}
catch
{
Scanner.MyScann.Scanner.SymbolEventHandler = null;
Scanner.MyScann.Scanner.InitSymbolReader();
InitScanner(100);
flag = true;
}
finally
{
if (!flag)
{
MessageBox.Show("Scanner Error");
}
}
}
void public void CloseScanner()
{
Scanner.MyScann.Scanner.SymbolEventHandler = null;
Scanner.MyScann.Scanner.DeinitSymbolReader();
}
void MainFormLoad(object sender, EventArgs e)
{
StartScanner();
}
void MainFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
CloseScanner();
}
void ButtonExitClick(object sender, EventArgs e)
{
Scanner.MyScann.Scanner.DeinitSymbolReader();
this.Close();
Application.Exit();
}
Any help would be appreciated!
I'm not familiar with the symbol library, but from what i can see the problem is the ReadNotify event being raised at some point after the "deinitialization" of the scanner.
What you should do in the MainForm.CloseScanner() void is to first remove ALL handles added in the MainForm.InitScanner() and then call Scanner.DeinitSymbolReader().
Edit:
You should remove the handle with the -= operator, not assigning null reference.
Hope this helps.
try not calling 'DeinitSymbolReader' on exit, and see if that fixes it
Pete
My impression is that your application doesn't exit correctly with or without 'deinitSymbolReader'. It is possible that by calling deinitSymbolReader on a resource that has already been closed you are causing an access violation.
Maybe you should try giving up deinintSymbolReader, and try to also Dispose the scanner/trigger in the Form's Disposing Event.
What seems to be the problem is that you are Disposing of complex data structures, and right that you're changing them to null which basically means you're changing the reference and probably ensuring the GC will never get to free all the un-managed resources.
One indication that you are dealing with the improper manipulation of an un-managed resource is the fact that the second deinintSymbolReader shouldn't do anything (since all your resources are null) much less cause an error.
I have an application that uses triggers and scanner and it only needs an "enableScanner = false" and an "Scanner.Dispose()" if the scanner is not null.
Related
I need to stream my OS mixer sound to the microphone. (to transfer them both via skype).
Important thing is -- I need to have ability to configure delay/latency of the stream.
(VAC) Virtual Audio Cable is not solution for me: it doesn't work in my case. I have an external USB sound device an app doesn't work for me. I have tried it. Truly.
I google it more than 2 days and found nothing.
So I want to try wrote my own app for this. Have no experience with NAudio.
At the moment all I have is:
using System;
using System.Collections.Generic;
using NAudio.Wave;
namespace SoundApp
{
public class AudioCable
{
private WaveOut _wvOut = null;
private DirectSoundOut _output = null;
private WaveIn _sourceStreamIn = null;
private WaveOut _sourceStreamOut = null;
public void InitDevices(string fromDevice, string toDevice)
{
Dispose();
_sourceStreamIn = new WaveIn();
_sourceStreamOut = new WaveOut();
_output = new DirectSoundOut();
if (fromDevice.Contains("INPUT"))
{
var tmp = fromDevice.Split('|')[0].Replace("INPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
_sourceStreamIn.DeviceNumber = tmpDeviceNumber;
}
else
{
var tmp = toDevice.Split('|')[0].Replace("OUTPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
_sourceStreamOut.DeviceNumber = tmpDeviceNumber;
}
Guid deviceGuid;
if (toDevice.Contains("INPUT"))
{
var tmp = toDevice.Split('|')[0].Replace("INPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(tmpDeviceNumber);
deviceGuid = deviceInfo.ManufacturerGuid;
}
else
{
var tmp = toDevice.Split('|')[0].Replace("OUTPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
WaveOutCapabilities deviceInfo = WaveOut.GetCapabilities(tmpDeviceNumber);
deviceGuid = deviceInfo.ManufacturerGuid;
}
_output = new DirectSoundOut(deviceGuid);
}
public void PlaySound()
{
WaveInProvider waveIn = null;
if (_sourceStreamIn != null)
{
waveIn = new WaveInProvider(_sourceStreamIn);
}
else if (_sourceStreamOut != null)
{
throw new Exception("Sorry, not supported right now");
//waveIn = new WaveInProvider(_sourceStreamOut);
}
_output.Init(waveIn);
_output.Play();
}
public void Dispose()
{
_sourceStreamIn = null;
_sourceStreamOut = null;
if (_output != null)
{
if (_output.PlaybackState == PlaybackState.Playing)
{
_output.Stop();
}
_output.Dispose();
_output = null;
}
}
public string[] GetAudioDevices()
{
var devices = new List<string>();
for (int i = 0; i < WaveIn.DeviceCount; i++)
{
WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(i);
devices.Add($"INPUT: {i} | {deviceInfo.ProductName}");
}
for (int i = 0; i < WaveOut.DeviceCount; i++)
{
WaveOutCapabilities deviceInfo = WaveOut.GetCapabilities(i);
devices.Add($"OUTPUT: {i} | {deviceInfo.ProductName}");
}
return devices.ToArray();
}
}
}
And the form source:
namespace SoundApp
{
public partial class Form1 : Form
{
AudioCable _ac = new AudioCable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cBoxSource.DropDownStyle = ComboBoxStyle.DropDownList;
cBoxTarget.DropDownStyle = ComboBoxStyle.DropDownList;
cBoxSource.Items.AddRange(_ac.GetAudioDevices());
cBoxTarget.Items.AddRange(_ac.GetAudioDevices());
}
private void btnStartStop_Click(object sender, EventArgs e)
{
_ac.InitDevices(cBoxSource.SelectedItem.ToString(), cBoxTarget.SelectedItem.ToString());
_ac.PlaySound();
}
}
}
So at the first I'm trying to stream microphone to the sound output device.... And it does not work at all.
So My questions is:
There are no microphone sound and I'm do not understand why so. Code is valid and dont throw any errors.
Looks like there is no ability to stream outputDevice sound stream to the inputDevice with NAudio. Is there exist some hack for this?
I am using Kinect SDK 2.0 and I want to track just one skeleton.
How do I achieve this?
I already tried the FindClosestSkeleton method in HD Face Basics sample, but that stopped my program from updating every frame, and I didn't entirely understand it.
Can someone kindly explain and show me how to do this?
The following code is based on the BodyBasics-WPF sample.
public class KinectManager
{
// Active Kinect sensor
private KinectSensor kinectSensor = null;
// Reader for body frames
private BodyFrameReader bodyFrameReader = null;
// Array for the bodies
private Body[] bodies = null;
// index for the currently tracked body
private int bodyIndex;
// flag to asses if a body is currently tracked
private bool bodyTracked = false;
public KinectManager()
{
this.kinectSensor = KinectSensor.GetDefault();
// open the reader for the body frames
this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();
// open the sensor
this.kinectSensor.Open();
this.bodyFrameReader.FrameArrived += this.Reader_FrameArrived;
}
// Handles the body frame data arriving from the sensor
private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (this.bodies == null)
{
this.bodies = new Body[bodyFrame.BodyCount];
}
bodyFrame.GetAndRefreshBodyData(this.bodies);
dataReceived = true;
}
}
if (dataReceived)
{
Body body = null;
if(this.bodyTracked) {
if(this.bodies[this.bodyIndex].IsTracked) {
body = this.bodies[this.bodyIndex];
} else {
bodyTracked = false;
}
}
if(!bodyTracked) {
for (int i=0; i<this.bodies.Length; ++i)
{
if(this.bodies[i].IsTracked) {
this.bodyIndex = i;
this.bodyTracked = true;
break;
}
}
}
if (body != null && this.bodyTracked && body.IsTracked)
{
// body represents your single tracked skeleton
}
}
}
}
I need to download a file and use it to connect to a server. If the connection fails, it restarts the loop. Somehow the while loop keeps running and downloading the file constantly. I think that something weird happens with the boolean Globals.sockRetry but I can't find what's really happening.
public class Globals
{
public static string serverIp;
public static int serverPort;
public static int sockConn = 0;
public static bool sockRetry = false;
public static TcpClient client;
public static NetworkStream nwStream;
public static StreamReader reader;
public static StreamWriter writer;
}
static void connect(Globals g)
{
Globals.sockConn = 1;
try
{
Globals.client = new TcpClient(Globals.serverIp, Globals.serverPort);
Globals.nwStream = Globals.client.GetStream();
Globals.reader = new StreamReader(Globals.nwStream);
Globals.writer = new StreamWriter(Globals.nwStream);
Globals.sockConn = 2;
string inputLine;
while ((inputLine = Globals.reader.ReadLine()) != null)
{
// ParseMessage(Globals.writer, inputLine, g);
}
}
catch
{
Globals.sockRetry = true;
Globals.sockConn = 0;
return;
}
}
static void getInfo()
{
while (true)
{
try
{
WebRequest request = WebRequest.Create(INFO_HOST + INFO_PATH);
WebResponse response = request.GetResponse();
string content;
using (var sr = new StreamReader(response.GetResponseStream()))
{
content = sr.ReadToEnd();
}
string[] contentArray = content.Split(':');
string serverIp = contentArray[0];
string serverPortStr = contentArray[1];
int serverPort = 5000;
Int32.TryParse(serverPortStr, out serverPort);
Globals g = new Globals();
Globals.serverIp = serverIp;
Globals.serverPort = serverPort;
while (Globals.sockConn == 0)
{
if (Globals.sockRetry == false)
{
connect(g);
}
else
{
// error connecting
// wait and retry
Globals.sockRetry = false;
Thread.Sleep(60000);
break;
}
}
continue;
}
catch
{
// error downloading file
// wait and retry
Thread.Sleep(60000);
continue;
}
}
}
The only place there you terminate the loop is here:
if (Globals.sockRetry == false)
{
connect(g);
}
else
{
...
break;
}
So it happens only if Globals.sockRetry == true. Globals.sockRetry is assigned true only if an exception is thrown. If no exception is thrown, the loop never ends.
Change it like this:
if (Globals.sockRetry == false)
{
connect(g);
break;
}
Otherwise after you connect you will connect again, and then again till an exception is thrown (hopefully).
continue continues to the next iteration in the loop.
break stops the loop. So, the loop never ends.
You set sockRetry to false when you want to stop the loop, so you could do this: while (sockRetry)
I'm developing an application to control cafeteria consumption for my company. Basically each employee has a badge id with a barcode, and they are entitled to a free meal every day. The application will scan the badge and log each employees' meals. It will run on a Motorola MK4000 device, which has an integrated scanner and runs on Windows CE.
I've got an issue with the device scanner. I can get it to run and scan fine, but if it stays idle for a few minutes, it goes to "Waiting" status, the laser turns off, and doesn't come back on. I've tried monitoring the status and starting a new read when it changes to that status, but then it just keeps scanning false reads indefinitely.
Can you guys help me figure out what im doing wrong?
This is the class I'm using for the scanner functionality. It wasn't developed by me, but its begin used for other applications on the same device (I made a few changes to it, mostly on the error messages).
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace MK4000
{
class BarCode
{
#region Fields
private Symbol.Barcode.Reader myReader = null;
private Symbol.Barcode.ReaderData myReaderData = null;
private System.EventHandler myReadNotifyHandler = null;
private System.EventHandler myStatusNotifyHandler = null;
#endregion Fields
#region Properties
/// <summary>
/// Provides the access to the Symbol.Barcode.Reader reference.
/// The user can use this reference for his additional Reader - related operations.
/// </summary>
public Symbol.Barcode.Reader Reader
{
get
{
return myReader;
}
}
public String ErrorMessage
{
get
{
return "Error";
}
}
#endregion Properties
#region Methods
/// <summary>
/// Attach a ReadNotify handler.
/// </summary>
public void AttachReadNotify(System.EventHandler ReadNotifyHandler)
{
// If we have a reader
if (myReader != null)
{
// Attach the read notification handler.
myReader.ReadNotify += ReadNotifyHandler;
myReadNotifyHandler = ReadNotifyHandler;
}
}
/// <summary>
/// Attach a StatusNotify handler.
/// </summary>
public void AttachStatusNotify(System.EventHandler StatusNotifyHandler)
{
// If we have a reader
if (myReader != null)
{
// Attach status notification handler.
myReader.StatusNotify += StatusNotifyHandler;
myStatusNotifyHandler = StatusNotifyHandler;
}
}
/// <summary>
/// Detach the ReadNotify handler.
/// </summary>
public void DetachReadNotify()
{
if ((myReader != null) && (myReadNotifyHandler != null))
{
// Detach the read notification handler.
myReader.ReadNotify -= myReadNotifyHandler;
myReadNotifyHandler = null;
}
}
/// <summary>
/// Detach a StatusNotify handler.
/// </summary>
public void DetachStatusNotify()
{
// If we have a reader registered for receiving the status notifications
if ((myReader != null) && (myStatusNotifyHandler != null))
{
// Detach the status notification handler.
myReader.StatusNotify -= myStatusNotifyHandler;
myStatusNotifyHandler = null;
}
}
/// <summary>
/// Initialize the reader.
/// </summary>
public bool InitReader()
{
// If the reader is already initialized then fail the initialization.
if (myReader != null)
{
return false;
}
else // Else initialize the reader.
{
try
{
// Get the device selected by the user.
Symbol.Generic.Device MyDevice =
Symbol.StandardForms.SelectDevice.Select(
Symbol.Barcode.Device.Title,
Symbol.Barcode.Device.AvailableDevices);
if (MyDevice == null)
{
MessageBox.Show(ErrorMessage);
return false;
}
// Create the reader, based on selected device.
myReader = new Symbol.Barcode.Reader(MyDevice);
// Create the reader data.
myReaderData = new Symbol.Barcode.ReaderData(
Symbol.Barcode.ReaderDataTypes.Text,
Symbol.Barcode.ReaderDataLengths.MaximumLabel);
// Enable the Reader.
myReader.Actions.Enable();
// In this sample, we are setting the aim type to trigger.
switch (myReader.ReaderParameters.ReaderType)
{
case Symbol.Barcode.READER_TYPE.READER_TYPE_IMAGER:
myReader.ReaderParameters.ReaderSpecific.ImagerSpecific.AimType = Symbol.Barcode.AIM_TYPE.AIM_TYPE_TRIGGER;
//myReader.Parameters.Feedback.Success.BeepTime = 0;
break;
case Symbol.Barcode.READER_TYPE.READER_TYPE_LASER:
myReader.ReaderParameters.ReaderSpecific.LaserSpecific.AimType = Symbol.Barcode.AIM_TYPE.AIM_TYPE_TRIGGER;
break;
case Symbol.Barcode.READER_TYPE.READER_TYPE_CONTACT:
// AimType is not supported by the contact readers.
break;
}
myReader.Actions.SetParameters();
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
return false;
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
return false;
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
return false;
};
return true;
}
}
/// <summary>
/// Start a read on the reader.
/// </summary>
public void StartRead(bool toggleSoftTrigger)
{
// If we have both a reader and a reader data
if ((myReader != null) &&
(myReaderData != null))
try
{
if (!myReaderData.IsPending)
{
// Submit a read.
myReader.Actions.Read(myReaderData);
if (toggleSoftTrigger && myReader.Info.SoftTrigger == false)
{
myReader.Info.SoftTrigger = true;
}
}
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
/// <summary>
/// Stop all reads on the reader.
/// </summary>
public void StopRead()
{
//If we have a reader
if (myReader != null)
{
try
{
// Flush (Cancel all pending reads).
if (myReader.Info.SoftTrigger == true)
{
myReader.Info.SoftTrigger = false;
}
myReader.Actions.Flush();
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
}
/// <summary>
/// Stop reading and disable/close the reader.
/// </summary>
public void TermReader()
{
// If we have a reader
if (myReader != null)
{
try
{
// stop all the notifications.
StopRead();
//Detach all the notification handler if the user has not done it already.
DetachReadNotify();
DetachStatusNotify();
// Disable the reader.
myReader.Actions.Disable();
// Free it up.
myReader.Dispose();
// Make the reference null.
myReader = null;
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
// After disposing the reader, dispose the reader data.
if (myReaderData != null)
{
try
{
// Free it up.
myReaderData.Dispose();
// Make the reference null.
myReaderData = null;
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
}
#endregion Methods
}
}
And this is the code for the actual form:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MK4000
{
public partial class Form1 : Form
{
private bool isReaderInitiated;
private BarCode myScanner;
private EventHandler myStatusNotifyHandler = null;
private EventHandler myReadNotifyHandler = null;
private String MacAddress = "00-00-00-00-00-00";
private String strIPAddress = "000.000.000.000";
private String version = "0.0.0.1";
public static int TaskbarHeight = Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height;
private int counter = 0;
private int itemLimit = 10;
public String ErrorMessage
{
get
{
return "Error";
}
}
public Form1()
{
InitializeComponent();
this.Width = Screen.PrimaryScreen.Bounds.Width;
this.Height = Screen.PrimaryScreen.Bounds.Height - TaskbarHeight;
this.FormBorderStyle = FormBorderStyle.None;
this.ControlBox = false;
this.MinimizeBox = false;
this.EmpID.Visible = false;
this.EmpName.Visible = false;
this.messageLabel.Visible = false;
this.lblCounter.Text = counter.ToString();
this.lblCounter.Visible = false;
this.statusBar1.Text = "Initializing.. Reticulating Splines " + MacAddress + " | " + strIPAddress + " | " + version;
this.listView1.View = View.Details;
this.listView1.Columns.Add("EmployeeID", 150, HorizontalAlignment.Left);
this.listView1.Columns.Add("EmployeeName", 330, HorizontalAlignment.Left);
this.listView1.Columns.Add("Time", 250, HorizontalAlignment.Left);
this.Closing += new CancelEventHandler(Form1_OnClosing);
this.myScanner = new BarCode();
this.isReaderInitiated = this.myScanner.InitReader();
if (!(this.isReaderInitiated))// If the reader has not been initialized
{
// Display a message & exit the application.
MessageBox.Show(ErrorMessage);
Application.Exit();
}
else // If the reader has been initialized
{
// Attach a status natification handler.
myScanner.AttachStatusNotify(myScanner_StatusNotify);
// Start a read operation & attach a handler.
myScanner.StartRead(true);
myScanner.AttachReadNotify(myScanner_ReadNotify);
}
}
private void myScanner_ReadNotify(object Sender, EventArgs e)
{
// Get ReaderData
Symbol.Barcode.ReaderData TheReaderData = this.myScanner.Reader.GetNextReaderData();
processData(TheReaderData.ToString());
this.myScanner.StopRead();
System.Threading.Thread.Sleep(1000);
this.myScanner.StartRead(true);
}
private void processData(string readerData)
{
string EmployeeName = "";
string EmployeeID = readerData;
hideMessage();
//This will query the employee database and proceed if employee exists, right now i just give it a random name
EmployeeName = "John Doe";
if (EmployeeName != "")
{
addToList(EmployeeID, EmployeeName);
counter += 1;
this.lblCounter.Text = counter.ToString();
this.EmpID.Visible = true
this.EmpName.Visible = true
this.lblCounter.Visible = true;
showMessage("Thank You!", System.Drawing.Color.LimeGreen);
}
}
private void showMessage(string messageText, System.Drawing.Color messageColor)
{
this.messageLabel.Text = messageText;
this.messageLabel.BackColor = messageColor;
this.messageLabel.Visible = true;
}
private void hideMessage()
{
this.messageLabel.Text = "";
this.messageLabel.BackColor = System.Drawing.Color.Black;
this.messageLabel.Visible = false;
}
private void addToList(string EmployeeID, string EmployeeName)
{
if (this.listView1.Items.Count >= itemLimit)
{
this.listView1.Items.RemoveAt(0);
}
ListViewItem item = new ListViewItem(EmployeeID);
//item.Text = EmployeeID;
item.SubItems.Add(EmployeeName);
item.SubItems.Add(DateTime.Now.ToString());
this.listView1.Items.Add(item);
this.listView1.Refresh();
}
private void myScanner_StatusNotify(object Sender, EventArgs e)
{
// Get ReaderData
Symbol.Barcode.BarcodeStatus TheStatusData = this.myScanner.Reader.GetNextStatus();
switch (TheStatusData.State)
{
case Symbol.Barcode.States.IDLE:
this.statusBar1.Text = "Idle - Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
case Symbol.Barcode.States.READY:
this.statusBar1.Text = "Ready - Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
case Symbol.Barcode.States.WAITING:
//this.myScanner.StopRead();
//this.myScanner.StartRead(true);
this.statusBar1.Text = "Waiting- Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
default:
this.statusBar1.Text = TheStatusData.Text + " " + MacAddress + " | " + strIPAddress + " | " + version;
break;
}
}
private void Form1_OnClosing(object Sender, EventArgs e)
{
if (isReaderInitiated)
{
myScanner.DetachReadNotify();
myScanner.DetachStatusNotify();
myScanner.TermReader();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
private void pictureBox2_Click(object sender, EventArgs e)
{
this.myScanner.StopRead();
this.myScanner.StartRead(true);
}
}
}
This is still a work in progress, mind you, so there is some functionality missing, but I want to have the scanner workingfull before moving forward. Any help will be greatly appreciated, thank you.
Ok, I figured out that the scanner goes into a cycle of switching between Idle and Waiting status, this is why my StatusNotify event handler was making the scanner laser turn on and off repeatedly.
I solved it by saving the previous status, and only restarting the scanner when the previous status is not one of those two.
case Symbol.Barcode.States.WAITING:
if (lastScannerStatus != "WAITING" && lastScannerStatus != "INIT" && lastScannerStatus != "IDLE")
{
this.myScanner.StopRead();
this.myScanner.StartRead(true);
}
this.statusBar1.Text = "Waiting- Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
I have a Boat Mooring reservations program, and currently, the way it works is, after you enter your name and click a button, the program gives you the next available mooring, there are 6 piers and 5 moorings per pier.
So, after all the moorings and piers are used up, the program crashes becuase there is nowhere for it to go, how can I make it so that the user gets a message box telling them, that there are no more spots available?
This is my code:
Button click:
private void button1_Click(object sender, EventArgs e)
{
var req = new BoatRequest();
req.Name = txtName.Text;
var client = new BoatReserveSoapClient();
BoatResponse response = client.ReserveMooring(req);
if (req != null)
{
Pierlbl.Text = response.Pier.ToString();
Mooringlbl.Text = response.Mooring.ToString();
Pierlbl.Visible = true;
Mooringlbl.Visible = true;
}
else
{
Pierlbl.Text = "Error Occured, please try again";
Mooringlbl.Text = "Error Occured, please try again";
}
}
The web method:
//Setting the max value for Piers and Moorings
public const int maxPiers = 6;
public const int maxMoorings = 30;
private static bool[,] reserveMooring = new bool[maxPiers, maxMoorings];
[WebMethod]
public BoatResponse ReserveMooring(BoatRequest req)
{
var res = new BoatResponse();
//if pierCalc set to 0, if smaller than maxPiers increment
for (int pierCalc = 0; pierCalc < maxPiers; pierCalc++)
{
//if mooringCalc set to 0, if smaller than maxMoorings increment
for (int mooringCalc = 0; mooringCalc < maxMoorings / maxPiers; mooringCalc++)
{
if (!reserveMooring[pierCalc, mooringCalc])
{
reserveMooring[pierCalc, mooringCalc] = true;
res.Pier = (Pier)pierCalc;
res.Mooring = (Mooring)mooringCalc;
return res;
}
}
}
return null;
}
This is where it crashes:
Pierlbl.Text = response.Pier.ToString();
Check that the response is not null, like this:
if (response != null)
{
Pierlbl.Text = response.Pier.ToString();
Mooringlbl.Text = response.Mooring.ToString();
Pierlbl.Visible = true;
Mooringlbl.Visible = true;
}
else
{
Pierlbl.Text = "Error Occured, please try again";
Mooringlbl.Text = "Error Occured, please try again";
}
You should just check if response != null and if it's the case, show the user a message.
In this example, req is never going to equal null. the response object is receiving the return value from your Web Service and would therefore the one to check for a null value in your if statement.
Like so:
if (response != null)
{
//Logic for success
}
else
{
//Logic for failure
}