How to detect which documents the user is sending to printer? [duplicate] - c#

Background:
I'm writing an application in C# using .NET 4.0. It prints a bunch of documents in a certain order. The documents are of all different types and are actually printed using ShellExecute with the "print" verb.
To make sure the order doesn't get jumbled, I'd like to examine the print queue for the printer involved. My main loop would look like:
Invoke "print" action on the document
Wait for document to show up in print queue
Repeat until done
How Can I Monitor The Print Queue Using Managed Code?
I found some great examples of doing similar things using unmanaged calls (Like: http://blogs.msdn.com/b/martijnh/archive/2009/08/05/printmonitor-a-c-print-spooler-monitor.aspx). Also, I know how to look at the spooled files under c:\windows\system32\spool... and figure things out that way.
Howver, none of those solutions are very satisfying ... with amount of unmanaged cod I'm calling I feel like I should just be writing the app in C++. (And not have the .NET dependency/overhead.)
Main Question: Is there really no way to monitor a print queue using only managed calls?
More general question: I come from the java world, and typically only use .NET languages when I want to do something OS specific or something that needs to interact with other things in the MS world. (For example SSIS components.)
It seems like every time I start a project I end up in this same mess: all kinds of calls to native functions, COM stuff, etc, etc.
Secondary Question: Is there something I'm missing about the .NET philosophy or implementation? (Am I just not looking hard enough for managed libraries to do things? Is .NET the wrong choice for anything that needs to do Windows-Specific things like manipulate the print queue?) I get (or think I get) that .NET is theoretically supposed to be OS-independent.. but surely most modern operating system have printers and print queues and things like that. (So if you had generic calls for doing these kinds of things, they could be implemented on each platform's version of the framework..)

Main Question: Take a look at the PrintQueue and LocalPrintServer class in the System.Printing namespace.
Secondary Question: .NET was not written to be OS-independent (sans Mono), it was written to be Windows version independent. While it would be nice only deal with managed objects and managed calls, I see this as a somewhat unrealistic expectation. The sheer size and volume of existing C and COM functions exposed by Windows makes wrapping everything a daunting task. While i'm sure Microsoft has tons of developers on the payroll, I would say that the return on investment is quite low for such an undertaking, considering the relatively easy to use COM & P/Invoke support available.

Related

Watch resources that are used by exe\dll

How can I watch a specific process to know what resources it uses at runtime (such as sounds, pictures, cursors, and registry keys)?
I have to do that programmatically using C# (e.g. using the Windows API or any third party library).
Any help is appreciated. Thanks.
I would stick to performance counters. There are ones for
Memory
GDI Handles (Bitmap, Font, ...)
Handles (File, Registry Key, Event, Mutex, Socket, Process, ...)
Windows (User Objects)
The exact type cannot be determined by using performance counters but it can give you a hint if you are leaking something. If you want to know which handles you can use handles from SysInternals which will give you a nice per process output which you can parse.
If you want to fix the handle leaks then you need to use a debugger (Windbbg) and use the !handle extension to start tracking all aquire/release call stacks for each handle so you can get latter a statistics which handles have been allocated but not freed yet.
Your question is a little to broad because the exact tactic to nail a resource leakage is dependant on the nature of the leak. EasyHook is a good solution to track all resource aquire/release calls and record them automatically.
If you want to automate a debugger with e.g. C# you can use http://wmemoryprofiler.codeplex.com/ which is bascially a managed wrapper around Windbg which even allows you to self debug your application.
When you just want to learn the principles how to get your hands on scattered data for various resources you should read the code of Process Hacker.
Do you want the GDI objects or Win32 handles?
Win32 handles can be obtained using the NtQuerySystemInformation WinAPI function. You can find the C# code for handle-related tasks in these ProcessHacker sources: http://sourceforge.net/p/processhacker/code/HEAD/tree/1.x/trunk/ProcessHacker.Native/Windows.cs
EasyHook will allow you to intercept Windows API calls. Here's a simple example for all file accesses made by a process. Registry calls also seem to be supported.

