C#/.NET wrapper for serial port WIN32 Comm API - c#

I am looking for a way to have as much control as it is possible over serial port in my c# application. The problem is that I need to communicate with a device that has no documentation except for an old c++ program written to control it. I've tried to use SerialPort class to communicate with the device but its behaviour is quite odd (I have to repeat some of the commands, some other commands dont work at all).
I would like to copy that unmanaged program's behaviour, however it seems to be impossible with serialport class, as it does not provide access to low-level functions and structures like DCB for example.
Are there any low-level wrappers for serial communication available for .net? Maybe i could use reflection to manipulate serialport innacessible members at runtime?

For those suggesting to look at the .NET SerialPort class; frequent Stack Overflow answer provider on Serial related issues, Ben Voigt, provides some excellent insights on why a wrapper around WinAPI would eventually turn out to be a much better idea than using the framework provided SerialPort:
Ben Voigt on .NET SerialPort
A must read.
He also refers to a WinAPI wrapper that he might reveal in future blog posts. If that would happen, it would answer the original question.
Also, there seems to be at least one commercial solution providing the requested functionality here.
Another edit:
Some more searching online has yielded this blog post apparently from the time when there was no SerialPort class in .NET... Source code is provided showing how to wrap Win32 API for the purpose.
EDIT
Some users have pointed out that the above mentioned MSDN blog post link is dead.
The title of the linked article was:
"Use P/Invoke to Develop a .NET Base Class Library for Serial Device Communications", written by John Hind andpublished October 2002 as I can tell from another MSDN article referring to it:
Unfortunately, Microsoft seems to only serve editions of their magazine down to 2003:
FWIW, I found a half working online version elsewhere...

Unfortunetely, the SerialPort class is an incomplete wrapper. I have found the only way to gain access to the underlying DCB is through reflection.
The only other option would be to re-write SerialPort and make it complete. I have not seen any such implementation freely available (yet).
Here is an example where I used reflection to gain access to RTS_CONTROL_TOGGLE:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/45a89532-b01c-4ef8-aa46-532882cec004

The SerialPort class is a very thin wrapper around the Win32 serial port API, hard to see how another wrapper could improve your life. There are wrappers available from the .NET 1.x days, it didn't support serial ports. Here is one from MSDN magazine.
But you're just as likely to have the same problems. One way that written commands could get lost is by the device throwing away received bytes (or losing them) when it has turned off the RTS signal off. You fix that by setting the Handshake property to RequestToSend.
One way that things can go wrong with reading commands is to get the Read() call wrong. It will return an arbitrary number of bytes, as many as are available in the receive buffer. Pay attention to the return value, it tells you how many bytes were actually read. The only guarantee is that it will at least be 1 and never more than count.
The SysInternals' PortMon utility can help you troubleshoot communications, it gives you a raw view of what the device driver sees. Compare with, say, Hyperterminal or another known-good program.

Working with a serial port through PInvoke works fine. We're doing this in a Silverlight application, but it should work the same in a normal .NET app. The answer to Serial Communication with Silverlight 5 (COM port) provides a basic wrapper for a which could easily be adapted to your needs. It uses the normal WinAPI method so you get full access to all serial port functionality, like you would in a C++ application.
P.S. If you don't already, use PortMon to monitor what's happening on the line.

You may be able to copy the old C++ code into a managed C++ class, which you could then use just like any normal .NET class from your C# code. This may be the fastest way to reach your goal.

Related

Control parallel port using C# Mono in Linux

As per the title, I want to control a parallel (LPT) port using C# in Ubuntu.
Are there any inbuilt libraries in Mono that will allow me to do this?
Can anyone give any code examples of making this work?
Guide with basics, and c# code for use of inpout driver and api: http://www.codeproject.com/KB/cs/csppleds.aspx
More general collection of links, both technical as well as software related to the parallel port: http://www.lvr.com/parport.htm
I spend quite some time researching this, and never found a native mono library. It's easier for Serial Ports btw.
While I acknowledge Jesper's contribution, I felt his answer was incomplete and the initial answer gave only references to Windows code as pointed out by Dai. Jesper's follow up comment regarding P/Invoke did lead me down a path to finding the answer.
I have documented my complete solution, including code samples here: http://www.iaincarlin.com/ylsned/controlling-the-parallel-port-using-ubuntu-mono-and-c/ however, in a nutshell:
There appears to be no native library in C# Mono for accessing the parallel port
P/invoke is required and I had to create a native C++ application that I could invoke with DLLImport in order to access the LPT1 port.
The C++ application essentially provides a wrapper round the io library outb function that I can call from C#
My blog post above contains more details regarding the background to what I was doing. I could have used native C++ to do the same thing (in fact it would have been easier to port my existing Dos code over to Linux), but I wanted to experiment with Mono and this was a practical way to do so.
I need to acknowledge the post here: http://www.moythreads.com/wordpress/2008/02/04/pinvoke-how-to-call-c-from-c/ that provided the most helpful in getting this to work.

Change default audio device on Windows 7

