|
Hi all, I am pretty new to coding, and am attempting to port this code from C to c#, and cannot figure out the createfile section. Do i need it? can i replace it with something?
original C.
HANDLE openAndSetupComPort(const TCHAR* comport)
{
HANDLE com_handle;
DCB dcb_serial_params = { 0 };
COMMTIMEOUTS timeouts = { 0 };
DWORD com_error;
COMSTAT comstat;
com_handle = CreateFile(comport,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (com_handle == INVALID_HANDLE_VALUE){
printf("Error opening port\n");
return INVALID_HANDLE_VALUE;
}
dcb_serial_params.DCBlength = sizeof(dcb_serial_params);
if (!GetCommState(com_handle, &dcb_serial_params)){
printf("Failed to get the previous state of the serial port\n");
CloseHandle(com_handle);
return INVALID_HANDLE_VALUE;
}
dcb_serial_params.BaudRate = 115200;
dcb_serial_params.ByteSize = 8;
dcb_serial_params.StopBits = ONESTOPBIT;
dcb_serial_params.Parity = NOPARITY;
if (!SetCommState(com_handle, &dcb_serial_params)){
printf("Failed to set the serial port's state\n");
}
timeouts.ReadIntervalTimeout = -1;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(com_handle, &timeouts)){
printf("Failed to set the timeouts\n");
CloseHandle(com_handle);
return INVALID_HANDLE_VALUE;
}
Sleep(300);
ClearCommError(com_handle, &com_error, &comstat);
if (comstat.cbInQue != 0){
PurgeComm(com_handle, PURGE_RXCLEAR | PURGE_TXCLEAR);
}
return com_handle;
}
which is being called here:
if(!WriteFile(com_handle, write_bytes, sizeof(write_bytes), &bytes_written, 0)){
printf("Error writing to port\n");
return 2;
}
So I am opening a serial port:
public static void SerialSetupIMU()
{
_serialPort = new SerialPort();
_serialPort.PortName = "COM11";
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = 100;
_serialPort.WriteTimeout = 100;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
try
{
_serialPort.Open();
_serialPort.DiscardInBuffer();
_serialPort.DiscardOutBuffer();
}
catch
{
Console.Write("port does not exist");
}
if (_serialPort.IsOpen)
Console.Write("port 11 opened");
}
and attempting to write:
_serialPort.Write(com_handle , write_bytes, byteSize, bytes_written, 0);
And it fails on the 'com_handle', obviously, because I haven't added it. But what is it expecting there?
Any help would be much appreciated!
Thank you much.
|
|
|
|
|
C# is an object oriented language, C isn't.
When you create and open the SerialPort object it "remembers" which port handle it should use internally, so you don't need to think about it - you just tell the SerialPort instance to write, and it sorts it all out for you: http://msdn.microsoft.com/en-us/library/ms143551(v=vs.110).aspx[^]
So, once you have the port opened, just write your data to it:
_serialPort.Write(write_bytes, 0, write_bytes.Length); Will write all the bytes in the write_bytes array to the port.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks for your answer!
_serialPort.Write(write_bytes, 0, write_bytes.Length);
is giving me a
'no overload for method takes 3 arguments' exception.
|
|
|
|
|
actually, my bad. that is working great. thanks again!
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Hi,
Regarding sqlConnection, is it recommended to keep it open all across the application or open it every time I want to use it then close it? Which method is better for the memory?
Thanks,
Jassim
Technology News @ www.JassimRahma.com
|
|
|
|
|
Forget memory, it's pretty much irrelevant for SqlConnection objects.
Close it when you are finished with it, and Dispose the object.
The actual connections at the other end (SQL Server) are scarce resources, and holding yours open for the duration of your application can "block" others from accessing the database at all. So release it when you are finished, which lets other users have it and you can get it back later.
And Dispose any SqlCommand objects you create as well!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
In your methods that require a SqlConnection ensure you use a using block to enclose your connection related code. Objects that implement the IDispose interface (of which SqlConnection does) is guaranteed to be disposed when completed.
using (SqlConnection conn = new SqlConnection())
{
}
"There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." - C.A.R. Hoare
Home | LinkedIn | Google+ | Twitter
|
|
|
|
|
Im Making a very simple vehicle renting program as learning task.
This is probably a simple question even if the text is a bit long.
I have made theese simple classes.
Vehicle, VehicleManager, VehicleForm with (Add/Remove buttons)
Customer, CustomerManager, CustomerForm(Add/Remove buttons)
Agreement, AgreementManager, AgreementForm(with Add/Remove buttons
one ComboBox with Customers and
one ComboBox with vehicles
(and 2 datepickers))
In AgreementManager I have 'private List<agreement> _Agreements'
A very simple structure but....
I was planning to remove a customer in CustomerForm.
The problem comes up when I want to remove a customer that has an agreement.
This must be inhibited(Show error/informative message and all that) if the customer is found as a customer in the agreementlist witch resides in the AgreementManager class.
How can I look in this list from 'inside' the Customer form.
I cant just make another agreementamng. object, because making a new one will not have the agreements in it.
How should/can I access methods in AgreementManager from CustomerForm?
Alternatively I could have a boolean _HasAgreement in the Customer objekt, to prevent delete. But that seems like a rather primitive solution now that i am learning to use obejct orientation and ObjectLists and working with managers.
thanks
BlindNavigator
|
|
|
|
|
You're mixing concerns here. Is it not the case that a Customer has a collection of Agreements? This would indicate that the customer object has a list associated with it - which simplifies what you need to do to check for customers.
|
|
|
|
|
My first ideas was:
agreementmanager would have a list of agreements. Agreement had a customer and a vehicle inside.
The Customermanager would have a CustomerList and methods to add/delete/edit etc. to this list.
and the Vehiclemanager would have a VehicleList and methods to add/delete/edit etc. to this list.
Considering your interesting suggestion, Pete.
Doing it this way I wonder if perhaps removing a Vehicle from a Vehicle List if that vehicle is in a agreementlist of a customer might become a similar problem instead.
It turned out a bit more tricky than i first imagined to 'separate concerns' here.
I was also toying with an idea of having a mainManager with all managers inside. Im not sure if that might solve the issues with removing enteties that are included in lists.
|
|
|
|
|
If I were designing a Form to be used for viewing the current state of a Customer, I would not have a method available from that form to actually delete a Customer ... for security reasons. I would allow only the Manager's Form to delete a Customer, or delete any agreement with the Customer.
I would probably want to show, on a given Customer's Form:
1. the customer information appropriate to the role of the person viewing the Form
2. at least the fact that the Customer has a current agreement(s).
3. depending on design: perhaps a mechanism to notify the Manager the customer has made a request to delete account/agreement.
I'd suggest (hard to be more specific without seeing/understanding your code):
1. when the current Customer Form is created, pass to it the necessary information it needs to present what you want to appear on the Form about the current agreement(s), or the fact there is no current agreement.
2. I'd use a separate Form to notify the Manager of a request for deleting an account, or agreement ... if the Customer Form did not allow such a notifiaction by the person using it.
«A man will be imprisoned in a room with a door that's unlocked and opens inwards ... as long as it does not occur to him to pull rather than push» Wittgenstein
|
|
|
|
|
Hi All,
We need to build our own workflow engine using c#,
please help me if you can how to start do that and let me know if it is possible or not.
Thanks
|
|
|
|
|
The first question I would have to ask is why? .NET has Workflow Foundation available for free, so have you looked into what it offers? As to the second part, yes it is possible to build your own Workflow engine using C#. Only you and your team can decide what you want it to be able to do, so it's up to you to define your requirements. For instance, what database do you intend to use to provide support for your Serializable Large Objects (SLOBs)?
|
|
|
|
|
|
What?
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
|
We'd love to be able to help you, but we don't understand your question. I appreciate that English isn't your first language, but if you could find someone who was more fluency in English to help you write your question, this will probably help everyone.
|
|
|
|
|
|
Hi
i need to create a windows service which can run continuously
i have some ms sql qureys which i would like to run can any one help me i don't have any idea on c# if any one can help it will be great full.
Thank
Sharm
|
|
|
|
|
Have a look at Topshelf or Cinchoo for getting started with a service - when you have a running service then add the ability to connect and query a database to it - you might like to think about how you're going to 'schedule' the execution of your queries - some sort of timing mechanism - its not too hard to use Quartz.Net with Topshelf to provide this ability
have fun
|
|
|
|
|
int a = 0;
int inputvalue = 0;
for (int i = 0; i < 1; i++)
{
Console.WriteLine("Give me a number");
inputvalue = Convert.ToInt16(Console.ReadLine());
if (i == 0)
a = inputvalue;
while ()
}
Console.ReadLine();
Hi guys, this is what I have so far. I am trying to learn this but i cant even understand the basics and i am really frustrated. Heres what im trying to do. Im trying to have a loop repeat certain code before it exits out. So in this example, I want to be able to write a nested loop where if I dont meet a certain condition, it continues to repeat until the condition is met. For example,
Give me a number greater than 50.
If the condition is met then loop out of the nested loop and ask for another number, if condition is not met, ask again until condition is met.
Am I close? do I have to use a loop at all or will an if statement suffice?
|
|
|
|
|
Nearly, but I would likely do the inner loop more like this:
do
{
Console.Write("Give me a number");
}
while (!System.Int16.TryParse(Console.ReadLine() , out inputvalue ) || (inputvalue <= 50 ) ) ;
|
|
|
|
|
Nested Loop defines as create the new loop inside the already existing loop. e.g.
for(int i =0;i<5;i++)
{
for(int j=0;j<i;j++)
{
Console.Write("*");
}
Console.WriteLine("");
}
Here is the example of nested for loop. You may also include the while or do-while loop inside or outside the loop.
Happy Coding
|
|
|
|
|
Your code here ... the for-loop ... suggests you want to get a certain number of numbers from the user, but I don't see you storing those numbers for future use.
PieBald's response here shows you how to use 'TryParse, and you should definitely be using that.
Do you need to preserve the user's entries ?
Also, what about letting the user quit the loop when they enter something like "quit" ?
«OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. » Alan Kay's clarification on what he meant by the term "Object" in "Object-Oriented Programming."
|
|
|
|