Monitoring Print Spool Without Using Interop/Unmanaged Code

Background:
I'm writing an application in C# using .NET 4.0. It prints a bunch of documents in a certain order. The documents are of all different types and are actually printed using ShellExecute with the "print" verb.
To make sure the order doesn't get jumbled, I'd like to examine the print queue for the printer involved. My main loop would look like:
Invoke "print" action on the document
Wait for document to show up in print queue
Repeat until done
How Can I Monitor The Print Queue Using Managed Code?
I found some great examples of doing similar things using unmanaged calls (Like: http://blogs.msdn.com/b/martijnh/archive/2009/08/05/printmonitor-a-c-print-spooler-monitor.aspx). Also, I know how to look at the spooled files under c:\windows\system32\spool... and figure things out that way.
Howver, none of those solutions are very satisfying ... with amount of unmanaged cod I'm calling I feel like I should just be writing the app in C++. (And not have the .NET dependency/overhead.)
Main Question: Is there really no way to monitor a print queue using only managed calls?
More general question: I come from the java world, and typically only use .NET languages when I want to do something OS specific or something that needs to interact with other things in the MS world. (For example SSIS components.)
It seems like every time I start a project I end up in this same mess: all kinds of calls to native functions, COM stuff, etc, etc.
Secondary Question: Is there something I'm missing about the .NET philosophy or implementation? (Am I just not looking hard enough for managed libraries to do things? Is .NET the wrong choice for anything that needs to do Windows-Specific things like manipulate the print queue?) I get (or think I get) that .NET is theoretically supposed to be OS-independent.. but surely most modern operating system have printers and print queues and things like that. (So if you had generic calls for doing these kinds of things, they could be implemented on each platform's version of the framework..)
Main Question: Take a look at the PrintQueue and LocalPrintServer class in the System.Printing namespace.
Secondary Question: .NET was not written to be OS-independent (sans Mono), it was written to be Windows version independent. While it would be nice only deal with managed objects and managed calls, I see this as a somewhat unrealistic expectation. The sheer size and volume of existing C and COM functions exposed by Windows makes wrapping everything a daunting task. While i'm sure Microsoft has tons of developers on the payroll, I would say that the return on investment is quite low for such an undertaking, considering the relatively easy to use COM & P/Invoke support available.

Most eficent way of .NET IPC on Windows Mobile

