|
Perhaps to add to what Luc is saying... perhaps you want to use System.Text.Encoding.ASCII.GetBytes ( string ) ?
|
|
|
|
|
Hi,
If you mean the following, this is not working either.
string asciiString = "abc";
byte[] buff = System.Text.Encoding.ASCII.GetBytes(asciiString);
serialPort1.Write(buff, 0, buff.Length);
|
|
|
|
|
turbosupramk3 wrote: If I send "pin1=2" via the simpleserial object, it is received
and the microchip code reacts. When I try and send it through the below method,
the data is not received by the microchip and it does not react.
Like Bob, I can't see any functional difference between the simpleserial code and your version.
Here are a few random ideas which may help.
1) Are you sending the correct message?
When you use simpleserial and type in the characters individually, how does the device know when it has a complete message? Does it respond as soon as the 2 of pin1=2 is typed in or do you have enter something more?
{EDIT} I see from your response to Luc that you must have been pressing the enter key.
2) Is the loop sending the message too quickly?
Test the effect of a delay (~300ms) between each character to simulate the transmission rate of a typed message.
foreach (char chr in lineToWrite)
{
char[] buff = new char[1];
buff[0] = chr;
serialPort1.Write(buff, 0, 1);
System.Threading.Thread.Sleep(300);
}
3) Is the port configured correctly?
In the simple serial class insert some code to log the values of all properties after the port has been opened.
e.g.
port.Open();
Debug.Print("Baud {0}", port.BaudRate);
and then make sure that your code uses the same settings.
Alan.
|
|
|
|
|
Hi Alan,
Thanks for the reply. I had to add the CR and verify some things. The port is configured correctly. The loop was sending data too quickly when I had the pipe clogged up with debug info, once I cleared that, 100mS resolution was good, and I believe that is sufficient, I may try 50mS later on.
It was responding to a single character push, without having to hit the enter key, with the event key press trigger. I'm not quite sure why I had to add a CR, maybe you have a theory?
|
|
|
|
|
In a C#.net 2010 application that I am suppose to maintain (since I am new to working with this language), I find code that looks like the following:
[^]try
{ //do something}
catch (ex){} [^]
In the visual studio ide, I see a a curly green under the ex.
I also do not see any using statement that I would think applies.
Thus can you tell me if this kind of code really catches any errors? if so can you explain it to me?
I put this kind of code around some of my new code and everything falls into the catch block.
Thus can you tell me what a "good" try catch block should look like aand what namespace should be included in the
using statement?
|
|
|
|
|
0.
your example is pretty bad, e.g. it is missing the type of the exception you're catching.
1.
the green curly indicates the variable "ex" isn't used anywhere. If you aren't going to use it, leave out the variable's name, so write:
...
catch(FileNotFoundException) {
log("Saving the customer data failed because the necessary file wasn't there");
}
2.
a good try-catch construct would have one or more regular statements in the try-block, and at least one in the catch-block.
3.
an empty catch block most often is very bad (it "swallows" the error information without leaving a trace). One should only catch things one can deal with, and it is always wise to log the exception.
4.
There is no connection between try-catch and using .
5.
And of course the C# reference material has told you you can have 0 or more catch-blocks and 0 or 1 finally-block; all with good examples in the doc.
|
|
|
|
|
Luc Pattyn wrote: And of course the C# reference material has told you
But of course...
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman
|
|
|
|
|
When I was talking about the using statement, I was wanting to know what namespace should be used.
|
|
|
|
|
"Exception" is part of the System namespace. (ie. System.Exception)
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
Assuming you have a typical set of usings (Visual always gives you using.System to start with), there is nothing you have to add.
|
|
|
|
|
dcof wrote: catch (ex){}
You have to specify wich type of exception may handle by this try-catch. List of Exception
catch (Exception ex){}
dcof wrote: curly green under the ex.
Curly green indicate that variable is declared but not used inside catch block.So throw exception.
catch (Exception ex)
{
throw ex;
}
|
|
|
|
|
Your advice to just throw the exception isn't the best thing you can do. You should never catch an exception and rethrow it without doing something else with the exception. The reason for this is because all you have done is recreate what would happen if you didn't have any exception handling at all.
|
|
|
|
|
All you've done is get back to the same situation plus paid the cost of throwing another exception! So yeah, don't do that.
|
|
|
|
|
Luc gave you a very good answer.
Here's a quick simple example, but try the MSDN site or maybe the articles here on CP for proper exception handling.
try{
}
catch(Exception ex){
}
finally{
}
tip: Do not show technical Exception messages to the user. Instead, depending on the catch, form a nice message explaining what happened and if they need to take action.
Hope this helps.
V.
|
|
|
|
|
Hey,
I've been stuck with this problem quite a while now, so I figured maybe you can help me?
I have a program that is being started by creating a new instance of a class, and then call it's start method, that is starting a timer. When developing, I've been using a win forms GUI to press the button to start, and that has been working fine. Now when the program is done and works fine, I want to make it a win service. So I simply added a win service to the project. But, even though the service does exatly the same thing as the forms GUI, the program doesn't start. This is the code..
private FileWatcher fw;
public MyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
fw = new FileWatcher();
fw.Start();
}
protected override void OnStop()
{
fw.Stop();
}
public FileWatcher()
{
_archiveFolder = "D:\\Archive\\";
_errorFolder = "D:\\Error\\";
_fileWatcherInputFolder = "C:\\Input\\";
_processFolder = "C:\\Process\\";
_archiveFolder = "C:\\PMI\\Archive";
_errorFolder = "C:\\PMI\\Error\\";
_fileWatcherInputFolder = "C:\\PMI\\Input";
_processFolder = "C:\\PMI\\Process";
_PMIRepository = new PMIRepository();
_ParserController = new ParserController(_archiveFolder, _errorFolder, _fileWatcherInputFolder, _processFolder);
}
public void Start()
{
try
{
if (!Directory.Exists(_archiveFolder))
Directory.CreateDirectory(_archiveFolder);
if (!Directory.Exists(_errorFolder))
Directory.CreateDirectory(_errorFolder);
_fileCheckTimerBatch = new System.Timers.Timer { AutoReset = false, Interval = 1000 };
_fileCheckTimerBatch.Elapsed += FileCheckTimer_Batch_Elapsed;
_fileCheckTimerBatch.Start();
}
catch (Exception ex)
{
}
}
public void Stop()
{
_fileCheckTimerBatch.Stop();
}
When I step into the program, I can see it reaches the Start() method and walks down to _fileCheckTimerBatch.Start(), but then it jumps out. The debugger just walks back to the Service class and stops the program. What have I done wrong? I even started a whole new service project and copied all the filewatcher DLL files to the new project, but still the same problem.
Thanks
Sunker
|
|
|
|
|
This is what I would expect to happen. The timer is started on a separate thread so there is nothing to hang around for after starting, therefore the process is complete.
|
|
|
|
|
Did you install it? And start it via the manager? I suspect you didn't.
|
|
|
|
|
Hello, CP! I have a question and I have yet to find the answer I need. I have created a custom ToolStrip renderer as well as a class derived from ToolStrip. I have also created a class derived from a standard Button control. Along with these, I have a "ThemeBase" class which all theme sets are derived from, I have two theme sets and I have a "ThemeManager" class. ThemeManager is a singleton class and it works perfectly fine for theming the application all at once. At runtime, that is.
However, I would like to add design-time support for dynamically changing the theme in the Forms Designer. Would this be possible without too much headache? The way it is currently set up is that the controls display in the Forms Designer with the default theme that I set. This is no issue as the themes are virtually identical aside from their color schemes. So if changing the theme at design-time is too much of a hassle then I am not worried about it.
I have looked at custom designers, deriving from ControlDesigner. However, I could not picture that as the solution I am looking for. I have seen controls which you can change the theme for individually at design-time and it takes effect. I am positive I know how that is done. I am interested in theming all controls in the designer (where applicable) at once. Maybe it is not even really possible but I wanted to ask since I could not find the answer elsewhere on my own.
Thank you!
djj55: Nice but may have a permission problem
Pete O'Hanlon: He has my permission to run it.
|
|
|
|
|
Controls render themselves normally (using Paint) at design time, so if that depends on the theme, you should be able to set the theme at design time and have controls change. So I think if you want it to be unified across a whole form or application you need to make your ThemeManager a component so you can get an icon for it at design time and get its properties (such as which theme is being used). You'd then have to make the controls look for the right theme manager and the theme manager would need to invalidate all applicable controls (in the tree of its parent?) when the theme changed.
|
|
|
|
|
Dear Fellows,
I want to create a DSN for oracle through code. I have searched a lot but couldn't get satisfatory solution. Could anyone help me out to get rid of the problem? It would be great if anyone can post a code for that.
Regards,
KS
|
|
|
|
|
I don't see the point. If you have the information to create a DSN you can just make a connection directly.
However, on a previous job I had to copy some ODBC configurations to various servers so I used a RegEdit script file to do it, maybe it'll help.
(This is for Cache , not Oracle.)
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\InterSystems Cache ODBC]
"Driver"="C:\\CacheSys\\bin\\CacheODBC.dll"
"Setup"="C:\\CacheSys\\bin\\CacheODBC.dll"
"SQLLevel"="1"
"FileUsage"="0"
"DriverODBCVer"="02.10"
"ConnectFunctions"="YYN"
"APILevel"="1"
[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers]
"InterSystems Cache ODBC"="Installed"
[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\CABMATE1]
"Driver"="C:\\CacheSys\\bin\\CacheODBC.dll"
"Protocol"="TCP"
"Host"="xx.xx.xx.xx"
"Port"="xxxx"
"Namespace"="CABMATE"
"UID"="xxxxxxx"
"Password"="xxx"
"Description"="CabMate on TTCAB1"
"Query Timeout"="0"
[HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\CABMATE2]
"Driver"="C:\\CacheSys\\bin\\CacheODBC.dll"
"Protocol"="TCP"
"Host"="xx.xx.xx.xx"
"Port"="xxxx"
"Namespace"="CABMATE"
"UID"="xxxxxxx"
"Password"="xxx"
"Description"="CabMate on TTCAB2"
"Query Timeout"="0"
|
|
|
|
|
Greetings Gurus,
I have been searching the forums and tuts for an answer to a question regarding getting running processes off a XP SP3 box without luck so I am posting here hoping one of the Gurus could help me solve this problem.
Running a Windows service under the Local System account (yes I am aware of the dangers this poses but I have taken care of that).
If I run
try
{
SqlConnection myconn = new SqlConnection("User id = a; password = b; server=c;" database=e; connection timeout=30");
SqlCommand insp = new SqlCommand("INSERT INTO dbo.tbconn(Tstamp, SysID, PID, PName)VALUES (@Tstamp, @SysID, @PID, @PName)", myconn);
insp.Parameters.Add("@Tstamp", SqlDbType.DateTime);
insp.Parameters.Add("@SysID", SqlDbType.Int);
insp.Parameters.Add("@PID", SqlDbType.Int);
insp.Parameters.Add("@PName", SqlDbType.NVarChar, 50);
DateTime Tstamp = DateTime.Now;
Process[] processlist = Process.GetProcesses();
foreach (Process p in processlist)
{
insp.Parameters["@Tstamp"].Value = Tstamp;
insp.Parameters["@SysID"].Value = 100;
insp.Parameters["@PID"].Value = p.Id;
insp.Parameters["@PName"].Value = p.ProcessName;
ProcMon.Open();
insp.ExecuteNonQuery();
ProcMon.Close();
}
}
catch (Exception procinfo)
{
everything writes to the table as expected, however I get 3 errors if I run
try
{
SqlConnection myconn = new SqlConnection("User id = a; password = b; server=c;" database=e; connection timeout=30");
SqlCommand insp = new SqlCommand("INSERT INTO dbo.tbconn(Tstamp, SysID, PID, PName, PExe, PCPU, PMem)VALUES (@Tstamp, @SysID, @PID, @PName, @PExe, @PCPU, @PMem)", myconn);
insp.Parameters.Add("@Tstamp", SqlDbType.DateTime);
insp.Parameters.Add("@SysID", SqlDbType.Int);
insp.Parameters.Add("@PID", SqlDbType.Int);
insp.Parameters.Add("@PName", SqlDbType.NVarChar, 50);
insp.Parameters.Add("@PExe", SqlDbType.NVarChar, -1);
insp.Parameters.Add("@PCPU", SqlDbType.Int);
insp.Parameters.Add("@PMem", SqlDbType.Int)
DateTime Tstamp = DateTime.Now;
Process[] processlist = Process.GetProcesses();
foreach (Process p in processlist)
{
insp.Parameters["@Tstamp"].Value = Tstamp;
insp.Parameters["@SysID"].Value = 100;
insp.Parameters["@PID"].Value = p.Id;
insp.Parameters["@PName"].Value = p.ProcessName;
insp.Parameters["@PExe"].Value = p.MainModule.FileName; //Error 1
insp.Parameters["@PCPU"].Value = p.TotalProcessorTime; //Error 2
insp.Parameters["@PMem"].Value = p.VirtualMemorySize64; //Error 3
ProcMon.Open();
insp.ExecuteNonQuery();
ProcMon.Close();
}
}
catch (Exception procinfo)
{
Error 1: System.ComponentModel.Win32Exception: Unable to enumerate the process modules - Still writes all fields but excludes "IDLE"
Error 2: System.InvalidCastException: Failed to convert parameter value from a TimeSpan to a Int32. System.InvalidCastException: Object must implement IConvertible - Writes all values except the TotalProcessorTime,"SYSTEM" and "IDLE" values.
Error 3: System.ComponentModel.Win32Exception: Unable to enumerate the process modules - Writes all values except TotalProcessorTime, "SYSTEM" and "IDLE".
I have tried running it piecemeal and as a Console App but I can't seem to shake these errors (even trying some Convert.ToX stuff).
Can someone help me move this forward please?
Many thanks.
|
|
|
|
|
1 and 3. You were told here[^] what you needed to do when you asked this before.
2. A TimeSpan is a complex structure - not an integer. Write the Tick count out from the TimeSpan instead (you can use this to recreate the TimeSpan later if you need to).
|
|
|
|
|
Hi Pete,
1 & 3
The previously posted example was a Console App running as a local admin, this question is based on the script being run as a Local System Windows service. Does that not make a difference?
I am fairly sure that Local System has access to enumerate those 2 processes (it can definately get the PID & Name, as can the Local Admin user) and, as my reply in the previous posting suggests, NTAuthority\System is the owner so should be able to manipulate the processes in question. Assuming that Local System can't get those values then what role/privilege is required to be able to get the starttime & mainmodule filename?
As I mentioned in the original question, the process [] getprocesses does return the values when the starttime & mainmodule are excluded from the request. Is there a way to get it to write the System and Idle values that are available and exclude the values it can't access?
2
The TotalProcessorTime works when run as a Console App under a local admin account so why does it error as a Windows service? Do I need to pre-format the request/return value? I am afraid I don't know (yet) how to remove the tick count from a built-in property as all I am really doing is taking this http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx and writing it into a service.
I would like to add that while my original question and this are related, I was hoping that changing the environment of the script would solve the permissions problem. I would also like to add that the WMI example can pull (most) of that data as can the Task manager pull the CPU time.
This tells me that there is a way to do it. I just don't know, and/or can't find, it. Thus my posting.
Thank you for your response.
|
|
|
|
|
CCodeNewbie wrote: 2 The TotalProcessorTime works when run as a Console App under a local admin
account so why does it error as a Windows service? Do I need to pre-format the
request/return value? I am afraid I don't know (yet) how to remove the tick
count from a built-in property as all I am really doing is taking this
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.totalprocessortime.aspx
and writing it into a service.
The issue you are hitting here is that you are trying to save the TimeSpan into an integer value (in the database part). This has to be the number only, so just use the Ticks value.
|
|
|
|
|