Serial port data savings in .ini file C# - c#

I have built application forms that use a serial port C#.
I want to save the last serial port number used and COM data in the .ini file when I close the executable.
So, I can use the same data for the next use of the application
private void btnSave_Click(object sender, EventArgs e)
{
try
{
_Ser.PortName = cBoxPort.Text;
_Ser.BaudRate = Convert.ToInt32(cBoxBaud.Text);
_Ser.DataBits = Convert.ToInt32(cBoxDatabits.Text);
_Ser.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cBoxStopBits.Text);
_Ser.Parity = (Parity)Enum.Parse(typeof(Parity), cBoxParitybits.Text);
this.Close();
string[] data = { cBoxPort.Text, cBoxDatabits.Text, cBoxStopBits.Text, cBoxParitybits.Text };
}
catch (Exception err)
{
MessageBox.Show(err.Message, ("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Configuration has been saved","Status");
}

I think the best way is for you to serialize the object with the data you want to save and to retrieve it, just deserialize the object.
Here is an example of how to do it with XML file:How to serialize/deserialize simple classes to XML and back
A simpler way is with JSON, here is an example applied to your code.
You will need the reference Newtonsoft.Json;
_Ser.PortName = cBoxPort.Text;
_Ser.BaudRate = Convert.ToInt32(cBoxBaud.Text);
_Ser.DataBits = Convert.ToInt32(cBoxDatabits.Text);
_Ser.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cBoxStopBits.Text);
_Ser.Parity = (Parity)Enum.Parse(typeof(Parity), cBoxParitybits.Text);
Serializing the object to a .json file
string dataFile = #"c:\DataFile.json";
string jsonString = JsonConvert.SerializeObject(_Ser);
File.WriteAllText(dataFile, jsonString);
Retrieving data from a .json file
string recoverdata = File.ReadAllText(dataFile);
_Ser = JsonConvert.DeserializeObject<[put here the type of your object "_ser"] >(recoverdata);

you need to generate a json and then save the port you last committed on that json.
When the program opens, you should read the last recorded port from the json and open the port again.

Related

is there a way to send data from unity c# and python program?

i have a unity project and i want to send the position of the object alongside some other data from it to a python project that will have a neural network then sending the output back to unity.
the data that i need to send from unity to python is the position of the object (x,y,z) and some bools maybe some strings, the output of the neural network will be (w,a,s,d), what i did is that i wrote the data to a text file and the python read the data from that file but this way will always produce an error because the python will need to read the file while c# is writing which will produce IO error, another way is using clipboard but this will be viable for small data but won't be good in my case.
c# code
void Update()
{
System.IO.StreamWriter saveFile = new System.IO.StreamWriter("Reading/Positions/PlanePos.txt", false);
saveFile.Write(this.transform.position);
saveFile.Close();
System.IO.StreamWriter saveFile2 = new System.IO.StreamWriter("Reading/Positions/done.txt", false);
if (this.transform.position.y> 2)
{
leftground = true;
}
if (leftground)
{
if (this.transform.position.y < 2)
{
saveFile2.Write("done");
saveFile2.Flush();
dones.text = "done";
}
else
{
saveFile2.Write("air");
saveFile2.Flush();
dones.text = "air";
}
}
else
{
saveFile2.Write("ground");
saveFile2.Flush();
dones.text = "ground";
}
saveFile2.Close();
}
Python Code:
def read_data():
# reading from file
file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/PlanePos.txt", "r")
planepos = file.readline()
file.close()
file = open("D:/Cs/Grad/Tests/airplane test/Reading/Positions/AirportPosition.txt", "r")
airportpos = file.readline()
file.close()
# ==================================================================
# spliting and getting numbers
#plane_X, plane_Y, plane_Z = map(float, planepos.strip('() \n').split(','))
#airport_X, airport_Y, airport_Z = map(float, airportpos.strip('() \n').split(','))
planepos=planepos.strip('() \n').split(',')
airportpos=airportpos.strip('() \n').split(',')
return planepos[0], planepos[1], planepos[2], airportpos[0], airportpos[1], airportpos[2]
i except a way to send data from unity to python and vice versa like a server or anything that can do this.

Opening a document from Imanage in Word 2016

I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();

Save the CheckBox state

