I've used in the past RabbitMq as MessageQueue and it was really simple to have an event fired when a message has been received.
I've looked at the .NET sources provided with IBM installer but I've found a not good way to handle it. Looking at the sample SimpleSubscribe it does such a thing to pool
// getting messages continuously
for (int i = 1; i <= numberOfMsgs; i++)
{
// creating a message object
message = new MQMessage();
try
{
topic.Get(message);
Console.WriteLine("Message " + i + " got = " + message.ReadString(message.MessageLength));
message.ClearMessage();
}
catch (MQException mqe)
{
if (mqe.ReasonCode == 2033)
{
++time;
--i;
Console.WriteLine("No message available");
Thread.Sleep(1000);
//waiting for 10sec
if (time > 10)
{
Console.WriteLine("Timeout : No message available");
break;
}
continue;
}
else
{
Console.WriteLine("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message);
}
}
}
where the number of numberOfMsgs is an integer passed as an argument. If I pass -1 it probably will pool at the infinite but I think it's not a good approach. This leads me to pool the queue at a specific interval then probably will spin a thread at 100% I don't put a Thread.Sleep
Does anyone have a better approach?
You should use "MQGET with Wait" option rather than use polling. The MQGET call will wait for a message to arrive and return immediately when it receives a message otherwise it will wait for "x" milliseconds.
Here is a simple working C# MQ program:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;
/// <summary> Program Name
/// MQTest62
///
/// Description
/// This C# class will connect to a remote queue manager
/// and get messages from a queue using a managed .NET environment.
///
/// Sample Command Line Parameters
/// -h 127.0.0.1 -p 1415 -c TEST.CHL -m MQWT1 -q TEST.Q1 -u tester -x mypwd
/// </summary>
/// <author> Roger Lacroix
/// </author>
namespace MQTest62
{
public class MQTest62
{
private Hashtable inParms = null;
private Hashtable qMgrProp = null;
private System.String qManager;
private System.String inputQName;
/*
* The constructor
*/
public MQTest62()
: base()
{
}
/// <summary> Make sure the required parameters are present.</summary>
/// <returns> true/false
/// </returns>
private bool allParamsPresent()
{
bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
inParms.ContainsKey("-q");
if (b)
{
try
{
System.Int32.Parse((System.String)inParms["-p"]);
}
catch (System.FormatException e)
{
b = false;
}
}
return b;
}
/// <summary> Extract the command-line parameters and initialize the MQ variables.</summary>
/// <param name="args">
/// </param>
/// <throws> IllegalArgumentException </throws>
private void init(System.String[] args)
{
inParms = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(14));
if (args.Length > 0 && (args.Length % 2) == 0)
{
for (int i = 0; i < args.Length; i += 2)
{
inParms[args[i]] = args[i + 1];
}
}
else
{
throw new System.ArgumentException();
}
if (allParamsPresent())
{
qManager = ((System.String)inParms["-m"]);
inputQName = ((System.String)inParms["-q"]);
qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));
try
{
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (inParms.ContainsKey("-u"))
qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));
if (inParms.ContainsKey("-x"))
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));
System.Console.Out.WriteLine("MQTest62:");
Console.WriteLine(" QMgrName ='{0}'", qManager);
Console.WriteLine(" Output QName ='{0}'", inputQName);
System.Console.Out.WriteLine("QMgr Property values:");
foreach (DictionaryEntry de in qMgrProp)
{
Console.WriteLine(" {0} = '{1}'", de.Key, de.Value);
}
}
else
{
throw new System.ArgumentException();
}
}
/// <summary> Connect, open queue, read (browse) a message, close queue and disconnect. </summary>
///
private void testReceive()
{
MQQueueManager qMgr = null;
MQQueue inQ = null;
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING;
try
{
qMgr = new MQQueueManager(qManager, qMgrProp);
System.Console.Out.WriteLine("MQTest62 successfully connected to " + qManager);
inQ = qMgr.AccessQueue(inputQName, openOptions);
System.Console.Out.WriteLine("MQTest62 successfully opened " + inputQName);
testLoop(inQ);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest62 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("MQTest62 ioex=" + ioex);
}
finally
{
try
{
if (inQ != null)
inQ.Close();
System.Console.Out.WriteLine("MQTest62 closed: " + inputQName);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest62 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
try
{
if (qMgr != null)
qMgr.Disconnect();
System.Console.Out.WriteLine("MQTest62 disconnected from " + qManager);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest62 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
}
}
}
private void testLoop(MQQueue inQ)
{
bool flag = true;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options |= MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING;
gmo.WaitInterval = 2500; // 2.5 seconds wait time or use MQC.MQEI_UNLIMITED to wait forever
MQMessage msg = null;
while (flag)
{
try
{
msg = new MQMessage();
inQ.Get(msg, gmo);
System.Console.Out.WriteLine("Message Data: " + msg.ReadString(msg.MessageLength));
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQTest62 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE)
{
// no meesage - life is good - loop again
}
else
{
flag = false; // severe error - time to exit
}
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("MQTest62 ioex=" + ioex);
}
}
}
/// <summary> main line</summary>
/// <param name="args">
/// </param>
// [STAThread]
public static void Main(System.String[] args)
{
MQTest62 write = new MQTest62();
try
{
write.init(args);
write.testReceive();
}
catch (System.ArgumentException e)
{
System.Console.Out.WriteLine("Usage: MQTest62 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
System.Environment.Exit(1);
}
catch (MQException e)
{
System.Console.Out.WriteLine(e);
System.Environment.Exit(1);
}
System.Environment.Exit(0);
}
}
}
Related
I created a windows service that will connect to remote MQ and get the message as MQSTR format but after getting the message I didn't closed connection to remote MQ . My windows service will continuously check if data is available in remote MQ or not but after getting one message I need to restart my service to get the another message from remote MQ . Can anyone tell me what I need to do to get message constantly from remote MQ . Any clue or any link will do fine . Please Help
My C# windows service code is like this :
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace MQ_listner
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
Service1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MQ_listner
{
public partial class Service1 : ServiceBase
{
private MQReader MQReader;
private string _serviceName = "MQ_Listener";
private DateTime _TimeStart;
private bool _run = true;
private Thread _thread;
int WaitWhenStop = 0;
private DateTime _TimeEnd;
private TimeSpan _TimeDifference;
private TimeSpan _TimeElasped = new TimeSpan(0);
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
EventLog.WriteEntry(_serviceName + "was started at" + _TimeStart.ToString());
_run = true;
_thread = new Thread(new ThreadStart(StartMQListenerService));
_thread.IsBackground = true;
_thread.Start();
}
catch (Exception ex)
{
EventLog.WriteEntry(_serviceName + "was not started . Error Message : " + ex.ToString());
}
}
protected override void OnStop()
{
_run = false;
_thread.Join(WaitWhenStop);
_TimeEnd = DateTime.Now;
_TimeDifference = _TimeEnd.Subtract(_TimeStart);
_TimeElasped = _TimeElasped.Add(_TimeDifference);
EventLog.WriteEntry(_serviceName + "was stopped at " + _TimeEnd.ToString() + "\r\n ran for total time :" + _TimeElasped.ToString());
}
// MQ connection service
public void StartMQListenerService()
{
try
{
if (_run)
{
if (MQReader == null)
{
MQReader = new MQReader();
MQReader.InitializeConnections();
EventLog.WriteEntry(_serviceName + "MQ connection is established");
}
}
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry(_serviceName, ex.ToString());
System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startinfo.FileName = "NET";
startinfo.Arguments = "stop" + this.ServiceName;
Process.Start(startinfo);
}
}
}
}
****MQReader.cs****
using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;
namespace MQ_listner
{
internal class MQReader
{
public MQReader()
{
}
public void InitializeConnections()
{
MQQueueManager queueManager;
MQMessage queueMessage;
MQGetMessageOptions queueGetMessageOptions;
MQQueue queue;
string QueueName;
string QueueManagerName;
string ChannelInfo;
string channelName;
string PortNumber;
string transportType;
string connectionName;
QueueManagerName = ConfigurationManager.AppSettings["QueueManager"];
QueueName = ConfigurationManager.AppSettings["Queuename"];
ChannelInfo = ConfigurationManager.AppSettings["ChannelInformation"];
PortNumber = ConfigurationManager.AppSettings["Port"];
char[] separator = { '/' };
string[] ChannelParams;
ChannelParams = ChannelInfo.Split(separator);
channelName = ConfigurationManager.AppSettings["Channel"];
transportType = ConfigurationManager.AppSettings["TransportType"];
connectionName = ConfigurationManager.AppSettings["ConnectionName"];
String strReturn = "";
try
{
queueManager = new MQQueueManager(QueueManagerName,
channelName, connectionName);
strReturn = "Connected Successfully";
queue = queueManager.AccessQueue(QueueName,
MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
queueMessage = new MQMessage();
queueMessage.Format = MQC.MQFMT_STRING;
queueGetMessageOptions = new MQGetMessageOptions();
queue.Get(queueMessage, queueGetMessageOptions);
strReturn = queueMessage.ReadString(queueMessage.MessageLength);
}
catch (MQException exp)
{
strReturn = "Exception: " + exp.Message;
}
string path1 = #"C:\documents\Example.txt";
System.IO.File.WriteAllText(path1, strReturn);
}
}
}
Can anyone tell me what is wrong in my code? Do I need anything to add here to get message constantly from remote MQ . Please Help . Any link or clue will do fine .
EDIT
after certain amount of time I need to restart my service to fetch data from remote mq . Can you tell me why windows service needs to restart to fetch data . Any clue? any idea ?
Where is your queue close and queue manager disconnect? If you connect and/or open something, you must make sure you close and disconnect from it. I would strongly suggest you take an MQ programming course. Or go to the MQ Technical Conference which has sessions on programming MQ.
I posted a fully functioning C# MQ program that retrieves all of the messages on a queue at MQQueueManager message pooling
Here is an updated version of your MQReader class that should give you the right idea. Note: I did not test it. I leave that for you. :)
Also, you should be putting your connection information in a Hashtable and pass the Hashtable to the MQQueueManager class.
using System;
using IBM.WMQ;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;
namespace MQ_listner
{
internal class MQReader
{
private MQQueueManager qManager = null;
private MQMessage inQ = null;
private bool running = true;
public MQReader()
{
}
public bool InitQMgrAndQueue()
{
bool flag = true;
Hashtable qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings["ConnectionName"]);
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings["Channel"]);
try
{
if (ConfigurationManager.AppSettings["Port"] != null)
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse(ConfigurationManager.AppSettings["Port"]));
else
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (ConfigurationManager.AppSettings["UserID"] != null)
qMgrProp.Add(MQC.USER_ID_PROPERTY, ConfigurationManager.AppSettings["UserID"]);
if (ConfigurationManager.AppSettings["Password"] != null)
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ConfigurationManager.AppSettings["Password"]);
try
{
qManager = new MQQueueManager(ConfigurationManager.AppSettings["QueueManager"],
qMgrProp);
System.Console.Out.WriteLine("Connected Successfully");
inQ = qManager.AccessQueue(ConfigurationManager.AppSettings["Queuename"],
MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
System.Console.Out.WriteLine("Open queue Successfully");
}
catch (MQException exp)
{
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
flag = false;
}
return flag;
}
public void LoopThruMessages()
{
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options |= MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING;
gmo.WaitInterval = 2500; // 2.5 seconds wait time or use MQC.MQEI_UNLIMITED to wait forever
MQMessage msg = null;
while (running)
{
try
{
msg = new MQMessage();
inQ.Get(msg, gmo);
System.Console.Out.WriteLine("Message Data: " + msg.ReadString(msg.MessageLength));
}
catch (MQException mqex)
{
if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE)
{
// no meesage - life is good - loop again
}
else
{
running = false; // severe error - time to exit
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("ioex=" + ioex);
}
}
try
{
if (inQ != null)
{
inQ.Close();
System.Console.Out.WriteLine("Closed queue");
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
try
{
if (qMgr != null)
{
qMgr.Disconnect();
System.Console.Out.WriteLine("disconnected from queue manager");
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
public void StopIt()
{
running = false;
}
}
}
Whenever you stop the service, make sure it calls the StopIt method in MQReader.
I have been facing slow client message consuming in client/server app using TCP sockets in c#. Whenever slow client is connected to server, it affects the processing of other clients.
After reading some literature regarding tcp/ip stack in c#, i concluded that due to RCV_BUFFER full at client side and SND_BUFFER full at server side, other clients are affecting.
Although i couldn't produce the scenario in real environment, so here is what i have done for simulating slow client message processing.
Created sample application for client and implemented the sleep for 1 to 10 seconds before reading it from RCV_BUFFER (so it can be full).
Connecting two clients (one with varying sleep time while other with no sleep time).
I saw that client with no sleep time is affecting but i couldn't determine the pattern of this problem.
Here are some queries, i want to clear confusion on my side.
1. How to determine the size of SND_BUFFER before sending the data to TCP SEND_WINDOW at server side.
2. What steps should i take to determine the pattern of problem. So i can proceed to solution.
Here are code snippets for Server Side.
public bool Start()
{
try
{
_listener.Bind(new IPEndPoint(IPAddress.Any, _port));
_listener.Listen(2000);
_listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 5000);
_listener.BeginAccept(ConnectionReady, null);
LogHelper.ErrorLogger.Debug("Listening started");
return true;
}
catch
{
return false;
}
}
public void createSession(object obj)
{
Socket conn = (Socket)obj;
try
{
LogHelper.ErrorLogger.Debug("Creating Session");
ConnectionState st = new ConnectionState(conn); // Custom class for maintaining the socket object
st._server = this;
st._provider = _provider;
st._buffer = new byte[4];
st._provider.OnAcceptConnection(st);
AcceptConnection.BeginInvoke(st, null, st);
LogHelper.ErrorLogger.Debug("Session Created");
}
catch (Exception ex)
{
try
{
conn.Close();
}
catch { }
LogHelper.ErrorLogger.Debug("Session aborted - >" + ex.ToString());
}
}
private void AcceptConnection_Handler(object state)
{
try
{
ConnectionState st = state as ConnectionState;
try
{
st.AuthenticateSocket();
//Starts the ReceiveData callback loop
if (st._conn.Connected)
st._conn.BeginReceive(st._buffer, 0, 0, SocketFlags.None, ReceivedDataReady, st);
}
catch
{
DropConnection(st);
}
}
catch { }
}
private void ReceivedDataReady_Handler(IAsyncResult ar)
{
try
{
ConnectionState st = ar.AsyncState as ConnectionState;
try
{
try
{
int bytesRcv = st._conn.EndReceive(ar);
//Encoding.UTF8.GetString(buffer, 0, readBytes);
//state.msgBuffer.Append(_receivedStr);
}
catch
{
DropConnection(st); return;
}
//Im considering the following condition as a signal that the
//remote host droped the connection.
if (st._conn.Available == 0)
{
DropConnection(st);//##SHARIQ
return;
}
else
{
try
{
st._provider.OnReceiveData(st);
}
catch
{
return;
}
//Resume ReceivedData callback loop
if (st._conn.Connected)
st._conn.BeginReceive(st._buffer, 0, 0, SocketFlags.None, ReceivedDataReady, st);
}
}
catch { DropConnection(st); return; }
}
catch { }
}
Message is fetched from MSMQ (a thread is running to fetch messages from MSMQ through receiver object), and whenever message is fetched following event is fired and extracts ip addresses from messages and send one message to socket(s).
private void m_broker_OnMessage(object obj)
{
try
{
Message m = (Message)obj;
m.Formatter = new BinaryMessageFormatter();
ConnectionState tstate = null;
bool containststate = false;
string TempLabels = string.Empty;
string BodyMessage = string.Empty;
if (m.Body.ToString().StartsWith("="))
{
BodyMessage = (string)m.Body;
TempLabels = BodyMessage.Substring(1, BodyMessage.IndexOf('#') - 1);
BodyMessage = BodyMessage.Substring(BodyMessage.IndexOf('#') + 1);
}
if (!string.IsNullOrEmpty(TempLabels))
{
string[] labels = TempLabels.Split(',');
foreach (string label in labels)
{
lock (cons)
{
containststate = cons.Contains(label);
if (containststate)
{
tstate = (ConnectionState)cons[label];
}
}
if (containststate)
{
ConnectionState state = tstate;
if (!state.WriteLine(BodyMessage + "1057=" + label + "#"))
{
OnDropConnection(state);
continue;
}
if (ConfigurationSettings.AppSettings["FullLog"] == "1")
{
eventLogger.Debug("OUT " + label + " " + BodyMessage);
}
}
else
{
long result;
if (!lastResolve.Contains(label))
{
if ((!string.IsNullOrEmpty(label)) && long.TryParse(label, out result))
{
if (ConfigurationSettings.AppSettings["FullLog"] == "1")
{
eventLogger.Info("Label not found: " + label);
}
string msg = "8=EXX.1.0#35=C7#1057=" + label + "#";
this.Send(msg, label, "0.0.0.0");
eventLogger.Info("Connection Disconnected: " + label);
//Nothing to clean here
lock (cons)
{
if (cons.Contains(label))
{
try
{
string ipaddress = ((ConnectionState)cons[label]).RemoteEndPoint.ToString().Split(':')[0];
connectionGroups[ipaddress]--;
}
catch { }
}
cons.Remove(label);
lastResolve.Add(label);
}
}
}
continue;
}
}
}
else
{
lock (cons)
{
containststate = cons.Contains(m.Label);
if (containststate)
{
tstate = (ConnectionState)cons[m.Label];
}
}
if (containststate)
{
ConnectionState state = tstate;
if (!state.WriteLine((string)m.Body + "1057=" + m.Label + "#"))
{
OnDropConnection(state);
return;
}
if (ConfigurationSettings.AppSettings["FullLog"] == "1")
{
eventLogger.Debug("OUT " + m.Label + " " + m.Body.ToString());
}
}
else
{
long result;
if (!lastResolve.Contains(m.Label))
{
if ((!string.IsNullOrEmpty(m.Label)) && long.TryParse(m.Label, out result))
{
if (ConfigurationSettings.AppSettings["FullLog"] == "1")
{
eventLogger.Info("Label not found: " + m.Label);
}
string msg = "8=EXX.1.0#35=C7#1057=" + m.Label + "#";
this.Send(msg, m.Label, "0.0.0.0");
eventLogger.Info("Connection Disconnected: " + m.Label);
//Nothing to clean here
lock (cons)
{
if (cons.Contains(m.Label))
{
try
{
string ipaddress = ((ConnectionState)cons[m.Label]).RemoteEndPoint.ToString().Split(':')[0];
connectionGroups[ipaddress]--;
}
catch { }
}
cons.Remove(m.Label);
lastResolve.Add(m.Label);
}
}
}
return;
}
}
}
catch (Exception e)
{
errorLogger.Error(e.Message, e);
}
}
Sending is done in blocking manner
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags)
{
lock (sendObject)
{
try
{
if (_innerSocketStream.IsUsingSsl)
{
myStream.Write(buffer, offset, size);
}
else
{
_innerSocketStream.Socket.Send(buffer, offset, size, SocketFlags.None);
}
}
catch (SocketException)
{
return 0;
}
return size;
}
}
I have a Windows service that exits or crashed because of internet outage. Is there a simple way to monitor it to make sure it gets restarted automatically if it crashes?
Update
Here is the exception that we often got from the service.
An error has occured with the myservice:
Exception Message: The operation has timed out
Inner Exception:
Date Time: 11/13/2015 8:03:09 PM
Stack Trace: at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at myservice.CrmSdk.CrmService.Delete(String entityName, Guid id)
at myservice.myservice.timer1_Elapsed(Object sender, ElapsedEventArgs e)
Here is what going on into the service.
public partial class myservice : ServiceBase
{
public myservice() {
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("myservice Source"))
{
System.Diagnostics.EventLog.CreateEventSource("myservice Source", "myservice Log");
}
eventLog1.Source = "myservice Source";
eventLog1.Log = "myservice Log";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("myservice service started on " + DateTime.Now.ToString());
//timer1.Interval = 60000;
//timer1.Start();
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
int intProcessHour = Convert.ToInt32(ProcessHour);
DateTime dtNow = DateTime.Now;
if (dtNow.Hour < intProcessHour){
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}else{
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}
}
protected override void OnStop(){
eventLog1.WriteEntry("myservice service stopped on " + DateTime.Now.ToString());
}
public string GetParentAccountID(string strAgentID)
{
/* some logic to bring parentAccount
*/
}
public int GetAuditGrade(string strAuditGrade)
{
/* some logic to get grades of audits
*/
}
public string GetAuditID(string sAgentID, string sDate)
{
/* some logic to get audit id
*/
}
public bool AuditRecordExists(string strAgentID, DateTime DateAuditStartDate)
{
/* some logic to check if audit record already exists
*/
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
eventLog1.WriteEntry("myservice timer1_Elapsed begin on " + DateTime.Now.ToString());
/* Create audit if not exists*/
}
catch (Exception ex)
{
eventLog1.WriteEntry("myservice - Exception Notice.\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Stack Trace: " + ex.StackTrace);
eventLog1.WriteEntry("Exception. myservice timer1_Elapsed ended on " + DateTime.Now.ToString());
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
DateTime dtStartDateTime = DateTime.Today.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
MailMessage message = new MailMessage(
ConfigurationManager.AppSettings["ErrorSender"],
ConfigurationManager.AppSettings["ErrorRecepient"],
"myservice - Exception Notice",
"An error has occured with the myservice:\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Date Time: " + DateTime.Now.ToString() + "\n\n" +
"Stack Trace: " + ex.StackTrace);
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPClient"]);
client.Send(message);
}
}
private void eventLog1_EntryWritten(object sender, EntryWrittenEventArgs e)
{
}
}
If you have access to the source code of the service, you should try to fix the service by adding proper error handling etc. If you do not have access to the source, you may try this.
1) Go to services
2) Right click on the service
3) Goto recovery tab
4) Select "Restart service" for first failure, 2nd failure and subsequent failures. Then click apply/ok.
Rewrite your code like this;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net.Mail;
using System.ServiceProcess;
using System.Timers;
namespace WindowsService1
{
public partial class myservice : ServiceBase
{
private EventLog _eventLog1;
private Timer _timer1;
public myservice()
{
InitializeComponent();
}
private void InitialiseService()
{
try
{
const string source = "myservice Source";
const string name = "myservice Log";
_eventLog1 = new EventLog();
if (!EventLog.SourceExists(source))
{
EventLog.CreateEventSource(source, name);
}
_eventLog1.Source = source;
_eventLog1.Log = name;
WriteLog("myservice service started on " + DateTime.Now);
int intProcessHour;
string processHour = ConfigurationManager.AppSettings["ProcessHour"];
var interval = (int.TryParse(processHour, out intProcessHour) && intProcessHour > 0 &&
intProcessHour < 24
? intProcessHour
: 1) * 60 * 60 * 1000;
_timer1 = new Timer(interval);
_timer1.Elapsed +=timer1_Elapsed;
_timer1.Start();
// Process(); //enable this if you want to process immidiately. Else the timer will process when it elapsed.
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void Process()
{
try
{
GetParentAccountID("xxx");
GetAuditGrade("yyyy");
GetAuditID("tttt", "45354345");
AuditRecordExists("rrrr", DateTime.Now);
}
catch (Exception ex)
{
WriteLog(ex.Message);
SendEmail(ex);
}
}
private string GetParentAccountID(string strAgentID)
{
/* some logic to bring parentAccount
*/
}
private int GetAuditGrade(string strAuditGrade)
{
/* some logic to get grades of audits
*/
}
private string GetAuditID(string sAgentID, string sDate)
{
/* some logic to get audit id
*/
}
private bool AuditRecordExists(string strAgentID, DateTime DateAuditStartDate)
{
/* some logic to check if audit record already exists
*/
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
WriteLog("myservice timer1_Elapsed started at " + DateTime.Now);
Process();
WriteLog("myservice timer1_Elapsed finished at " + DateTime.Now);
}
catch (Exception ex)
{
WriteLog(ex.Message);
}
}
private void SendEmail(Exception ex)
{
try
{
using (SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPClient"]))
{
using (MailMessage message = new MailMessage(
ConfigurationManager.AppSettings["ErrorSender"],
ConfigurationManager.AppSettings["ErrorRecepient"],
"myservice - Exception Notice",
"An error has occured with the myservice:\n\n" +
"Exception Message: " + ex.Message + "\n\n" +
"Inner Exception: " + ex.InnerException + "\n\n" +
"Date Time: " + DateTime.Now + "\n\n" +
"Stack Trace: " + ex.StackTrace))
{
client.Send(message);
}
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
private void WriteLog(string logEntry)
{
try
{
if (!string.IsNullOrEmpty(logEntry) && _eventLog1 != null)
_eventLog1.WriteEntry(logEntry);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
protected override void OnStart(string[] args)
{
try
{
InitialiseService();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
protected override void OnStop()
{
try
{
_timer1.Stop();
_timer1.Elapsed -= timer1_Elapsed;
WriteLog("myservice service stopped on " + DateTime.Now);
_eventLog1.Close();
_eventLog1.Dispose();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
I have a C# desktop app that sends jpegs to my server at the rate of 10 per second.
Each jpeg has the time stamp as part of its header and is read by my server.
I am experiencing a disorderly arrival on my server.
the majority of the time the jpegs are received by my sever in the order they have been sent by my client.
But, every now and then the order becomes 'jumbled'.
Are TCP packets supposed to be guaranteed to be sent in order or is it subject to delays by the network/internet?
If the order is guaranteed then I will post my code.
Thanks
My Code:
On Client:
class WebSocketClient
{
static WebSocket websocket = null;
public static void Start()
{
try {
Console.WriteLine("Started At: " + DateTime.Now.ToString());
if (websocket != null)
{
websocket.Dispose();
}
websocket = new WebSocket("ws://a uri");
websocket.Opened += new EventHandler(webSocketClient_Opened);
websocket.Error += websocket_Error;
websocket.Closed += new EventHandler(webSocketClient_Closed);
websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
websocket.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#8");
}
}
private static bool TimeOutOccured = false;
private static DateTime stopped;
public static void Send(byte[] packet)
{
try
{
if (websocket.State == WebSocketState.Open)
{
if (packet != null)
{
websocket.Send(packet, 0, packet.Length);
}
TimeOutOccured = false;
}
else
{
if (TimeOutOccured)
{
Console.WriteLine("TimeOut At: " + DateTime.Now.ToString());
if ((DateTime.Now - stopped).TotalSeconds > 30)
{
websocket.Opened -= new EventHandler(webSocketClient_Opened);
websocket.Error -= websocket_Error;
websocket.Closed -= new EventHandler(webSocketClient_Closed);
websocket.MessageReceived -= new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
Start();
}
}
else
{
TimeOutOccured = true;
stopped = DateTime.Now;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#9");
}
}
static void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs ex)
{
try {
Console.WriteLine("Error At: " + DateTime.Now.ToString());
Shared.AddError("WebSocketClient.websocket_Error", ex.Exception);
}
catch (Exception x)
{
Console.WriteLine(x.ToString() + " DEBUG#10");
}
}
protected static void webSocketClient_MessageReceived(object sender, MessageReceivedEventArgs e)
{
try {
var m_CurrentMessage = e.Message;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#11");
}
}
protected static void webSocketClient_Closed(object sender, EventArgs e)
{
try
{
Console.WriteLine("Closed At: " + DateTime.Now.ToString());
if (websocket.State == WebSocketState.Closed)
{
System.Threading.Thread.Sleep(1000);
Start();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " DEBUG#12");
}
}
protected static void webSocketClient_Opened(object sender, EventArgs e)
{
Console.WriteLine("Opened At: " + DateTime.Now.ToString());
}
}
My Server Code:
public void Start2()
{
try
{
var server = new WebSocketServer("my wan uri");
ILog logger = LogManager.GetLogger(typeof(FleckLog));
FleckLog.LogAction = (level, message, ex) =>
{
switch (level)
{
case LogLevel.Debug:
//gger.Debug(message, ex);
break;
case LogLevel.Error:
SocketMessage("3", message, ex);
break;
case LogLevel.Warn:
SocketMessage("4", message, ex);
break;
default:
SocketMessage("5", message, ex);
break;
}
};
server.Start(socket =>
{
socket.OnOpen = () => evStatusChanged("Open!");
socket.OnClose = () => evStatusChanged("Close!");
socket.OnError = error =>
{
Console.WriteLine("DEBUG:1 " + error.ToString());
};
socket.OnBinary = packetIn =>
{
try
{
//i check my timestamps in my headers here
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " ServerWebSocket.WebSocketServer_NewDataReceived.Catch3");
}
};
socket.OnMessage = message =>
{
};
});
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString() + " ServerWebSocket.Start2");
}
}
I am using the WebSocket4Net for my client socket framework
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;