I want to be able to change the default audio output device on Windows 7 programatically using C# (and probably some underlying Win32 API calls, as well). I've already done my homework, and I've heard a lot of mixed comments from different sources, so I wanted to ask this question again to get a straight answer. Is this actually possible (through any means)? If so, how would I go about doing this?
And please do not suggest a solution with "AutoIt" or some other similar program... this is a C#/.NET-specific question.
A little up-to-date answer, which is compatible with Windows 10.
This program is able to do it in a beautiful manner (hotkey to switch between pre-selected devices) and is written on C# :
SoundSwitch on GitHub
Some reverse engineering should get you there (for my use this program was just perfect as it is).
It makes use of that library (same author) which is in C++ :
AudioEndpointLibrary on GitHub
So if you know C++ (which I don't enough), you might go further in the analysis of how it works. Or just use the library like SoundSwitch does.
Just in case anyone stumbles across this thread in the future... here's some C++ code that'll do it by calling some undocumented Win32 APIs. This can be compiled into an EXE and then called silently from a .NET application, so you could build a .NET program around this code.
http://web.archive.org/web/20190317012739/http://www.daveamenta.com/2011-05/programmatically-or-command-line-change-the-default-sound-playback-device-in-windows-7/

monitor internet usage in .net

I want to write a method in C# to check which applications in my machine/server are using internet connection at a particular point in time and if possible, how much bandwidth they are using. Can anyone please help me get a head start on this?
I decided to write an answer because comments are too small.
Well, reading other Q&A on stackoverflow and looking around on the internet, I didn't find a simple solution for your problem.
Actually, for .NET processes is really simple, you just need to retrieve informations from ".NET CLR Networking - Bytes Received/Bytes Sent" performance counters, as shown in this Q&A
But in general, getting per-process used bandwidth isn't an easy work.
For example "Microsoft Network Monitor" sniffer can trace the process that generates internet packets only for TCP traffic, because probably it maps IP-port pairs with processes using them (or something similar, TCP is a connected protocol so it is simpler).
Anyway if you want to give it a try you can use the exposed API (look at this blog entry for some hint).
However, as suggested in these Q&A's (LINK 1, LINK 2), the right, and probably the only way, is to write a NDIS/TDI driver that can intercept network traffic and exposing a .NET callable API to it.
The problem is that such drivers can't be written in managed code, and so you need to implement it in C/C++.
Obviously, if you manage to find an already written driver/sniffer exposing a callable API, you can use it.
For example WinPCap has one (and some .NET wrappers like SharpPCap or PCap.Net), but I don't think (not sure) it's able to get packets's source-process information.
As digEmAll noted, in pre-Vista Windows you are reduced to writing your own driver or using a 3-rd party one. In Vista, 2008 and Windows 7 you can use the GetPerTcpConnectionEStats API (there is a large example of its usage on the MSDN page). Resource Monitor relies on this API, together with the older GetTcpTable/GetTcpRow APIs, for extended network statistics.
I found Process Monitor as a very useful tool and it served my purpose so I didnt had to write any code although i am yet to check out whether it gives any API which i can use in my application to get some information I need.
Thanks everyone for helping me out.

How do I create a COM (and other device) emulator in C#?

We have several legacy components that interact with COM ports, USB etc.
I would like to create a .NET program that would emulate a COM port and log the traffic, relaying it to a WCF service endpoint somewhere or directly into a database. Maybe also wrapping a real COM port kind of like the decorator pattern.
I have looked around and I have found Sourceforge project Com0Com, but it's pretty old API and in c++.
I realize that I can solve this specific problem by creating a line printer driver and never really interacting with the COM ports registered in the system. Some links to that would also be highly appreciated.
Has anybody done this? How do you create system resources in .NET?
You would have to write a driver, that's how Com0Com works. If these components run in-process, you could hijack the Windows API functions, Microsoft's Detours for example.
Either solution requires C/C++, you can't write this code in a managed language. Although detouring could be technically possible, just very hard to get right. You can buy a solution though, your requirements are not uncommon, albeit it dated. Dated enough that finding one might be a bit tricky.
Has anybody done this?
To add to what nobugz said:
When I wrote a COM port emulator, I did it starting from the sample serial port driver in the DDK (serial.sys).
When I wrote a COM port wrapper/logger, I did it starting from the sample parallel port filter driver in the DDK (parport.sys).

IRAPIStream COM Interface in .NET

I'm trying to use the OpenNETCF RAPI class to interact with a windows mobile device using the RAPI.Invoke() method.
According to the following article:
http://blog.opennetcf.com/ncowburn/2007/07/27/HOWTORetrieveTheDeviceIDFromTheDesktop.aspx
You can do the communication in either block or stream mode. I have used block mode before, but now I need to do something a bit more complicated with a lot more data and continuous communication and therefore need to use the stream mode. Unfortunately on that article, and basically everywhere else, there is no explaination of how to use IRAPIStream in .NET I have found C/C++ documentation, but my desktop app needs to be written in C#
Does anyone know how to properly implement the IRAPIStream COM interface in .NET?
And better yet, anyone actually used RAPI.Invoke() with IRAPIStream before? Examples would be much appreciated.
Edit: Upon a closer look at the RAPI class documentation, I realized that the Invoke() method doesn't support the stream interface.... so OpenNETCF is likely out, but maybe there is still a way to do it?
I have found that generally the most performant and stable way to push/pull large amounts of data of a device over activesync is to use a socket.
Early on we used CeRapiInvoke and a stream to pull data down of the device but ditched this early on in favour of using tcp/ip over a socket.

Categories

Resources