Watch resources that are used by exe\dll - c#

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.

Related

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

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.

How do I sandbox calling an external unmanaged application from managed code?

We are developing an online test application for XSLT processors in ASP.NET, however, I'm a bit worried about how to limit the vulnerabilities of our system. Is it possible with .NET to sandbox a third party unmanaged or managed application? It should:
not be allowed to start any other process by any means or vulnerability;
have no access to other existing processes on the system;
be killed when it takes too much processing power or memory;
work with both managed and unmanaged external applications;
should not be able to access system calls
Some applications have a managed API, but that doesn't suffice because than I need to run it in the same processing space as ASP.NET with all potential risks (stack overflow, memory exceptions, buffer overflow). I'm not aware whether .NET offers sandboxing of unmanaged applications.
We currently execute the external program in a console with specific affinity and monitor this, but that doesn't feel like a right or even closely safe approach.
You can execute managed code within an AppDomain which can be configured to provide some level of protection, however as soon as you allow unmanaged code to run, its pretty much got access to everything the user its running under has access to.
I'm pretty sure you can prevent unmanaged/unsafe code being executed within an AppDomain though.

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.

How to use GC.KeepAlive() and for what purpose?

How can we use GC.KeepAlive() and what is the purpose?
I transfer files from terminal (Windows-CE) to Server using Socket. The time needed for transfer is 8 minutes. After 5 minutes the Windows-CE shuts down (if touch screen not pressed)
If I use GC.KeepAlive() for this, does this solve my problem?
You very rarely need to use GC.KeepAlive - very rarely. You'd use it if you wanted to prevent the side-effect of a finalizer from occurring too early, for example. I've most often seen it used for Mutex - keeping mutex alive until the end of an app to make sure there's only one instance. (A using statement is actually better here, but that's a separate matter.)
And no, it doesn't sound like it's relevant in your situation.
From the MSDN library for .NET:
The purpose of the KeepAlive method is to ensure the existence of a
reference to an object that is at risk of being prematurely reclaimed
by the garbage collector. A common scenario where this might happen is
when there are no references to the object in managed code or data,
but the object is still in use in unmanaged code such as Win32 APIs,
unmanaged DLLs, or methods using COM.
So not this would not solve your problem. In fact it's not even related to your problem.
The only thing you can do is in the service/application running on the Windows CE, adding code that prevents the system to shutdown as long as the transfer is in progress
The screen powering down is a power-management setting on the device. It's going to happen whether or not any app is running. The GC has absolutely nothing to do with this.
If you want to prevent the power maanger from putting hte device into a low-power state, you have a few options. You can periodically call SystemIdleTimerReset in your app.
You could force the power state to something you like with SetSystemPowerState.
You could change the power manager timeouts to something more to your liking by adjusting settings at [HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Power\Timeouts] (followed by a WM_SETTINGS_CHANGE broadcast IIRC).
The best "solution" is going to depend on your app requirements, your users' requirements and the power management system of the target device.

Using win32 in managed code

I have been using WPF for a few years now and don't have any experience with anything but managed code. I started writing an app that uses a lot of win32 interop and i started wondering if i was leaking memory or generally doing something stupid that i didn't know about... So i thought i would seek some advice!
Is there any gotchas/tips/tricks when using win32 calls inside managed code?
I am mostly interested in memory/garbage collection but any other tips are welcome!
There are no gotchas. You free all resources that you allocate (unless the documentation indicates that the call you make takes over the resource, relieving you from ownership), and that's all there is to it. GC doesn't enter into it at all.
As a tip, System.Runtime.InteropServices.SafeHandle is a stock helper class to use Win32 handles RAII-style.
Almost resource you allocate in Win32 has to be deallocated with the right API call, which is documented on the MSDN page for the allocation API.
This is an entirely manual process; garbage collection doesn't assist with this at all, although you can use SafeHandle or (last resort) finalizers.
At the very least, use IDisposable wrapper classes around any resources you allocate. In some cases, these already exist in Windows Forms.
You can use Perfmon or Task Manager to monitor the number of handles open in your process.
The main problem with win32 interop is (obviously) Linux/Mac OS incompatibility(Mono won't be able to help you yet if you have P/Invokes to win32 libraries).
Apart from that, I'm not aware of any problems. Unless, of course, the function you're calling itself leaks memory.
You have to be a bit careful if you need to call GetLastError to determine why a win32 call failed. This page provides a detailed description.

Categories