Run an application if it’s not already running

Today we had a problem about an old Windows XP machine, running a 3rd party executable file. The executable sends info to a light board. Digging into problem I figured out that executable file is stopping with client interaction or by itself from time to time.

What we needed is to check if the app is running constantly. If it has been stopped we should run it. The process is not hanging so we don’t need anything there. Also the machine’s OS is old so we needed something other than WMI or PowerShell. I didn’t waste time to check if those are running on XP or not.

Here is how i solved it;

First I looked up for a batch file to do that and I came up with this thanks to Stack Overflow;

tasklist /FI "IMAGENAME eq TOTALCMD.EXE" /FO CSV &gt; search.log</code>

FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

cd "C:\TotalCMD"
start TOTALCMD.EXE

:end

del search.log

I tested it with good old TOTALCMD.EXE. You can test this with your executable. It’s pure DOS.

Then I feel like unhappy with the unnecessary log file I created etc. Then I coded a small Console Application and compiled it with .NET 2.0.

Here is the code:

        static void Main(string[] args)
        {
            if (args.Length != 2 || string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]))
            {
                Console.WriteLine(@"Rerun Process
Usage: RERUNPROCESS.EXE [EXECUTABLENAME] [PATH]
");
                return;
            }

            Process thisProc = Process.GetCurrentProcess();
            if (!IsProcessOpen(args[0].ToLower().Replace(".exe", "")))
            {
                StartProcess(args);
            }
            else
            {
                Console.WriteLine("{0} Process Is Already Running", args[0]);
            }
        }

        private static void StartProcess(string[] args)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = Path.Combine(args[1], args[0]);
            try
            {
                p.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Rerunning {0}\n{1}", Path.Combine(args[1], args[0]), ex.Message);
            }
        }

        private static bool IsProcessOpen(string name)
        {
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.ToLower().Contains(name))
                {
                    return true;
                }
            }
            return false;
        }

What this app does is pretty straightforward. It checks for the app name in processes. If not exits, it tries to run it. I used System.Diagnostics.Process to create a new process and redirect output to that process.

Process.GetProcesses() gets all the running processes. Here is the usage if you are not happy with it or want to alter it. http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx

You can call the program like the example below;

RerunApp [Executable] [Path]
RerunApp “MYAPP.EXE” “C:\My Folder\My App\”

You can schedule it with windows task manager with the parameters you want and almost have Windows Service like behavior in old systems when running 3rd party executable files.

Here is the source; https://github.com/serkanberksoy/RerunApp

Happy Coding 🙂

Delete All Your Yahoo Mail with AutoIt

UPDATE – I tried to cleanup my yahoo mail recently. They fixed the problem with the new interface. You can scroll down and select all messages. Then do what you want with them like moving to another folder or deleting.

Yesterday I had a problem. Yahoo didn’t allow me to delete all mail in a folder.

I had 20k mail in my old Customers’ folder. I redirected all application system warnings to my yahoo mail and I forgot to maintain it. After a year it was like 20k of mails. I tried everything to delete those mails by filtering etc. but Yahoo wouldn’t bend to my will. So I thought there should be another solution and I decided to do it with brute force.

There is a great application called AutoIt. I used it once to automate some UI tasks and develop automated tests. It provides you a scripting language that you can pretty much automate anything that you do with your mouse and keyboard.

You can download it here;
http://www.autoitscript.com/site/

Also there is an AutoItRecorder application to record your mouse moves and key presses, then save all recording session as an AutoIt script. You can download it here;
http://sourceforge.net/projects/autoit-recorder/

Note: The shortcut for autoit-recorder launches an error but you can go manually to C:\Program Files (x86)\INET-Consulting\AutoIT-Recorder

So here is how I use both apps together;

1. Run autoit-recorder and do what you want to do. CTRL+BREAK to stop recorder.

autoit-recorder

2. Save your script to a file, it creates a large file, which every mouse coordinate recorded in it.

3. Right click to script file and select Edit Script. This opens the cute Auto-It editor. You don’t need another editor, Auto-It editor is great for these kind of operations. Also you can test your script by hitting F5 and stop by CTRL+BREAK in the editor.

4. So, you got large record file with lots of mousemove(x, y) coordinates. You actually don’t need all the coordinates to run this script. So find out lines like where the MouseDown(“left”) code exists. These are the lines that you actually click something. Also the first line with MouseMove command above this MouseDown line is the line that your final destination is. You only need these to go somewhere and click something on the screen. The other MouseMove lines between MouseDown commands may be deleted.

5. Also you may need to put some delay between MouseMove, MouseDown and other methods. If it’s a web page that you are automating your task, it may not respond your next move. We do it with putting a sleep command in between MouseMove and MouseDown methods.

Sleep (500) -> 500 is default that I use as milliseconds. But if I need to wait for a web page to reload I use at least Sleep(5000) (5 seconds) depending on the web page performance.

Here is my code for deleting yahoo mail. It works on Chrome browser with 1920 x 1080 resolution. You may change $pageCount variable for your need. Currently it deletes 70 pages of mails.
What my script does is straighforward. It deletes all mail page by page. To do that; first goes to checkbox at the upper left corner, clicks it. Then goes to delete button and clicks it. Goes to OK button and clicks it. Waits for 5 seconds. When page updates, it scrolls 2 lines down, so it presses Home key to keep coordinates intact. After that it goes and clicks to next page.

– Remember it deletes ALL mail in that folder. So be careful. I am not responsible if you delete wrong mail.
– If you have different resolution, different browser etc. You need to record your script or alter the coordinates below. 

dim $i
$i = 0

dim $pageCount
$pageCount = 70

While($i < $pageCount)
   MouseMove(196, 193)
   Sleep (500)
   MouseDown("left")
   MouseUp("left")
   Sleep (500)

   MouseMove(210, 173)
   Sleep (500)
   MouseDown("left")
   MouseUp("left")
   Sleep (500)

   MouseMove(796, 596)
   Sleep (500)
   MouseDown("left")
   MouseUp("left")
   Sleep (5000)

   Send("{HOME DOWN}")
   Send("{HOME UP}")
   Sleep (500)

   MouseMove(1708, 199)
   Sleep (500)
   MouseDown("left")
   MouseUp("left")
   Sleep (1000)

   $i = $i + 1
WEnd

Happy Coding 🙂