I have a scenario where I must delete a file. I don't know and don't care who holds the file. I must delete it and they can crush for all I care. (I don't want to kill the locking task)
the only solution that comes to my mind is to use http://www.emptyloop.com/unlocker/ command line interface.
MoveFileEx is not and option as I cannot restart the machine.
is there any more C#ish method/library for this?
im not thrilled using console application API
in case it is not clear.I know the risk involved and I don't need a lecture of why this is a bad practice. if you know how to do what I asked. thank you very much!
if you want to lecture why this is bad - just don't find someone else to bother##
I can't give you a solution but can point you into a direction.
Window's Process Explorer has a function that can make you search for handles:
When you then select that handle you go to the process owning that handle and you can right click on it and Close the handle and also relieve the lock that process has on that file.
So basically you need to find out which API calls Process explorer is using and execute them yourself in your application.
I think what you are asking for is impossible due to the nature of a lock.
How would you feel if another program could just snatch your files and wipe them as you were reading data?
I believe these unlockers detect the process and try to force it to release it's lock 1 way or another(maybe even shutting their process down).
While this may work for most applications some will be more aggressive (think virus scanners for example).
So maybe you need to ask yourself if you want to increase your chances of getting a lock or if you need to be absolutely sure to get a lock.
Edit:
Assuming you can terminate the locker process and you really want to clear those files(no matter the consequences) you could find the process that holds the lock and shut it down.
In this thread they give a few solutions for tracking which process holds a lock(in c# code) via either handle, win32 dll's or even plan .NET code.
Disclaimer Be aware that shutting down a process like this will have a terrible impact on the consistency of that program and you might even do more bad then good(suppose it's writing it's status the the database for example and halfway it gets terminated)
I have been working on many applications which run as windows service or scheduled tasks.
Now, i want to make sure that these applications will be fault tolerant and reliable. For example; i have a service that runs every hour. if the service crashes while its operating or running, i d like the application to run again for the same period (there are several things involved with this including transactions of data processing) , to avoid data loss. moreover, i d like the program to report the error with details. My goal is to avoid data loss and not falling behind for running the program.
I have built a class library that a user can import into a project. Library is supposed to keep information of running instance of the program, ie. program reads and writes information of running interval, running status etc. This data is stored in a database.
I was curious, if there are some best practices to make the scheduled tasks/ windows services fault tolerant and reliable.
Edit : I am talking about independent tasks or services which on different servers. and my goal is to make sure that the service will keep running, report any failures and recover from them.
I'm interested in what other people have to say, but I'll give you a few points that I've stumbled across:
Make an event handler for Unhandled Exceptions. This way you can clean up resources, write to a log file, email an administrator, or anything you need to instead of having it crash.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppUnhandledExceptionEventHandler);
Override any servicebase event handlers you need in the main part of your application. OnStart and OnStop are pretty crucial, but there are many others you can use. http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase%28v=VS.71%29.aspx
Beware of timers. Windows forms timers won't work right in a service. User System.Threading.Timers or System.Timers.Timer. Best Timer for using in a Windows service
If you are updating on a thread, make sure you use a lock() or monitor in key sections to make sure everything is threadsafe.
Be careful not to use anything user specific, as a service runs without a specific user context. I noticed some of my SQL connection strings were no longer working for windows authorizations, etc. Also have heard people having trouble with mapped drives.
Never make a service with a UI. In fact for Vista and 7 they make it nearly impossible to do anyway. It shouldn't require user interaction, the most you can do is send a message with a WIN32 function. MSDN claims making interactive services is bad practice. http://msdn.microsoft.com/en-us/library/ms683502%28VS.85%29.aspx
For debugging purposes, it is way cool to make a service run as a console application until you get it doing what you want it to. Awesome tutorial: http://mycomponent.blogspot.com/2009/04/create-debug-install-windows-service-in.html
Anyway, hope that helps a little, but that is just a couple thing I poked around to find on my own.
Something obvious - don't run all your tasks at the same time. Try to schedule them so only one task is using some expensive resource at any time (if possible). For example, if you need to send out newsletters and some specific notifications, schedule them at different times. If two tasks need to clean up something in the database, let the one run after another.
Also schedule tasks to run outside of normal business hours - at night obviously.
I have a C# security/monitoring application that I need to have running no matter what. However, I can not remove privileges or restrict access to parts of the OS (Windows).
I thought of having a protection service running which monitors continuously if an application is running, and starts it back up when the application is killed somehow, while the application monitors the protection service and starts the service if the service is killed. To my knowledge you can't simultaneously kill multiple processes at the same time.
Any better idea to guarantee that an application is always running?
The Windows team gets requests like this all the time:
"I want to make a process that can never be killed".
"Well I want to make a tool that can kill any process".
One of those two people is going to be disappointed.
"I want to make a window that is always on top of all other windows no matter what"
"I also want to make a window that is always on top of all other windows no matter what"
One of those two people is going to be disappointed.
"I want to make a process that does not show up in any list of processes no matter how cleverly the listing program is trying to find me"
"I want to make a program that lists all processes, no matter how cleverly the process is trying to hide".
One of those two people is going to be disappointed.
And so on.
I think you're going to be one of the disappointed people.
There is no guarantee - if the user has enough privilege it can terminate your program or any other monitoring code you have running that will restart your application.
Imagine if this were true - every piece of spyware on the planet would be using it.
I would write your program as a windows service - configure it to run automatically on startup, and to restart automatically if it is terminated unexpectedly. You cannot do any better than this since the user must be allowed to control the computer.
We are making a Jabber client for our internal use in our company and somehow we need to catch the moment when the user tries to kill the program to actually restart it or just make impossible for the user to kill the client.
Is this possible?
Our Jabber client will be written in C#.
How would I go about accomplishing this?
What you are asking for has implications far beyond what you are being asked to accomplish. For example, if the process cannot be killed, how can Windows shut down normally?
I don't know your boss, so you will have to gauge their level of understanding for yourself. If a user/manager asked me for this, I would have to probe deeper to find what they really mean. My suspicion is that your users want the default close behavior to minimize to the system tray rather than exit the program, similar to most instant message clients, rather then not be able to ever close the program at all.
let me first say, this is a horrible idea.
but...if you must do it, the way I see malicious software and spam hounds do it is to create 3 running processes, one is the main process and the other two will monitor and restart any killed process. it's very difficult for the average user to kill 3 processes simultaneously.
Sounds like a virus.
Since this is internal, you could create a separate windows service that monitors the active processes. If the process of your jabber client isn't there, you could just relaunch it.
Then use permissions to keep them from accessing the Windows Service to disable it.
I think you should go ask the requirement designer what they mean by app that is impossible to "kill." What are they getting at with the word "kill"?
Not allowing a user to close their program
Prevent standard use of X button in window?
Minimize to task tray?
Not allow them to close the app in Task Manager?
Not allowing the OS to close their program
The requirement is ambiguous enough that I'd go talk to the requirement designer/boss to get a better idea of what they want.
Not only does this sound like a bad idea (it is abusive to your users) but you will not be able to prevent users from killing the process itself.
You would have to run two separate processes - one to run the application and a second one to monitor the first one and restart it if necessary.
You can't. You can make it harder, but not impossible. See The arms race between programs and users.
You'll have to reduce their user rights until they can't kill processes.
Control it with a Windows Service. Easy to do in C#. Lock down permissions to stop the service.
Note: I think the answers of "this is impossible/horrible/evil" are perhaps missing your point. A service is specifically designed 'keep going', which is what you're asking about.
More importantly, WHY are you rewriting a jabber client when so many good ones, like Miranda and Pidgin already exist? If it's for logging, you can easily do that server side on your Jabber server, and not rely on the clients.
If it's to prevent other IM services, robust firewall rules will help stop that (but it won't prevent it from the super geniuses who'll proxy AIM+Gtalk over https to their home servers).
You can catch most signals with handlers, except for SIGKILL.
You can create a watch dog windows process that respawns your application in the event it's terminated.
If you want, you can name this process something very innocuous sounding like "sysmon" so it doesn't look as sketchy.
I do hope this is a requirement for work, and not your way to bringing about the downfall of man.
sounds like you have access to the jabber client. Can you make it poll to a separate location with it's status and startup time? You aren't disabling the ability to kill it... but at least you can track it and respond from there.
Shouldn't this be controlled by your desktop group? We have PCs in a few kiosks that allow associates to check personal e-mail and stuff (Gmail, Yahoo, Hotmail, etc...), and the user permissions on those PCs will not allow users to kill processes.
Kind of annoying if IE locks up, but I can understand the reasoning.
Sounds like a case of this
Promise to suspend the users who kill your traffic logger Jabber client?
I agree that this is an awful idea.
Having said that, you'd create two programs (probably windows services). Both programs would monitor each other as well as functioning as the client. You would need shared memory that both processes could access to synch which client processes incoming requests.
You can prevent from the users to run TaskManager by GPO.
You can create your application as a Windows Service and prevent from the user kill the task manualy ( can be killed only from the services.msc )
Try to tie their hands :- )
go to actions and make a form closing event and in c# type e.cancel = true;
Unless you're really writing a virus, you should be able to block their ability to kill the process with permissions. Assuming they are all domain users and you are the admin.
I guess there would be a few cases where you would want to do this. You don't want users making security vulnerabilities. I can't exit or change any settings of Norton endpoint on my work computer, and it hasn't bothered me yet.
But if all the users are admins on their machines, and you want to make it impossible to close, and presumably impossible to start in safe made and remove... then you're asking: "How do I write malware?"
is there a way to be notified when a program is executed or terminated by a user in c#? I am talking about all the programs that a user can execute, not just a certain program. I would like to be notified whenever a user execute .exe files.
I can't even think of a keyword to google.
any suggestions would be appreciated!
The closest thing I know of would be to use Hooks.
You can use WH_SHELL Hooks to receive notification any time a new, non-owned, top level window is created or destroyed by the system. This isn't the same as a process, but it's pretty close in many cases, and potentially more useful in others (since it'd show a new word document window opening after one was already opened, even though they're using a shared process).
You might be able to combine that with EnumProcess to check to see if the process list has changed. This would work for tracking windows applications (but not services or console-based applications running in an existing console).
In Microsoft .NET Framework 3.5, you can get a list of Processes and register for the Process.Exited event. I suppose someone could implement a polling system in which they continually looked for new Processes, but that doesn't really notify you when something launches.
-- EDIT --
You might find this article useful. If you're willing to write a kernel mode driver, you can control every process start and finish.
Now, if you really want to get wild, you can hook into Microsoft Detours. Here is an interesting article about that.