Following Code snippet is sending PIN to another Self Hosted WCF service inside Windows Service which further then makes a call to SMPP server. But that only happens when i am in debug mode. In normal mode it does not work.
$
ChannelFactory<IServiceWCF> pipeFactory =
new ChannelFactory<IServiceWCF>(
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/MyService/PipeForMyService"));
pipeProxy = pipeFactory.CreateChannel();
pipeProxy.Connect();
pipeProxy.SendPin(pin);
ServiceWCF
$
public class ServiceWCF : IServiceWCF
{
PINComposer pinComposer = new PINComposer();
public bool SendPin(string pin)
{
Library.WriteErrorLog("Call Hits. Pin is " + pin);
PINComposer pinComposer = new PINComposer();
pinComposer.Connect();
pinComposer._client.SendSpeedLimit = 0;
DataCodings coding = (DataCodings)Enum.Parse(typeof(DataCodings), "Default");
byte srcTon = byte.Parse("0");
byte srcNpi = byte.Parse("0");
string srcAdr = "2378";
byte dstTon = byte.Parse("1");
byte dstNpi = byte.Parse("1");
string dstAdr = "03347823422";
IList<SubmitSmResp> resp = pinComposer._client.Submit(SMS.ForSubmit()
.From(srcAdr, srcTon, srcNpi)
.To(dstAdr, dstTon, dstNpi)
.Coding(coding)
.Text(pin + " " + "is your pin code")
.ExpireIn(TimeSpan.FromDays(2))
.DeliveryReceipt()
);
Library.WriteErrorLog("SMS Sent");
return true;
}
public bool Connect()
{
pinComposer.Connect();
return true;
}
}
PINComposer.CS
$
class PINComposer
{
public readonly SmppClient _client;
private readonly MessageComposer _messageComposer = new MessageComposer();
public PINComposer()
{
_client = new SmppClient();
_client.Timeout = 60000;
_client.NeedEnquireLink = true;
_client.EnquireInterval = 20;
_client.RaiseEventsInMainThread = true;
_client.evConnected += new Inetlab.SMPP.Common.ConnectedEventHandler(client_evConnected);
_client.evDisconnected += new Inetlab.SMPP.Common.DisconnectedEventHandler(client_evDisconnected);
_client.evBindComplete += new Inetlab.SMPP.Common.BindRespEventHandler(client_evBindComplete);
_client.evDeliverSm += new Inetlab.SMPP.Common.DeliverSmEventHandler(client_evDeliverSm);
_client.evEnquireLink += new Inetlab.SMPP.Common.EnquireLinkEventHandler(client_evEnquireLink);
_client.evGenericNack += new Inetlab.SMPP.Common.GenericNackEventHandler(client_evGenericNack);
_client.evUnBind += new Inetlab.SMPP.Common.UnBindEventHandler(client_evUnBind);
_client.evDataSm += new Inetlab.SMPP.Common.DataSmEventHandler(client_evDataSm);
_client.evSubmitComplete += new Inetlab.SMPP.Common.SubmitSmRespEventHandler(client_evSubmitComplete);
_client.evQueryComplete += new Inetlab.SMPP.Common.QuerySmRespEventHandler(client_evQueryComplete);
_messageComposer.evFullMessageReceived += OnFullMessageReceived;
_messageComposer.evFullMessageTimedout += OnFullMessageTimedout;
}
public void Connect()
{
if (_client.Status == ConnectionStatus.Closed)
{
_client.AddrNpi = Convert.ToByte(0);
_client.AddrTon = Convert.ToByte(0);
_client.EnabledSslProtocols = SslProtocols.None;
_client.ConnectAsync("172.16.53.39", 2775);
}
}
void client_evConnected(object sender, bool bSuccess)
{
if (bSuccess)
{
_client.BindAsync("radius", "rad12", ConnectionMode.Transceiver);
Library.WriteErrorLog("SMPP Service has been connected to server...");
}
}
private void client_evEnquireLink(object sender, EnquireLink data)
{
Library.WriteErrorLog("Link with server is alive...");
}
private void client_evGenericNack(object sender, GenericNack data)
{
Library.WriteErrorLog("GenericNack received with status " + data.Status.ToString());
}
private void client_evUnBind(object sender, UnBind data)
{
Library.WriteErrorLog("UnBind request received");
}
void client_evSubmitComplete(object sender, SubmitSmResp data)
{
Library.WriteErrorLog("SubmitSmResp received." + " Status: " + data.Status + ", Message Id: " + data.MessageId + ", Sequence: " + data.Sequence);
}
void client_evQueryComplete(object sender, QuerySmResp data)
{
Library.WriteErrorLog("QuerySmResp received." + " Status: " + data.Status + ", Message Id: " + data.MessageId + ", Sequence: " + data.Sequence + ", Message State: " + data.MessageState);
}
private void client_evDeliverSm(object sender, DeliverSm data)
{
try
{
//Check if we received Delivery Receipt
if (data.MessageType == MessageTypes.SMSCDeliveryReceipt)
{
//Get MessageId of delivered message
string messageId = data.Receipt.MessageId;
MessageState deliveryStatus = data.Receipt.State;
}
else
{
// Receive incoming message and try to concatenate all parts
if (data.Concatenation != null)
{
_messageComposer.AddMessage(data);
Library.WriteErrorLog(
string.Format(
"DeliverSm part received : Sequence : {0} SourceAddr : {1} Concatenation ( {2} )" +
" Coding : {3} Text : {4}",
data.Sequence, data.SourceAddr, data.Concatenation, data.DataCoding, data.MessageText));
}
else
{
Library.WriteErrorLog("DeliverSm received : "
+ " Sequence : " + data.Sequence
+ " SourceAddr : " + data.SourceAddr
+ " Coding : " + data.DataCoding
+ " MessageText : " + data.MessageText);
}
}
}
catch (Exception ex)
{
data.Response.Status = CommandStatus.ESME_RX_T_APPN;
Library.WriteErrorLog("Failed to process DeliverSm" + ex);
}
}
private void client_evDataSm(object sender, DataSm data)
{
string messageText = data.Client.GetMessageText(data);
Library.WriteErrorLog("DataSm received :"
+ " Sequence: " + data.Sequence
+ ", SourceAddr: " + data.SourceAddr
+ ", DestAddr: " + data.DestAddr
+ ", Coding: " + data.DataCoding
+ ", Text: " + messageText);
}
void client_evDisconnected(object sender)
{
Library.WriteErrorLog("SmppClient disconnected");
}
private void OnFullMessageTimedout(object sender, MessageEventHandlerArgs args)
{
Library.WriteErrorLog(string.Format("Incomplete message received from {0}", args.Parts[0].SourceAddr));
}
private void OnFullMessageReceived(object sender, MessageEventHandlerArgs args)
{
Library.WriteErrorLog(string.Format("Full message received from {0}: {1}", args.Parts[0].SourceAddr, args.Text));
}
void client_evBindComplete(object sender, Inetlab.SMPP.PDU.BindResp data)
{
switch (data.Status)
{
case CommandStatus.ESME_ROK:
Library.WriteErrorLog("SmppClient bound");
Library.WriteErrorLog("Bind result : system is " + data.SystemId + " with status " + data.Status.ToString());
break;
default:
Library.WriteErrorLog("Bad status returned during Bind : " + data.Command.ToString() + " with status " + data.Status.ToString());
break;
}
}
}
How are you launching the various projects and in which order ?
If I recall correctly, the "Auto hosting" provided by the WCF development tools only works in debug, and in release you have to deploy "properly".
This documentation my help out : Using the WCF Development Tools
Related
I am trying to record a video of a user desktop when he logged in via RDP, the monitoring is based on the windows service onSessionChange event, due the nature of it then I am facing what is so called Session 0 isolation, so what I am looking for is how to switch to the logged in user in order to be able record his session?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
namespace RdpMonitoringService
{
struct RdpSession
{
public int sessionId;
public string userName;
public string ipAddress;
public string sessionDateTime;
public string recordFileName;
public Recorder sessionRecorder;
public string generateRecordFileName()
{
string dirName = "RecordedSessions";
string path = AppDomain.CurrentDomain.BaseDirectory + "\\" + dirName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\" + dirName + "\\" + userName + " - " + sessionDateTime + ".mp4";
return filepath;
}
public override string ToString()
{
return "SessionId: " + sessionId + ", userName: " + userName;
}
}
public partial class RdpMonitoringService : ServiceBase
{
RdpSession onRdpSession;
Dictionary<int, RdpSession> rdpSessionList;
public RdpMonitoringService()
{
InitializeComponent();
this.CanPauseAndContinue = true;
this.CanHandleSessionChangeEvent = true;
rdpSessionList = new Dictionary<int, RdpSession>();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at: ============ " + DateTime.Now);
WriteToFile("this.CanHandleSessionChangeEvent: " + this.CanHandleSessionChangeEvent);
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
protected override void OnSessionChange(SessionChangeDescription sessionChangeDescription)
{
try {
var userInfo = TermServicesManager.GetSessionInfo(Dns.GetHostEntry("").HostName, sessionChangeDescription.SessionId);
IPAddress ipAddress = new IPAddress(userInfo.ClientAddress.Address.Skip(2).Take(4).ToArray());
if (!rdpSessionList.ContainsKey(sessionChangeDescription.SessionId))
{
onRdpSession.sessionId = sessionChangeDescription.SessionId;
onRdpSession.ipAddress = ipAddress.ToString();
onRdpSession.userName = userInfo.UserName;
onRdpSession.sessionDateTime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss");
onRdpSession.recordFileName = onRdpSession.generateRecordFileName();
//onRdpSession.sessionRecorder = Recorder.CreateRecorder();
//onRdpSession.sessionRecorder.Record(onRdpSession.generateRecordFileName());
rdpSessionList.Add(sessionChangeDescription.SessionId, onRdpSession);
}
else
{
onRdpSession = rdpSessionList[sessionChangeDescription.SessionId];
}
WriteToFile("SessionChange event");
switch (sessionChangeDescription.Reason)
{
case SessionChangeReason.SessionLogon:
case SessionChangeReason.RemoteConnect:
case SessionChangeReason.SessionUnlock:
WriteToFile("SessionChange" + DateTime.Now.ToLongTimeString() + ", SessionUnlock|RemoteConnect|SessionLogon [" + sessionChangeDescription.SessionId.ToString() + "]" + ", User: " + userInfo.UserName + ", Connect state: " + userInfo.ConnectState.ToString() + ", Client address: " + ipAddress.ToString() + ", user: " + userInfo.UserName + ", WinStationName: " + userInfo.WinStationName.ToString());
// Currently the bellow line crash the service because there is no desktop
// onRdpSession.sessionRecorder = new Recorder(new RecorderParams(onRdpSession.generateRecordFileName(), 60, SharpAvi.KnownFourCCs.Codecs.MotionJpeg, 70));
// Switch to the user desktop based on his session id and start recording
break;
case SessionChangeReason.SessionLock:
case SessionChangeReason.SessionLogoff:
case SessionChangeReason.RemoteDisconnect:
WriteToFile("SessionChange: " + onRdpSession.ToString() + ", " + DateTime.Now.ToLongTimeString() + " RemoteDisconnect|SessionLogoff|SessionLock [" + sessionChangeDescription.SessionId.ToString() + "]" + ", User: " + userInfo.UserName + ", Connect state: " + userInfo.ConnectState.ToString() + ", Client address: " + ipAddress.ToString() + ", user: " + userInfo.UserName + ", WinStationName: " + userInfo.WinStationName.ToString());
onRdpSession.sessionRecorder.Dispose();
break;
default:
break;
}
}
catch(Exception ex)
{
WriteToFile("SessionChange exception: " + ex.Message + " || " + sessionChangeDescription.SessionId.ToString() + " || " + onRdpSession.sessionId.ToString());
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
}
I have a list made by user input which is bound to a datasource class, I also have a datagridview where the data is supposed to be put into the datagrid.
private void ViewMemo_Load(object sender, EventArgs e)
{
dgvMemo.DataSource = Datasources.memorecorders;
}
this is the AddMemo class
private void btAdd_Click(object sender, EventArgs e)
{
int SerialId;
SerialId = int.Parse(txtSerialId.Text);
decimal price;
price = decimal.Parse(txtPrijs.Text);
MemoRecorder m1 = new MemoRecorder(SerialId);
m1.make = txtMerk.Text;
m1.model = txtModel.Text;
m1.priceExBtw = price;
m1.creationDate = dtProductie.Value;
foreach (MemoCartridgeType mem in Enum.GetValues(typeof(MemoCartridgeType)))
{
if (cbCartridge.SelectedValue.ToString() == mem.ToString())
{
m1.maxCartridgeType = mem;
}
}
Datasources.memorecorders.Add(m1);
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
txtMerk.Text = String.Empty;
txtModel.Text = String.Empty;
txtPrijs.Text = String.Empty;
}
but when I view the datagridview the data is not in there, what did I do wrong?
Datasources.memorecorders.Add(m1);
dgvMemo.DataSource = Datasources.memorecorders;
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
I am having a tough time with the following error:
Failed to marshal the Objective-C object 0x17109780 (type:
SMBSC_iOS_EddystoneManagerDelegate). Could not find an existing
managed instance for this object, nor was it possible to create a new
managed instance (because the type
'SMBSC.iOS.EddystoneManagerDelegate' does not have a constructor that
takes one IntPtr argument).
I have added the constructor it is looking for, but the application still crashes with this error.
I am working with the Kontakt Xamarin component.
I am creating a new scan with the following line:
manager = new KTKEddystoneManager(new EddystoneManagerDelegate() { ScanID = ID });
Here is the delegate that is causing the error:
public class EddystoneManagerDelegate : KTKEddystoneManagerDelegate
{
public static int closestRssi { get; set; }
public static string closestInstance { get; set; }
public int ScanID { get; set; }
public EddystoneManagerDelegate()
{
}
public EddystoneManagerDelegate(IntPtr handle) : base(handle)
{
}
public override void DidFailToStartDiscovery(KTKEddystoneManager manager, NSError error)
{
Console.WriteLine("Eddystone discovery failed with error: " + error.Description);
}
public override void DidUpdateEddystone(KTKEddystoneManager manager, KTKEddystone eddystone, KTKEddystoneFrameType frameType)
{
string bkpnt = "";
}
public override void DidDiscoverEddystones(KTKEddystoneManager manager, NSSet<KTKEddystone> eddystones, KTKEddystoneRegion region)
{
try
{
Console.WriteLine("");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
int i = 0;
foreach (SavedPoint p in App.discoveredBeaconList)
{
i += 1;
Console.WriteLine("Existing Beacon List: " + p.BeaconInstanceID + " - " + p.BeaconTruckDesc + " - " + p.RSSI);
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon Before Logic: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
}
else
{
Console.WriteLine("Selected Beacon Before Logic: no beacon selected");
}
App.singleOutputValue = "";
Console.WriteLine("Discovered " + eddystones.Count + " eddystones");
App.beaconTimer = DateTime.Now;
App.trackingBeaconTimer = DateTime.Now;
MessagingCenter.Send<App>(App.instance, "Output");
if (eddystones.Count == 1)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("First Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " First Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 2)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Second Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Second Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 3)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Third Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Third Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 4)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Fourth Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Fourth Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
App.closestBeaconForTracking = null;
foreach (var stone in eddystones)
{
KTKEddystone eddystone = (KTKEddystone)stone;
Console.WriteLine(eddystone.RSSI + ", " + eddystone.EddystoneUID.InstanceID);
App.outputValue += " " + eddystone.RSSI + ", " + ScanID + "; " + eddystone.EddystoneUID.InstanceID + Environment.NewLine;
App.instanceID = eddystone.EddystoneUID.InstanceID;
App.NameSpaceID = eddystone.EddystoneUID.NamespaceID;
App.rssi = eddystone.RSSI.Int32Value;
App.BeaconCount = (int)eddystones.Count;
App.lastBeaconTime = DateTime.Now.ToString();
if (App.isViewingBeacons)
{
MessagingCenter.Send<App>(App.instance, "StoneForBeaconList");
}
MapApp.Beacon beacon = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
if (beacon != null)
{
beacon.RSSI = eddystone.RSSI.Int32Value;
SavedPoint point = new SavedPoint() { BeaconID = beacon.BeaconID, BeaconInstanceID = beacon.instanceID, BeaconName = beacon.Name, BeaconNameSpaceID = beacon.namespaceID, RSSI = beacon.RSSI, BeaconTruckDesc = beacon.truckDesc };
point.LastSeenTime = DateTime.Now;
if (App.discoveredBeaconList == null)
{
App.discoveredBeaconList = new List<SavedPoint>();
}
if (!App.discoveredBeaconList.Exists(x => x.BeaconInstanceID == point.BeaconInstanceID) && beacon.RSSI != 0)
{
App.discoveredBeaconList.Add(point);
}
else
{
foreach (SavedPoint p in App.discoveredBeaconList)
{
if (p.BeaconInstanceID == point.BeaconInstanceID && beacon.RSSI != 0)
{
p.LastSeenTime = DateTime.Now;
p.RSSI = point.RSSI;
}
}
}
}
if (eddystone.RSSI.Int32Value != 0)
{
if (string.IsNullOrWhiteSpace(App.closestBeaconOutput))
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if (closestInstance == eddystone.EddystoneUID.InstanceID)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if ((int)eddystone.RSSI > closestRssi)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
//if(App.closestBeaconForTracking == null)
//{
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if(App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
//}
//if (App.closestBeaconForTracking != null)
//{
// if (App.closestBeaconForTracking.instanceID.ToLower() == eddystone.EddystoneUID.InstanceID && App.closestBeaconForTracking.namespaceID.ToLower() == eddystone.EddystoneUID.NamespaceID)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// if (eddystone.RSSI.Int32Value > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if (App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// }
//}
}
SavedPoint flipPoint = new SavedPoint();
//if(App.discoveredBeaconList.Count > 1)
//{
// try
// {
// if (App.discoveredBeaconList[0].BeaconInstanceID != App.closestBeaconForTracking.instanceID)
// {
// App.discoveredBeaconList.Insert(1, App.discoveredBeaconList[1]);
// App.discoveredBeaconList[0].BeaconInstanceID = App.closestBeaconForTracking.instanceID;
// App.discoveredBeaconList[0].BeaconNameSpaceID = App.closestBeaconForTracking.namespaceID;
// App.discoveredBeaconList[0].BeaconID = App.closestBeaconForTracking.BeaconID;
// App.discoveredBeaconList[0].RSSI = App.closestBeaconForTracking.RSSI;
// }
// }
// catch (Exception ex)
// {
// throw new Exception("Error in App.discoveredBeaconList.Count > 1");
// }
//}
//if(App.discoveredBeaconList.Count > 1)
//{
// if(App.discoveredBeaconList[0].RSSI > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking.instanceID = App.discoveredBeaconList[0].BeaconInstanceID;
// App.closestBeaconForTracking.namespaceID = App.discoveredBeaconList[0].BeaconNameSpaceID;
// App.closestBeaconForTracking.RSSI = App.discoveredBeaconList[0].RSSI;
// App.closestBeaconForTracking.truckDesc = App.discoveredBeaconList[0].BeaconTruckDesc;
// }
//}
App.singleOutputValue += eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI.Int32Value + "; ";
}
if (App.discoveredBeaconList.Count > 0)
{
SavedPoint topBeacon = App.discoveredBeaconList.OrderByDescending(c => c.RSSI).First();
MapApp.Beacon convertedBeacon = new MapApp.Beacon();
convertedBeacon.RSSI = topBeacon.RSSI;
convertedBeacon.Name = topBeacon.BeaconName;
convertedBeacon.namespaceID = topBeacon.BeaconNameSpaceID;
convertedBeacon.instanceID = topBeacon.BeaconInstanceID;
convertedBeacon.BeaconID = topBeacon.BeaconID;
convertedBeacon.truckDesc = topBeacon.BeaconTruckDesc;
App.closestBeaconForTracking = convertedBeacon;
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
MapApp.Beacon beacon = App.Database.GetBeaconByID(App.closestBeaconForTracking.instanceID, App.closestBeaconForTracking.namespaceID);
if(!string.IsNullOrWhiteSpace(beacon.truckDesc))
{
App.catchTruckDesc = beacon.truckDesc;
//Insights.Identify(App.catchTruckDesc);
}
}
else
{
Console.WriteLine("Selected Beacon: no beacon selected");
}
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("");
//if (App.closestBeaconForTracking != null && !string.IsNullOrWhiteSpace(App.closestBeaconForTracking.instanceID))
//{
// App.singleOutputValue = "Beacon found at: " + DateTime.Now + Environment.NewLine + App.closestBeaconForTracking.instanceID + " " + App.closestBeaconForTracking.RSSI;
//}
MessagingCenter.Send<App>(App.instance, "singleOutput");
MessagingCenter.Send<App>(App.instance, "UpdateStartText");
MessagingCenter.Send<App>(App.instance, "Output");
}
catch (Exception ex)
{
if (string.IsNullOrWhiteSpace(App.catchFieldDesc))
{
App.catchFieldDesc = "Null";
}
if (string.IsNullOrWhiteSpace(App.catchTruckDesc))
{
App.catchTruckDesc = "Null";
}
Insights.Report(ex, new Dictionary<string, string>() { { "DidDiscoverEddystone", ex.StackTrace }, { "Field Description", App.catchFieldDesc }, { "Truck Description", App.catchTruckDesc } }, Insights.Severity.Critical);
}
}
I have done some searching on the internet, but I have not found anything that would be relevant to my scenario. I'm sure there is an error with my code, but I do not fully understand this error.
I have read that this error can be caused by the Garbage Collector collecting the object.
What exactly does this error mean and what can I look at to attempt a fix?
Thanks!
I am using visual studio 2010 professional on windows 7 (32 bit) to connect to RFID reader LRU3000 and i encounterd this exception
Method not found: 'IntPtr
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(!!0)
kindly download the sample from the following link.
I searched the web much but i failed to know what is wrong.
Thanks In advance
NotificationSample.zip
and this is the code of the sample
this is the code of the sample :
the exception occurs at the line of code :
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
public partial class NotificationSample : Form,FedmTaskListener
{
FedmIscReader reader;
FedmTaskOption taskOpt;
long count=1;
//declaration from delegatetyp
public delegate void DelegateDisplayRecSets(int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip);
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NotificationSample());
}
//Constructor
public NotificationSample()
{
InitializeComponent();
try
{
reader = new FedmIscReader();
reader.SetTableSize(FedmIscReaderConst.BRM_TABLE, 255); // max 255 tag with each notification
taskOpt = new FedmTaskOption();
}
catch(FedmException ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
//Actualy Time propertie
private string Time
{
get
{
DateTime d;
d = DateTime.Now;
string t;
// Get the Date
if (d.Month.ToString().Trim().Length == 1)
{
t = "0" + d.Month.ToString().Trim() + "/";
}
else
{
t = d.Month.ToString().Trim() + "/";
}
if (d.Day.ToString().Trim().Length == 1)
{
t += "0" + d.Day.ToString().Trim() + "/";
}
else
{
t += d.Day.ToString().Trim() + "/";
}
t += d.Year.ToString().Trim() + " ";
// Get the time
if (d.Hour.ToString().Trim().Length == 1)
{
t += "0" + d.Hour.ToString().Trim() + ":";
}
else
{
t += d.Hour.ToString().Trim() + ":";
}
if (d.Minute.ToString().Trim().Length == 1)
{
t += "0" + d.Minute.ToString().Trim() + ":";
}
else
{
t += d.Minute.ToString().Trim() + ":";
}
if (d.Second.ToString().Trim().Length == 1)
{
t += "0" + d.Second.ToString().Trim() + ".";
}
else
{
t += d.Second.ToString().Trim() + ".";
}
if (d.Millisecond.ToString().Trim().Length == 1)
{
t += "00" + d.Millisecond.ToString().Trim() + ".";
}
else if (d.Millisecond.ToString().Trim().Length == 2)
{
t += "0" + d.Millisecond.ToString().Trim() + ".";
}
else
{
t += d.Millisecond.ToString().Trim() + ".";
}
return t;
}
}
/*****************************Methods from interface FedmTaskListener*******************/
public void OnNewNotification(int iError,string IP,uint PortNr)
{
int i;
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
//declaration from delegateobject
DelegateDisplayRecSets DisplayRecSetMethod = new DelegateDisplayRecSets(DisplayRecSets);
object[] obj = new object[11];
IAsyncResult result;
if(brmItems == null)
{
return;
}
string[] serialnumber = new string[brmItems.Length];
string[] dataBlock = new string[brmItems.Length];
string[] date = new string[brmItems.Length];
string[] time = new string[brmItems.Length];
byte[] type = new byte[brmItems.Length];
byte[] antennaNr = new byte[brmItems.Length];
byte[] input = new byte[brmItems.Length];
byte[] state = new byte[brmItems.Length];
byte[] dbsize = new byte[brmItems.Length];
Dictionary<byte, FedmIscRssiItem>[] dicRSSI = new Dictionary<byte, FedmIscRssiItem>[brmItems.Length];
long dbn;
byte dbadr;
string db;
for (i = 0; i < brmItems.Length; i++)
{ // serial number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_SNR, out serialnumber[i]);
}
// data blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_DBN, out dbn);
brmItems[i].GetData(FedmIscReaderConst.DATA_DB_ADR, out dbadr);
int j;
for (j = dbadr; j < dbn; j++)
{
brmItems[i].GetData(FedmIscReaderConst.DATA_RxDB, j, out db);
dataBlock[i] = dataBlock[i] + db + "\r\n"+"\t\t";
}
}
// Transponder Type
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TRTYPE))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_TRTYPE, out type[i]);
}
// Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
date[i] = brmItems[i].GetReaderTime().GetDate();
}
// Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
time[i] = brmItems[i].GetReaderTime().GetTime();
}
// Antenna number
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_ANT_NR, out antennaNr[i]);
}
// RSSI value
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_RSSI))
{
dicRSSI[i] = brmItems[i].GetRSSI();
}
else
{
dicRSSI[i] = new Dictionary<byte, FedmIscRssiItem>();
}
// Input
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
brmItems[i].GetData(FedmIscReaderConst.DATA_INPUT, out input[i]);
brmItems[i].GetData(FedmIscReaderConst.DATA_STATE, out state[i]);
}
}
obj[0] = brmItems.Length;
obj[1] = type;
obj[2] = serialnumber;
obj[3] = dataBlock;
obj[4] = date;
obj[5] = time;
obj[6] = antennaNr;
obj[7] = dicRSSI;
obj[8] = input;
obj[9] = state;
obj[10] = IP;
result = (IAsyncResult)Invoke(DisplayRecSetMethod, obj);
}
public void OnNewApduResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewQueueResponse(int iError)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewSAMResponse(int iError, byte[] responseData)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewReaderDiagnostic(int iError,string IP,uint PortNr)
{
}
public int OnNewMaxAccessEvent(int iError, string maxEvent, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public int OnNewMaxKeepAliveEvent(int iError, uint uiErrorFlags, uint TableSize, uint uiTableLength, string ip, uint portNr)
{
throw new Exception("The method or operation is not implemented.");
}
public void OnNewTag(int iError)
{
}
public void onNewPeopleCounterEvent(uint counter1, uint counter2, uint counter3, uint counter4, string ip, uint portNr, uint busAddress)
{
throw new Exception("The method or operation is not implemented.");
}
/************************************ENDE***********************************************/
/******************************************************Asynchrone method*****************************************************************************************************/
public void DisplayRecSets( int recSets,
byte[] type,
string[] serialNumber,
string[] dataBlock,
string[] date,
string[] time,
byte[] antennaNr,
Dictionary<byte, FedmIscRssiItem>[] dicRSSI,
byte[] input,
byte[] state,
string ip)
{
Dictionary<byte, FedmIscRssiItem> RSSIval;
FedmIscRssiItem RSSIitem;
int i;
bool bcheck;
byte antNo;
string dr;
string tr = "";
FedmBrmTableItem[] brmItems;
brmItems = (FedmBrmTableItem[])reader.GetTable(FedmIscReaderConst.BRM_TABLE);
tr += "-----------------------------------------------------------------" + "\r\n";
tr += "DATE/TIME: " + Time.ToString() + "\r\n";
tr += "-----------------------------------------------------------------" + "\r\n";
count = 1;
for (i = 0; i < recSets; i++)
{
tr += (count).ToString().Trim() + "." + " TRANSPONDER" + "\r\n";
count = count + 1;
if (type[i] >= 0)
{
//just the two last bit
dr = "0x" + FeHexConvert.IntegerToHexString(type[i]).Substring(FeHexConvert.IntegerToHexString(type[i]).Length - 2, 2);
tr += "TR-TYPE:" + "\t" + dr.ToString() + "\r\n";
}
// Output SeriaNo.
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_SNR))
{
if (serialNumber[i] != null)
{
tr += "SNR:" + "\t\t" + serialNumber[i].ToString() + "\r\n";
}
}
// Output Data Blocks
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_RxDB))
{
if (dataBlock[i] != null)
{
tr += "DB:" + "\t\t" + dataBlock[i].ToString() + "\r\n";
}
}
// Output Date
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER) || brmItems[i].IsDataValid(FedmIscReaderConst.DATA_DATE))
{
if (date[i] != null)
{
tr += "DATE:" + "\t\t" + date[i].ToString() + "\r\n";
}
}
// Output Time
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_TIMER))
{
if (time[i] != null)
{
tr += "TIME:" + "\t\t" + time[i].ToString() + "\r\n";
}
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output ANT_NR
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_ANT_NR))
{
tr += "ANT. NR:"+"\t\t" + (antennaNr[i].ToString()).Trim() + "\r\n";
}
// It is possible either to output the ANT_NR or the RSSI value (this is also important for the reader config!)
// Output RSSI
if (dicRSSI.Length > 0)
{
if (dicRSSI[i] != null)
{
RSSIval = dicRSSI[i];
for(antNo = 1; antNo<FedmBrmTableItem.TABLE_MAX_ANTENNA; antNo++)
{
bcheck = RSSIval.TryGetValue(antNo, out RSSIitem);
if (!bcheck)
continue;
tr += "RSSI of AntNr. " + "\t" + antNo.ToString() + " is " + "-" + RSSIitem.RSSI.ToString() + "dBm" + "\r\n";
}
}
}
// Output INPUT
if (brmItems[i].IsDataValid(FedmIscReaderConst.DATA_INPUT))
{
tr += "INPUT:" + "\t\t" + (input[i].ToString()).Trim() + "\r\n";
tr += "STATE:" + "\t\t" + (state[i].ToString()).Trim() + "\r\n";
}
// Output IP where notification data comes from
tr += "FROM:" + "\t\t" + ip + "\r\n";
tr += "" + "\r\n";
tr += "" + "\r\n";
}
this.textBoxData.AppendText(tr);
tr = "";
}
/**********************************************************ENDE***************************************************************************************************************/
/**************************************************Buttons**********************************************/
private void buttonListen_Click(object sender, EventArgs e)
{
if(this.buttonListen.Text == "Listen")
{
this.buttonListen.Text = "Cancel";
taskOpt.IPPort = Convert.ToInt16(this.textBoxPortNr.Text);
if(this.checkBoxAkn.Checked)
{
taskOpt.NotifyWithAck = 1;
}
else
{
taskOpt.NotifyWithAck = 0;
}
//Start from intern Thread
try
{
reader.StartAsyncTask(FedmTaskOption.ID_NOTIFICATION, this, taskOpt);
}
catch (FeReaderDriverException ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
this.buttonListen.Text = "Listen";
//End from intern thread
int val;
reader.ResetTable(FedmIscReaderConst.BRM_TABLE);
val=reader.CancelAsyncTask();
//case Deadlocks ->-4084
if (val < 0)
{
reader.CancelAsyncTask();
}
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
this.textBoxData.Clear();
count = 1;
}
/***********************************************************Ende******************************************/
private void NotificationSample_FormClosing(object sender, FormClosingEventArgs e)
{
reader.CancelAsyncTask();
Application.Exit();
}
}
I have a code for serial communication, with this code im sending values from textboxes to an device or when im testing to another PC. But when I press my "Program" button I get this error.
System.NullReferenceException was unhandled
Object reference not set to an instance of an object.
And i can catch the exception with an try catch but then i wont send my values to the device connected to my port.
This is my code:
public partial class MainForm : Form
{
private Settings _settings;
private SettingsIniFile _settingsIniFile = new SettingsIniFile();
private StringList _baudratelist = new StringList();
private StringList _systemPorts = new StringList();
private StringList _comportList = new StringList();
private Timer _comtimer = new Timer();
private ComPort _comport;
public MainForm()
{
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
//var portname = GetCurrentComPort();
}
private String GetCurrentComPort()
{
int index = _comPortComboBox.SelectedIndex;
if (index < 0)
return null;
return _comportList[index];
}
private void OnComtimerOnTick(object sender, EventArgs args)
{
foreach (var item in SerialPort.GetPortNames())
{
if (!_systemPorts.Contains(item))
{
_comtimer.Stop();
_systemPorts.Add(item);
LoadComportName();
//MessageBox.Show("The new device is connected to" + item);
_comtimer.Start();
}
}
}
private void LoadSettings(bool defaults)
{
SettingsIniFile iniFile = new SettingsIniFile();
_settings = iniFile.LoadSettings(defaults);
}
private void SaveSettings()
{
SaveTextBoxes();
_settingsIniFile.Save(_settings);
}
private void LoadTextBoxes()
{
//ACR
_startRemovalTextBox.Text = _settings.AcrStartRemoval11;
_removalTimeTextBox.Text = _settings.AcrRemovalTime12;
_removalDelayTextBox.Text = _settings.AcrRemovalDelay13;
//CLEANING
_durCleaningTextbox.Text = _settings.CleanDurCleaning21;
_timeValveOnTextbox.Text = _settings.CleanTimeValveOn22;
_timeValveOffTextBox.Text = _settings.CleanTimeValveOff23;
//CALIBRATE
_contentLeftTextBox.Text = _settings.CalibrateContentLeft31;
_calibrateLeftTextBox.Text = _settings.CalibrateCalibrateLeft33;
_contentRightTextBox.Text = _settings.CalibrateContentRight32;
_calibrateRightTextBox.Text = _settings.CalibrateCalibrateRight34;
//CONDUCTIVITY
_factorLeftTextBox.Text = _settings.ConductFactorLeft41;
_offsetLeftTextBox.Text = _settings.ConductOffsetleft42;
_factorRightTextBox.Text = _settings.ConductFactorRight43;
_offsetRightTextBox.Text = _settings.ConductOffsetRight44;
_levelLeftTextBox.Text = _settings.ConductLevelLeft45;
_levelRightTextBox.Text = _settings.ConductLevelRight46;
//GENERAL
_typeOfValveTextBox.Text = _settings.GeneralTypeOfValve51;
_indicatorTextBox.Text = _settings.GeneralIndicator52;
_inverseOutputTextBox.Text = _settings.GeneralInverseOutput53;
_restartTimeTextBox.Text = _settings.GeneralRestartTime54;
_waterTimeTextBox.Text = _settings.GeneralWaterTime55;
_gateDelayTextbox.Text = _settings.GeneralGateDelay56;
//PULSATION
_pulsationTextBox.Text = _settings.PulsationPulsationPm61;
_ratioFrontTextBox.Text = _settings.PulsationSrRatioFront62;
_ratioBackTextBox.Text = _settings.PulsationSrRatioBack63;
_stimulationTextBox.Text = _settings.PulsationStimulationPm64;
_stimFrontTextBox.Text = _settings.PulsationSrStimFront65;
_stimBackTextBox.Text = _settings.PulsationSrStimBack66;
_stimulationDurTextBox.Text = _settings.PulsationStimulationDur67;
//return _settings;
}
private void SaveTextBoxes()
{
//ACR
_settings.AcrStartRemoval11 = _startRemovalTextBox.Text;
_settings.AcrRemovalTime12 = _removalTimeTextBox.Text;
_settings.AcrRemovalDelay13 = _removalDelayTextBox.Text;
//CLEANING
_settings.CleanDurCleaning21 = _durCleaningTextbox.Text;
_settings.CleanTimeValveOn22 = _timeValveOnTextbox.Text;
_settings.CleanTimeValveOff23 = _timeValveOffTextBox.Text;
//CALIBRATE
_settings.CalibrateContentLeft31 = _contentLeftTextBox.Text;
_settings.CalibrateCalibrateLeft33 = _calibrateLeftTextBox.Text;
_settings.CalibrateContentRight32 = _contentRightTextBox.Text;
_settings.CalibrateCalibrateRight34 = _calibrateRightTextBox.Text;
//CONDUCTIVITY
_settings.ConductFactorLeft41 = _factorLeftTextBox.Text;
_settings.ConductOffsetleft42 = _offsetLeftTextBox.Text;
_settings.ConductFactorRight43 = _factorRightTextBox.Text;
_settings.ConductOffsetRight44 = _offsetRightTextBox.Text;
_settings.ConductLevelLeft45 = _levelLeftTextBox.Text;
_settings.ConductLevelRight46 = _levelRightTextBox.Text;
//GENERAL
_settings.GeneralTypeOfValve51 = _typeOfValveTextBox.Text;
_settings.GeneralIndicator52 = _indicatorTextBox.Text;
_settings.GeneralInverseOutput53 = _inverseOutputTextBox.Text;
_settings.GeneralRestartTime54 = _restartTimeTextBox.Text;
_settings.GeneralWaterTime55 = _waterTimeTextBox.Text;
_settings.GeneralGateDelay56 = _gateDelayTextbox.Text;
//PULSATION
_settings.PulsationPulsationPm61 = _pulsationTextBox.Text;
_settings.PulsationSrRatioFront62 = _ratioFrontTextBox.Text;
_settings.PulsationSrRatioBack63 = _ratioBackTextBox.Text;
_settings.PulsationStimulationPm64 = _stimulationTextBox.Text;
_settings.PulsationSrStimFront65 = _stimFrontTextBox.Text;
_settings.PulsationSrStimBack66 = _stimBackTextBox.Text;
_settings.PulsationStimulationDur67 = _stimulationDurTextBox.Text;
}
private void DefaultSettingButtonClick(object sender, System.EventArgs e)
{
LoadSettings(true);
LoadTextBoxes();
SaveSettings();
LoadComportName();
}
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void LoadComportName()
{
var availablePorts = _systemPorts;
_comPortComboBox.DataSource = null;
if (availablePorts != null && availablePorts.Any())
{
_comPortComboBox.DataSource = availablePorts;
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
private void SetBaudrate()
{
_baudratelist.Add("4600");
_baudratelist.Add("9600");
_baudratelist.Add("19200");
}
private void SendMessageTest()
{
var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
+ _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
_removalDelayTextBox.Text + "\r\n";
var Cleaningcontent ="["+ _cleaningNamelLabel.Text+"]" +"\r\n"+_cleaningIdLabel21.Text+
_durCleaningTextbox.Text + "\r\n"+ _cleaningLabelId22.Text+
_timeValveOnTextbox.Text + "\r\n"+ _cleaningLabelId23.Text+_timeValveOffTextBox.Text+"\r\n";
var Calibratecontent = "[" +_calibrateNameLabel.Text+ "]"+"\r\n"+_calibrateIDLabel31.Text+_contentLeftTextBox.Text+
"\r\n"+ _calibrateIDLabel32.Text+_calibrateLeftTextBox.Text+"\r\n"+_calibrateIDLabel33.Text+_contentRightTextBox.Text+
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
try
{
_comport.WriteBytes(array);
}
catch(Exception exc)
{
MessageBox.Show("Error {1}: "+ exc);
}
try
{
_comport.ReadBytes(array, array.Length, 1000);
}
catch(Exception exc)
{
MessageBox.Show("Error {2}" + exc);
}
//string result = Encoding.ASCII.GetString(array);
//MessageBox.Show(result);
}
}
This is my code for the communication:
namespace Communication
{
public class ComPort
{
private readonly SerialPort _serialPort;
public ComPort(string portname, int baudRate)
{
_serialPort = new SerialPort();
_serialPort.PortName = portname; <-----
_serialPort.BaudRate = baudRate;
_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.Handshake = Handshake.None;
// _serialPort.WriteBufferSize = 1;
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
_serialPort.Open();
_serialPort.ReadTimeout = 20000;
_serialPort.WriteTimeout = 20000;
}
public void Clear()
{
while (ReadByte() != -1)
continue;
}
private byte[] _array = new byte[] {0};
public void WriteByte(byte value)
{
_array[0] = value;
_serialPort.Write(_array, 0, 1);
// _serialPort.BaseStream.WriteByte(value);
_serialPort.BaseStream.Flush();
}
public void WriteBytes(byte[] array)
{
_serialPort.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length )
{
_serialPort.Write(array, index, length);
}
private int _readTimeOut = -1;
public int ReadByte(int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
return _serialPort.ReadByte();
// _serialPort.Read(array, 0, 1);
// return array[0];
}
catch (TimeoutException)
{
return -1;
}
}
public int ReadBytes(byte[] array, int length, int timeOut = 200)
{
if (timeOut != _readTimeOut)
_serialPort.ReadTimeout = _readTimeOut = timeOut;
try
{
//return _serialPort.BaseStream.ReadByte();
int bytesRead = 0;
while ( bytesRead < length )
bytesRead += _serialPort.Read(array, bytesRead, length - bytesRead);
// _serialPort.Read(array, 0, 1);
// return array[0];
return bytesRead;
}
catch (TimeoutException)
{
return -1;
}
}
/// <summary>
/// sends string followed by CR - LF
/// </summary>
/// <param name="line"></param>
public void WriteLine(String line)
{
WriteBytes(StringToBytes(line + "\r\n"));
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
public void Close()
{
try
{
_serialPort.DtrEnable = false;
_serialPort.RtsEnable = false;
_serialPort.Close();
}
catch(IOException)
{
}
}
public bool Dtr
{
get { return _serialPort.DtrEnable; }
set { _serialPort.DtrEnable = value; }
}
public bool Rts
{
get { return _serialPort.RtsEnable; }
set { _serialPort.RtsEnable = value; }
}
}
}
Can someone explain to me what the problem is?
Thanks in advance
Possible anwser:
InitializeComponent();
SetBaudrate();
LoadSettings(false);
LoadTextBoxes();
LoadComportName();
_comtimer.Tick += OnComtimerOnTick;
_comtimer.Interval = 2000;
_comtimer.Start();
LoadComportName();
Thread.Sleep(1000);
var portname = GetCurrentComPort();
_comport = new ComPort("COM6", 9600);
But when i do this another error comes around the corner:
Value cannot be null.
Parameter name: PortName
This comes in the second piece of code where the arrow is.
Probably there is not comport selected at startup, so the _comport never gets created, you should check if the comport is created before you use is: if (_comport != null) ...
Update:
I think you should create a button instead of default connecting on a combobox selection change.
public void buttonConnect_Click(object sender, EventArgs e)
{
// check if the comport is created, else show a message and return,
TryDisconnect();
var portname = GetCurrentComPort();
if (portname == null)
return;
try
{
_comport = new ComPort(portname, 9600);
}
catch(Exception exception)
{
// try to create a better message here :-)
MessageBox.Show("Something went wrong....");
}
}
public void buttonDisconnect_Click(object sender, EventArgs e)
{
TryDisconnect();
}
public void TryDisconnect()
{
if( _comport != null)
{
_comport.Dispose();
_comport = null;
}
}
Also for this:
private void SendSettingsButtonClick(object sender, System.EventArgs e)
{
// check the _comPort instance first, if not assigned, leave a message..
if(_comPort == null)
{
MessageBox.Show("The comport is not initialized");
return;
}
var availablePorts = _systemPorts;
if (availablePorts != null && availablePorts.Any())
{
SaveSettings();
SendMessageTest();
}
else
{
_comPortComboBox.Text = "No Ports are available";
}
}
I got a tip for you, try to separate the markup/construction of the message, here how you could do.
I did not change all the code, only some examples:
I would create a struct/class to hold all information
public struct AcrContentInfo
{
public string AcrName;
public string AcrId11;
public string StartRemoval;
public string AcrId12;
public string RemovalTime;
public string AcrId13;
public string RemovalDelay;
// markup the information:
public override string ToString()
{
return string.Format(
"[{0}]\r\n{1}{2}\r\n{3}{4}\r\n{5}{6}\r\n",
AcrName,
AcrId11, StartRemoval,
AcrId12, RemovalTime,
AcrId13, RemovalDelay);
}
}
private void SendMessageTest()
{
// Instead of:
//var Acrcontent = "[" + _acrNameLabel.Text + "]" + "\r\n" + _acrIdLabel11.Text + _startRemovalTextBox.Text + "\r\n"
// + _acrIdLabel12.Text + _removalTimeTextBox.Text + "\r\n" + _acrIdLabel13.Text +
// _removalDelayTextBox.Text + "\r\n";
// I would use this instead, this way it wil be easier to maintain different versions.
// The code using the struct isn't responsible for markup
// Create the struct and fillin the fields.
AcrContentInfo acrContentInfo = new AcrContentInfo
{
AcrName = _acrNameLabel.Text,
AcrId11 = _acrIdLabel11.Text,
StartRemoval = _startRemovalTextBox.Text,
AcrId12 = _acrIdLabel12.Text,
RemovalTime = _removalTimeTextBox.Text,
AcrId13 = _acrIdLabel13.Text,
RemovalDelay = _removalDelayTextBox.Text
};
// if there is a new version of the protocol, you can create something like this
// AcrContentInfoV2 acrContentInfo = new AcrContentInfoV2
// call the tostring, (create a markup)
var Acrcontent = acrContentInfo.ToString();
// --- old code ---
var Cleaningcontent = "[" + _cleaningNamelLabel.Text + "]" + "\r\n" + _cleaningIdLabel21.Text +
_durCleaningTextbox.Text + "\r\n" + _cleaningLabelId22.Text +
_timeValveOnTextbox.Text + "\r\n" + _cleaningLabelId23.Text + _timeValveOffTextBox.Text + "\r\n";
var Calibratecontent = "[" + _calibrateNameLabel.Text + "]" + "\r\n" + _calibrateIDLabel31.Text + _contentLeftTextBox.Text +
"\r\n" + _calibrateIDLabel32.Text + _calibrateLeftTextBox.Text + "\r\n" + _calibrateIDLabel33.Text + _contentRightTextBox.Text +
"\r\n" + _calibrateIDLabel34.Text + _calibrateRightTextBox.Text + "\r\n";
var Conductcontent = "[" + _conductName.Text + "]" + "\r\n" + _conductIdLabel41.Text + _factorLeftTextBox.Text +
"\r\n"
+ _conductIdLabel42.Text + _offsetLeftTextBox.Text + "\r\n" + _conductIdLabel43.Text +
_factorRightTextBox.Text + "\r\n"
+ _conductIdLabel44.Text + _offsetRightTextBox.Text + "\r\n" + _conductIdLabel45.Text +
_levelLeftTextBox.Text + "\r\n"
+ _conductIdLabel46.Text + _levelRightTextBox.Text + "\r\n";
var Generalcontent = "[" + _generalName.Text + "]" + "\r\n" + _generalIdLabel51.Text + _typeOfValveTextBox.Text +
"\r\n" +
_generalIdLabel52.Text + _indicatorTextBox.Text + "\r\n" + _generalIdLabel53.Text +
_inverseOutputTextBox.Text +
"\r\n" + _generalIdLabel54.Text + _restartTimeTextBox.Text + "\r\n" +
_generalIdLabel55.Text + _waterTimeTextBox.Text +
"\r\n" + _generalIdLabel56.Text + _gateDelayTextbox.Text + "\r\n";
var Pulsationcontent = "[" + _pulsationName.Text + "]" + "\r\n" + _pulsationIdLabel61.Text +
_pulsationTextBox.Text + "\r\n" +
_pulsationIdLabel62.Text + _ratioFrontTextBox.Text + "\r\n" +
_pulsationIdLabel63.Text + _ratioBackTextBox.Text + "\r\n" +
_pulsationIdLabel64.Text + _stimulationTextBox.Text + "\r\n" +
_pulsationIdLabel65.Text + _stimFrontTextBox.Text + "\r\n" +
_pulsationIdLabel66.Text + _stimBackTextBox.Text + "\r\n" + _pulsationIdLabel67.Text +
_stimulationDurTextBox.Text + "\r\n";
// instad of:
//byte[] array = ComPort.StringToBytes(2+"\r\n"+Acrcontent+"\r\n"+Cleaningcontent + "\r\n" + Calibratecontent+"\r\n"+Conductcontent+"\r\n"+Generalcontent+"\r\n"+Pulsationcontent+3);
// I always try not to make very long lines of code.
// A stringbuilder is much more efficient building strings.
// I would:
StringBuilder sb = new StringBuilder();
sb.AppendLine("2");
sb.AppendLine("Acrcontent");
sb.AppendLine("Cleaningcontent");
sb.AppendLine("Calibratecontent");
sb.AppendLine("Conductcontent");
sb.AppendLine("Generalcontent");
sb.AppendLine("Pulsationcontent");
sb.AppendLine("3");
// why make the comport class responsible for the encoding type. _ComPort.StringToBytes_
byte[] array = Encoding.UTF8.GetBytes(sb.ToString());
try
{
_comport.WriteBytes(array);
// only read when write was succeed?
_comport.ReadBytes(array, array.Length, 1000);
}
catch (Exception exc)
{
MessageBox.Show("Error {1}: " + exc);
}
}
These are only my ideas, and meant to be constructive. (other point of view) Happy codeing..
You have to instantiate _comport before calling a method or accessing a property on it.
maybe in
var portname = GetCurrentComPort();
if (portname != null)
{
_comport = new ComPort("COM6", 9600);
}
portname is null then _comport not instantiated. you can trace it and check that if it has a value or not.
Yes assign a value to _comport like
_comport=null;