I'm going to split a program into two parts, because I'm running out of process memory. One part is taking a picture and storing it on the file system (GUI) and the other part is analyzing the picture (OCR) and reporting the results back to the main part.
The communication between the two processes will look like this:
Is the OCR process responding?
If not, start OCR process.
Tell the OCR process that there is a new picture.
Wait until the OCR process returns the result (most likely less than 1 KB of characters)
The three most important things, in order of priority for me are:
High performance
High stability
Low complexity - I've only got around three days to finish and test the program.
The GUI is written in .NET/C#, so the solution must be compatible with that. Which method of IPC would you recommend me to use?
I'd probably use point to point queues for this. They perform very well and are stable - the kernel uses them for it's own notification system. The MSDN article already has the managed classes built for using them, so complexity is also low.
You could use WCF for Windows Mobile. Microsoft have released guidelines and sample projects for how to do this. If you set it up to use message queue end points (I'm not sure if named pipes are available), then performance should be very good. Apart from that, WCF is a very easy technology to get started with. Good luck!

C++ backend with C# frontend?

I have a project in which I'll have to process 100s if not 1000s of messages a second, and process/plot this data on graphs accordingly. (The user will search for a set of data in which the graph will be plotted in real time, not literally having to plot 1000s of values on a graph.)
I'm having trouble understanding using DLLs for having the bulk of the message processing in C++, but then handing the information into a C# interface. Can someone dumb it down for me here?
Also, as speed will be a priority, I was wondering if accessing across 2 different layers of code will have more of a performance hit than programming the project in its entirety in C#, or of course, C++. However, I've read bad things about programming a GUI in C++; in regards to which, this application must also look modern, clean, professional etc. So I was thinking C# would be the way forward (perhaps XAML, WPF).
Thanks for your time.
The simplest way to interop between a C/C++ DLL and a .NET Assembly is through p/invoke. On the C/C++ side, create a DLL as you would any other. On the C# side you create a p/invoke declaration. For example, say your DLL is mydll.dll and it exports a method void Foo():
[DllImport("mydll.dll")]
extern static void Foo();
That's it. You simply call Foo like any other static class method. The hard part is getting data marshalled and that is a complicated subject. If you are writing the DLL you can probably go out of your way to make the export functions easily marshalled. For more on the topic of p/invoke marshalling see here: http://msdn.microsoft.com/en-us/magazine/cc164123.aspx.
You will take a performance hit when using p/invoke. Every time a managed application makes an unmanaged method call, it takes a hit crossing the managed/unmanaged boundary and then back again. When you marshal data, a lot of copying goes on. The copying can be reduced if necessary by using 'unsafe' C# code (using pointers to access unmanaged memory directly).
What you should be aware of is that all .NET applications are chock full of p/invoke calls. No .NET application can avoid making Operating System calls and every OS call has to cross into the unmanaged world of the OS. WinForms and even WPF GUI applications make that journey many hundreds, even thousands of times a second.
If it were my task, I would first do it 100% in C#. I would then profile it and tweak performance as necessary.
If speed is your priority, C++ might be the better choice. Try to make some estimations about how hard the calculation really is (1000 messages can be trivial to handle in C# if the calculation per message is easy, and they can be too hard for even the best optimized program). C++ might have some more advantages (regarding performance) over C# if your algorithms are complex, involving different classes, etc.
You might want to take a look at this question for a performance comparison.
Separating back-end and front-end is a good idea. Whether you get a performance penalty from having one in C++ and the other in C# depends on how much data conversion is actually necessary.
I don't think programming the GUI is a pain in general. MFC might be painful, Qt is not (IMHO).
Maybe this gives you some points to start with!
Another possible way to go: sounds like this task is a prime target for parallelization. Build your app in such a way that it can split its workload on several CPU cores or even different machines. Then you can solve your performance problems (if there will be any) by throwing hardware at them.
If you have C/C++ source, consider linking it into C++/CLI .NET Assembly. This kind of project allows you to mix unmanaged code and put managed interfaces on it. The result is a simple .NET assembly which is trivial to use in C# or VB.NET projects.
There is built-in marshaling of simple types, so that you can call functions from the managed C++ side into the unmanaged side.
The only thing you need to be aware of is that when you marshal a delegate into a function pointer, it doesn't hold a reference, so if you need the C++ to hold managed callbacks, you need to arrange for a reference to be held. Other than that, most of the built-in conversions work as expected. Visual Studio will even let you debug across the boundary (turn on unmanaged debugging).
If you have a .lib, you can use it in a C++/CLI project as long as it's linked to the C-Runtime dynamically.
You should really prototype this in C# before you start screwing around with marshalling and unmarshalling data into unsafe structures so that you can invoke functions in a C++ DLL. C# is very often faster than you think it'll be. Prototyping is cheap.

Can I get the functionality of MsgWaitForMultipleObjects in .Net CF?

We're migrating a C++ application to .Net CF. We need to monitor both the UI and several external events. I therefore wonder if we can get the same functionality of MsgWaitForMultipleObjects in the unmanaged world also in the managed world?
Edit: P/Invoke is not the complete answer I'm seeking, since what I meant was that we want the full functionality of what we have in the unmanaged world, meaning that when input messages are pumped, events and other sync objects are also monitored. We don't have access to the message pump in .Net, for obvious reasons. So where do we hook ourselves in for P/Invoking MsgWaitForMultipleObjects?
What we'll need to do is actually to skip Application.Run(Form) and roll our own message loop as in the unmanaged world. Then we can use MsgWaitForMultipleObjects as described in the original question. This has been done also in SDF.

Categories