I need to know if is possible to save the state of a CheckBox in C#? I mean if I check the CheckBox and close the program, once I restart the program the CheckBox will still stay checked. Is it possible to?
This is rather a general question. You need to serialise the state yourself somehow, but how, and where to depends on a lot of things.
Possibly take a look at a Settings file for a simple start.
For this, you will need to record the state of the CheckBox yourself. For example, you could store the value in an XML document that would contain your application's UI states. An example, in a very simplistic form, you could do the following:
// ... as the application is closing ...
// Store the state of the check box
System.IO.File.WriteAllText(#"C:\AppFile.txt", this.CheckBox1.IsChecked.ToString());
// ...
// ... as the application is being initialized ...
// Read the state of the check box
string value = System.IO.File.ReadAllText(#"C:\AppFile.txt");
this.CheckBox1.IsChecked = bool.Parse(value);
As you can see, this simply stores the value in a file and reads it back in during initialization. This is not a great way of doing it, but it demonstrates a possible process to follow.
The easiest way of doing this would be to use a config XML file. You can add this very easily through visual studio, there is no need to use registry and it can be used if the app is portable as the settings are saved with the program. A tutorial of how to set this up is here:
http://www.sorrowman.org/c-sharp-programmer/save-user-settings.html
If you are using Web application cookie enabled and storing the information in cookie then it is possible.
You can checkout http://www.daniweb.com/web-development/aspnet/threads/30505
http://asp.net-tutorials.com/state/cookies/
In C# you can use the Settings file. Information how to use it can be found here : http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx
If you wanted to save this to the Registry you could do something like this
RegistryKey Regkey = "HKEY_CURRENT_USER\\Software\\MyApplication";
RegKey.SetValue("Checkbox", Checkbox.Checked);
but personally I would save it to the .Config file
Here is an example of how to do it using the Config File if you so desire
private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
private static XmlDocument loadConfigDocument()
{
XmlDocument docx = null;
try
{
docx = new XmlDocument();
docx.Load(getConfigFilePath());
return docx;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
private void rem_CheckedChanged(object sender, EventArgs e)
{
if (rem.Checked == true)
{
rem.CheckState = CheckState.Checked;
System.Xml.XmlDocument docx = new System.Xml.XmlDocument();
docx = loadConfigDocument();
System.Xml.XmlNode node;
node = docx.SelectSingleNode("//appsettings");
try
{
string key = "rem.checked";
string value = "true";
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[#key='{0}']", key));
if (elem != null)
{
elem.SetAttribute("value", value);
}
else
{
elem = docx.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
docx.Save(getConfigFilePath());
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
}
}
I would use Settings like this:
Assuming a boolean setting called boxChecked has been created.
//if user checks box
Properties.Settings.Default.boxChecked = true;
Properties.Settings.Default.Save();
//...
//when the program loads
if(Properties.Settings.Default.boxChecked)
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}

SAXParser equivalent in C#

I have below java code , I need to convert these in C#, Kindly help me ..
public class Configuration {
private ConfigContentHandler confHandler;
public Configuration() {
}
public boolean parseConfigFile() throws Exception {
boolean bReturn = true;
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
System.out.println("*** Start parsing");
try {
confHandler = new ConfigContentHandler(100);
// Configuration file must be located in main jar file folder
// Set the full Prosper file name
String sConfigFile = "configuration.xml";
// Get abstract (system independent) filename
File fFile = new File(sConfigFile);
if (!fFile.exists()) {
System.out.println("Could not find configuration file " + sConfigFile + ", trying input parameters.");
bReturn = false;
} else if (!fFile.canRead()) {
System.out.println("Could not read configuration file " + sConfigFile + ", trying input parameters.");
bReturn = false;
} else {
parser.parse(fFile, confHandler);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Input error.");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("*** End parsing");
return bReturn;
}
Thanks
C# native XML parser XmlReader doesn't support SAX and is forward-only. You may take a look at this article presenting some specific points about it. You could simulate a SAX parser using XmlReader. If it doesn't suit your needs you could also use XDocument which is a different API for working with XML files in .NET. So to conclude there's no push XML parser built into .NET framework so you might need to use a third party library or COM Interop to MSXML to achieve this if you really need an event driven parser.
I used SAX for .NET in two projects successfully in the past.
http://saxdotnet.sourceforge.net/

Transfer file from Windows Mobile device to...anywhere

I can't seem to find a solution to this issue. I'm trying to get my Compact Framework application on Windows Mobile 6 to have the ability to move a file on its local filesystem to another system.
Here's the solutions I'm aware of:
FTP - Problem with that is most of
the APIs are way to expensive to use.
HTTP PUT - As far as I have been able to find, I can't use anonymous PUT with IIS7, and that's the web server the system is running. (An extreme workaround for this would be to use a different web server to PUT the file, and have that other system transfer it to the IIS system).
Windows share - I would need authentication on the shares, and I haven't seen that a way to pass this authentication through windows mobile.
The last resort would be to require that the devices be cradled to transfer these files, but I'd really like to be able to have these files be transferred wirelessly.
FTP: define "too expensive". Do you mean performance or byte overhead or dollar cost? Here's a free one with source.
HTTP: IIS7 certainly supports hosting web services or custom IHttpHandlers. You could use either for a data upload pretty easily.
A Windows Share simply requires that you to P/Invoke the WNet APIs to map the share, but it's not terribly complex.
I ended up just passing information to a web server via a PHP script.
The options provided above just didn't work out for my situation.
Here's the gist of it. I've got some code in there with progress bars and various checks and handlers unrelated to simply sending a file, but I'm sure you can pick through it. I've removed my authentication code from both the C# and the PHP, but it shouldn't be too hard to roll your own, if necessary.
in C#:
/*
* Here's the short+sweet about how I'm doing this
* 1) Copy the file from mobile device to web server by querying PHP script with paramaters for each line
* 2) PHP script checks 1) If we got the whole data file 2) If this is a duplicate data file
* 3) If it is a duplicate, or we didn't get the whole thing, it goes away. The mobile
* device will hang on to it's data file in the first case (if it's duplicate it deletes it)
* to be tried again later
* 4) The server will then process the data files using a scheduled task/cron job at an appropriate time
*/
private void process_attempts()
{
Uri CheckUrl = new Uri("http://path/to/php/script?action=check");
WebRequest checkReq = WebRequest.Create(CheckUrl);
try
{
WebResponse CheckResp = checkReq.GetResponse();
CheckResp.Close();
}
catch
{
MessageBox.Show("Error! Connection not available. Please make sure you are online.");
this.Invoke(new Close(closeme));
}
StreamReader dataReader = File.OpenText(datafile);
String line = null;
line = dataReader.ReadLine();
while (line != null)
{
Uri Url = new Uri("http://path/to/php/script?action=process&line=" + line);
WebRequest WebReq = WebRequest.Create(Url);
try
{
WebResponse Resp = WebReq.GetResponse();
Resp.Close();
}
catch
{
MessageBox.Show("Error! Connection not available. Please make sure you are online.");
this.Invoke(new Close(closeme));
return;
}
try
{
process_bar.Invoke(new SetInt(SetBarValue), new object[] { processed });
}
catch { }
process_num.Invoke(new SetString(SetNumValue), new object[] { processed + "/" + attempts });
processed++;
line = dataReader.ReadLine();
}
dataReader.Close();
Uri Url2 = new Uri("http://path/to/php/script?action=finalize&lines=" + attempts);
Boolean finalized = false;
WebRequest WebReq2 = WebRequest.Create(Url2);
try
{
WebResponse Resp = WebReq2.GetResponse();
Resp.Close();
finalized = true;
}
catch
{
MessageBox.Show("Error! Connection not available. Please make sure you are online.");
this.Invoke(new Close(closeme));
finalized = false;
}
MessageBox.Show("Done!");
this.Invoke(new Close(closeme));
}
In PHP (thoroughly commented for your benefit!):
<?php
//Get the GET'd values from the C#
//The current line being processed
$line = $_GET['line'];
//Which action we are doing
$action = $_GET['action'];
//# of lines in the source file
$totalLines = $_GET['lines'];
//If we are processing the line, open the data file, and append this new line and a newline.
if($action == "process"){
$dataFile = "tempdata/SOME_KIND_OF_UNIQUE_FILENAME.dat";
//open the file
$fh = fopen($dataFile, 'a');
//Write the line, and a newline to the file
fwrite($fh, $line."\r\n");
//Close the file
fclose($fh);
//Exit the script
exit();
}
//If we are done processing the original file from the C# application, make sure the number of lines in the new file matches that in the
//file we are transferring. An expansion of this could be to compare some kind of hash function value of both files...
if($action == "finalize"){
$dataFile = "tempdata/SOME_KIND_OF_UNIQUE_FILENAME.dat";
//Count the number of lines in the new file
$lines = count(file($dataFile));
//If the new file and the old file have the same number of lines...
if($lines == $totalLines){
//File has the matching number of lines, good enough for me over TCP.
//We should move or rename this file.
}else{
//File does NOT have the same number of lines as the source file.
}
exit();
}
if($action == "check"){
//If a file with this unique file name already exists, delete it.
$dataFile = "tempdata/SOME_KIND_OF_UNIQUE_FILENAME.dat";
if(file_exists($dataFile)){
unlink($dataFile);
}
}
?>

Categories