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!
Related
I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I´m trying to figure out how to implement a progress bar in my application.
I´ve read some articles like this How to correctly implement a BackgroundWorker with ProgressBar updates?, and I caught how it works. My doubt is how will I call and update the progressbar.xaml since I´m executing the sql in the PendenciaController.cs.
PendenciaConsulta.xaml.cs
Task.Factory.StartNew(() =>
{
Progress<long> progress = null;
progress = new Progress<long>((i) =>
{
try
{
Dispatcher.Invoke(() => { PBar.Value = i; });
}
catch { }
});
pendenciaController = new PendenciaController(progress);
pendenciaController.PendenciaConsultar((bool)chkFollowUp.IsChecked); //The error occurs here
pendenciaController.PopularListas();
StatusController statusController = new StatusController();
ObservableCollection<Status> ListaStatus = null;
dataContext = new DataContext();
this.listaPendencia = this.pendenciaController.ListaPendencia;
ListaStatus = statusController.StatusConsultar();
this.DataContext = dataContext;
dtgPendencia.ItemsSource = this.listaPendencia;
lblQuantidadeRegistros.Content = "Quantidade de registros: " + this.listaPendencia.Count;
PopularCombos();
});
PendenciaController.cs
private Progress<long> _progress;
public PendenciaController(Progress<long> progress)
{
_progress = progress;
}
public void PendenciaConsultar(bool followUp)
{
OleDbConnection conn = null;
#region Select e conversão do DataSet
try
{
conn = new OleDbConnection(Conexao.getConexao());
conn.Open();
//Select da tabela tblPendencia
StringBuilder cmd = new StringBuilder();
cmd.Append("SELECT P.pendenciaId, " +
" P.contrato, " +
" P.adAm, " +
" P.diasDecorridos, " +
" P.corretora, " +
" P.produto, " +
" P.clienteNome, " +
" P.clienteCnpj, " +
" P.aberturaData, " +
" P.pendenciaTipo, " +
" P.lastro, " +
" P.garantiaDescricao, " +
" P.observacao, " +
" P.vencimentoData, " +
" P.liquidacaoData, " +
" P.rating, " +
" P.operacaoValor, " +
" P.pendenciaNivel, " +
" P.pendenciaValorFator, " +
" P.porContrato, " +
" P.officer, " +
" P.centroCusto, " +
" P.isCritico, " +
" P.statusId, " +
" P.clienteGrupo, " +
" P.followUp, " +
" P.carenciaInicio, " +
" P.carenciaFim, " +
" P.moeda, " +
" P.documentoTipo, " +
" P.tipo, " +
" (SELECT S.statusDescricao " +
" FROM tblStatus S " +
" WHERE S.statusId = P.statusId) as statusDescricao" +
" FROM tblPendencia P");
if (!followUp)
{
cmd.Append(" WHERE ((P.followUp <= NOW()) " +
" OR (P.followUp IS NULL))");
}
else
{
cmd.Append(" WHERE ((P.followUp <= NOW()) " +
" OR (P.followUp >= NOW()) " +
" OR (P.followUp IS NULL))");
}
OleDbDataAdapter da = new OleDbDataAdapter(cmd.ToString(), conn);
DataSet ds = new DataSet();
da.Fill(ds, "tblPendencia");
DataTable dt = new DataTable();
dt = ds.Tables["tblPendencia"];
Pendencia pendencia = null;
this.ListaPendencia = new List<Pendencia>();
if (ds.Tables != null && ds.Tables[0].Rows.Count > 0)
{
//foreach (DataRow dtRow in ds.Tables[0].Rows)
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dtRow = ds.Tables[0].Rows[i];
pendencia = new Pendencia();
pendencia.AberturaData = dtRow["aberturaData"].ToString();
pendencia.AdAm = dtRow["adAm"].ToString();
pendencia.CentroCusto = dtRow["centroCusto"].ToString();
pendencia.ClienteCnpj = dtRow["clienteCnpj"].ToString();
pendencia.ClienteNome = dtRow["clienteNome"].ToString();
pendencia.Contrato = dtRow["contrato"].ToString();
pendencia.Corretora = dtRow["corretora"].ToString();
pendencia.DiasDecorridos = dtRow["diasDecorridos"].ToString();
pendencia.GarantiaDescricao = dtRow["garantiaDescricao"].ToString();
pendencia.Lastro = dtRow["lastro"].ToString();
pendencia.LiquidacaoData = dtRow["liquidacaoData"].ToString();
pendencia.Observacao = dtRow["observacao"].ToString();
pendencia.Officer = dtRow["officer"].ToString();
pendencia.OperacaoValor = dtRow["operacaoValor"].ToString();
pendencia.PendenciaId = Convert.ToInt32(dtRow["pendenciaId"]);
pendencia.PendenciaNivel = dtRow["pendenciaNivel"].ToString();
pendencia.PendenciaValorFator = dtRow["pendenciaValorFator"].ToString();
pendencia.StatusId = String.IsNullOrEmpty(dtRow["statusId"].ToString()) ? 0 : Convert.ToInt32(dtRow["statusId"]);
pendencia.Produto = dtRow["produto"].ToString();
pendencia.Rating = dtRow["rating"].ToString();
pendencia.PendenciaTipo = dtRow["pendenciaTipo"].ToString();
pendencia.VencimentoData = dtRow["vencimentoData"].ToString();
pendencia.ClienteGrupo = dtRow["clienteGrupo"].ToString();
pendencia.FollowUp = dtRow["followUp"].ToString();
pendencia.CarenciaInicioData = dtRow["carenciaInicio"].ToString();
pendencia.CarenciaFimData = dtRow["carenciaFim"].ToString();
pendencia.DocumentoTipo = dtRow["documentoTipo"].ToString();
pendencia.StatusDescricao = dtRow["statusDescricao"].ToString();
pendencia.PorContratoDescricao = dtRow["porContrato"].ToString();
pendencia.Moeda = dtRow["moeda"].ToString();
pendencia.Tipo = dtRow["tipo"].ToString();
pendencia.IsCritico = Convert.ToBoolean(dtRow["isCritico"]);
pendencia.StatusId = String.IsNullOrEmpty(dtRow["statusId"].ToString()) ? 0 : Convert.ToInt32(dtRow["statusId"]);
this.ListaPendencia.Add(pendencia);
((IProgress<long>)(_progress)).Report((long)i);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { conn.Close(); }
#endregion
}
Thanks.
You should use Progress<T> Class and Task.
Example :
public partial class Window25 : Window
{
public Window25()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
Progress<long> progress = null;
progress = new Progress<long>((i) =>
{
try
{
// Update ProgressBar
Dispatcher.Invoke(() => { PBar.Value = i; });
}
// handle pre-mature closing of window (task cancellation)
catch { }
});
Controller c = new Controller(progress);
c.Do();
}
);
}
}
public class Controller
{
Progress<long> _progress;
public Controller(Progress<long> progress)
{
_progress = progress;
}
public void Do()
{
for (long s = 0; s < 99999; ++s)
((IProgress<long>)(_progress)).Report((long)s);
}
}
Progress class
Async in 4.5: Enabling Progress and Cancellation in Async APIs
See if this solves your problem.
In my opinion you should raise progress events from PendenciaController and handle them into PendenciaConsulta to update the ProgressBar.
this is my code
public void ClosePort()
{
if (comPort.IsOpen == true)
{
//e.Cancel = true; //cancel the fom closing
Thread CloseDown = new Thread(new ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang
//comPort.DiscardInBuffer();
//comPort.DiscardOutBuffer();
//comPort.Dispose();
CloseDown.Start(); //close port in new thread to avoid hang
DisplayData(MessageType.Error, "Port communication has been closed" + " " + DateTime.Now + "\n");
}
}
private void CloseSerialOnExit()
{
try
{
comPort.Dispose();
comPort.DiscardInBuffer();
comPort.DiscardOutBuffer();
comPort.Close(); //close the serial port
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //catch any serial port closing error messages
}
BeginInvoke(new EventHandler(NowClose)); //now close back in the main thread
}
private void NowClose(object sender, EventArgs e)
{
comPort.Dispose();
comPort.DiscardInBuffer();
comPort.DiscardOutBuffer();
comPort.Close(); //now close the form
}
public void BeginInvoke(Delegate method)
{
}
why the serial port not close? and when i hit [X] Icon and exit the program, program stil detect in task manager.
In normal case, the above code is work. But when the serial do write or read data the code is not work, not close the serial port, any suggestion for this case? thanks for help and solution.
private void cmdClose_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure to disconnect?", "WARNING",
MessageBoxButtons.OKCancel);
switch (result)
{
case DialogResult.OK:
{
comm.ClosePort();
cmdRefresh.Enabled = true;
cmdNewReport.Enabled = true;
cboPort.Enabled = true;
cboBaud.Enabled = true;
cboStop.Enabled = true;
cboParity.Enabled = true;
cboData.Enabled = true;
label9.Text = " ";
label11.Text = " ";
cmdOpen.Enabled = true;
//cmdSend.Enabled = true;
cmdClose.Enabled = false;
break;
}
case DialogResult.Cancel:
{
break;
}
}
}
the above code is my button code which calling the comPort.ClosePort();
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//determine the mode the user selected (binary/string)
switch (CurrentTransmissionType)
{
//user chose string
case TransmissionType.Text:
//read data waiting in the buffer
string msg = comPort.ReadExisting();
//display the data to the user
DisplayData(MessageType.Incoming, msg + "\n");
break;
//user chose binary
case TransmissionType.Hex:
//retrieve number of bytes in the buffer
int OpeCode = 0;
int RequestID = 0;
int Product = 0;
int IPenNo = 0;
string status = " ";
while (true)
{
DateTime time = DateTime.Now; // Use current time.
string format = "dddddddd, MMMMM d, yyyy HH:mm:ss";
string currentTime = time.ToString(format);
byte[] TrueData = new byte[256];
try
{
int bytes = comPort.BytesToRead;
if (bytes == 0) continue;
//create a byte array to hold the awaiting data
byte[] comBuffer = new byte[bytes];
comPort.Read(comBuffer, 0, bytes);
DisplayData(MessageType.Incoming, "Hexa :" + ByteToHex(comBuffer) + "\n");
DisplayData(MessageType.Incoming, "Byte :" + bytes.ToString() + "\n");
if (bytes == 3)
{
var lines = File.ReadAllLines(Fullpath).ToList();
// Remove as many lines as you'd like from the end
if (lines.Count > 2)
{
lines.RemoveRange(lines.Count - 2, 2);
}
// Iterate backwards through the list until we've updated 2 (or more or less) lines
var linesUpdated = 0;
for (var i = lines.Count - 1; i >= 0 && linesUpdated < 1; i--)
{
if (lines[i].Contains("OK"))
{
lines[i] = lines[i].Replace("OK", "NG");
linesUpdated++;
}
}
File.WriteAllLines(Fullpath, lines.ToArray());
//DisplayData(MessageType.Incoming, "NG" + "\n");
}
if (bytes == 2)
{
continue;
}
int etx_ok = 0;
for (int i = 0; i < bytes; i++)
{
if (comBuffer[i] == 0x02)
{
//DisplayData(MessageType.Incoming, "cek II:" + checkStatus + "\n");
int length = comBuffer[i + 1];
DisplayData(MessageType.Incoming, "Length=" + length.ToString() + "\n");
if (String.IsNullOrEmpty(bytes.ToString()))
{
status = "NG";
}
if (length + i + 1 != bytes && status == " ")
{
DisplayData(MessageType.Incoming, length.ToString() + " " + i.ToString() + " " + bytes.ToString() + " ");
status = "NG";
DisplayData(MessageType.Incoming, "ERROR \n");
//break;
}
else
{
status = "OK";
}
DisplayData(MessageType.Incoming, "ini statusnya : " + status + "\n");
if (comBuffer[length + i - 1] == 0x03)
{
DisplayData(MessageType.Incoming, "ETX OK\n");
etx_ok = 1;
OpeCode = comBuffer[i + 2];
DisplayData(MessageType.Incoming, "OpeCode=" + OpeCode.ToString() + ",");
RequestID = comBuffer[i + 3];
DisplayData(MessageType.Incoming, "RequestID=" + RequestID.ToString() + ",");
int StoreCode = comBuffer[i + 4];
DisplayData(MessageType.Incoming, "StoreCode=" + StoreCode.ToString() + ",");
int ProductBatteryTraining = comBuffer[i + 5];
DisplayData(MessageType.Incoming, "ProductBatteryTraining=" + ProductBatteryTraining.ToString() + ",");
Product = ProductBatteryTraining >> 4;
DisplayData(MessageType.Incoming, " Product=" + Product.ToString() + ",");
int Battery = ProductBatteryTraining & 4;
DisplayData(MessageType.Incoming, " Batery=" + Battery.ToString() + ",");
int Training = ProductBatteryTraining & 1;
DisplayData(MessageType.Incoming, " Training=" + Training.ToString() + ",");
IPenNo = comBuffer[i + 6];
DisplayData(MessageType.Incoming, "IPenNo=" + IPenNo.ToString() + ",");
int CrcCalc = comBuffer[length + i] + 0x11;
for (int j = 7, k = 0; j < length; j++, k++)
{
//syswrite STDOUT , "TrueDataX " . $length . "\n";
DisplayData(MessageType.Incoming, "TrueDataX " + length.ToString() + "," + "\n");
TrueData[k] = comBuffer[i + j];
}
if (OpeCode == 0x63)
{
byte[] replyStr = new byte[] {
Convert.ToByte(0x45), Convert.ToByte(0x53), Convert.ToByte(0x4c), Convert.ToByte(0x14), Convert.ToByte(0x09), Convert.ToByte(0x00), //#Length Change
Convert.ToByte(0x02), Convert.ToByte(0x08),Convert.ToByte(OpeCode), Convert.ToByte(RequestID),Convert.ToByte(Product-1), Convert.ToByte(IPenNo), //#Reply Header Data
Convert.ToByte(0x00), //#Reply Status
Convert.ToByte(0x03), Convert.ToByte(CrcCalc), //#Footer Data
Convert.ToByte(0xcc), Convert.ToByte(0xcc)
};
comPort.Write(replyStr, 0, replyStr.Length);
//write file to textfile
//string path = #"d:\yosafat\testfile\tes1_Friday0916201614.33.txt";
string IPenID = IPenNo.ToString();
string appendText = ("IPen ID \t" + "Datetime\t\t\t\t\t" + "Status" + Environment.NewLine + IPenID + "\t\t" + currentTime + "\t\t" + status + Environment.NewLine);
File.AppendAllText(Fullpath, appendText);
}
}
else
{
OpeCode = 0;
//syswrite STDOUT , "ETX Bad Data" . $length . "\n";
DisplayData(MessageType.Incoming, "ETX Bad Data" + length.ToString() + "\n");
break;
}
}
if (etx_ok == 1)
{
break;
}
}
}
catch (Exception) { }
}
}
}
I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.
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;