Visual Studio:TaskKill only if Process exists

My primary tool for development is Visual Studio. Often while building and testing applications, I have face the following scenario numerous times:

  • I build and run the application (Ctrl + F5).
  • I test my application and feel the need for some more changes in the code.
  • I go back to the code and modify and build again.
  • Visual Studio gives me the following error message:

Unable to copy file “MyApp.exe” to “\Debug\MyApp.exe”. The process cannot access the file ‘..\Debug\MyApp.exe’ because it is being used by another process.
Only then I realize that I had forgotten to close the application before rebuilding. :(

I was thinking of finding a way to automatically close the application before each build. Initially I put the command “taskkill /f /im MyApp.exe” in the Pre-Build events of the project but this worked only if the application was running. If the application was already closed, the build failed with an error message saying that the script failed with an exit code 1.

I then found another solution on the web (link). This still gave me the same error. So, I tweaked it further to arrive at this script:

tasklist /FI "IMAGENAME eq $(TargetName).exe" 2>NUL | find /I /N "$(TargetName).exe">NUL
if "%ERRORLEVEL%"=="0" (taskkill /f /im $(TargetName).exe
) else ( exit 0)

It proved very effective and time-saving too!

Note: The above script will work only if you are building an .exe application. If you are building a DLL, try putting the name of the application, which is using the DLL, in place of $(TargetName).

Happy Coding! :)

P.S. I found another simpler solution here

taskkill /F /IM $(TargetName).exe 2>&1 | exit /B 0

FloTiles reviewed

Logo

Check out the review of my FloTiles game at Windows 8 Review. You can read the review here.

FluidMoveBehavior Bug (& Memory Leak!)

Back in August, two people, tmccowan and Bullimann, brought into my notice a bug associated with the FluidMoveBehavior in WPF. This issue can be found here. Since one of the controls (ToggleSwitch) in my WPFSpark project was using this behavior, the issue was preventing the garbage collection of the control. According to the post, the static TagDictionary in FluidMoveBehaviorBase is holding references of the associated objects and thus preventing them from being GCed.

Steve Greatrex posted a workaround subscribe to the UserControl.Unloaded event and in the handler call the Detach method of the FluidMoveBehavior.
I tried this workaround and did a memory profiling with ANTS Memory Profiler  (a really great tool!). To my dismay, this workaround had little effect. I thought the Detach method would remove the reference of the ToggleSwitch’s internal Grid but it didn’t. So the instances of ToggleSwitch kept piling in memory each time they were instantiated. (see images)

MemProfile1

MemProfile2
I debugged the code and dug in deeper into the FluidMoveBehaviorBase to see the contents of the TagDictionary object. In this dictionary, the Key is the object to which FluidMoveBehavior is added and the Value is an internal class called TagData which encapsulates the following properties: The object itself(Child), the object’s Parent, ParentRect, AppRect, TimeStamp and InitialTag.
So I thought of a different workaround using Reflection. In the UserControl.Unloaded event handler:
1. Get access to the TagDictionary field in the FluidMoveBehaviorBase.
2. Invoke the ContainsKey method to check if the object is added as a key in the dictionary.
3. If ContainsKey method returns true, then invoke the Remove method to remove the object from the dictionary.

private void OnUnloaded(object sender, RoutedEventArgs e)
{
    this.Unloaded -= OnUnloaded;
    DetachFluidMoveBehavior(rootGrid);
}

private void DetachFluidMoveBehavior(DependencyObject depObj)
{
    if (depObj != null)
    {
        foreach (var b in Interaction.GetBehaviors(depObj).OfType<FluidMoveBehavior>())
        {
            b.IsActive = false;
            b.Detach();
            // HACK: This hack is to remove the depObj from the TagDictionary collection using reflection as 
            // the TagDictionary collection is holding up the reference of depObj leading to its non-garbage collection of depObj (a.k.a Leak!)
            FieldInfo fieldInfo = typeof(FluidMoveBehaviorBase).GetField("TagDictionary", BindingFlags.Static | BindingFlags.NonPublic);
            if (fieldInfo == null)
                continue;

            // Get the TagDictionary object
            var tagDict = fieldInfo.GetValue(b);

            // Get the ContainsKey MethodInfo
            MethodInfo miContainsKey = fieldInfo.FieldType.GetMethod("ContainsKey");
            if (miContainsKey != null)
            {
                // Does the TagDictionary contain depObj as a key?
                bool containsKey = (bool)miContainsKey.Invoke(tagDict, new object[] { depObj });
                if (containsKey)
                {
                    // Get the Remove Method Info
                    MethodInfo miRemove = fieldInfo.FieldType.GetMethod("Remove");
                    if (miRemove != null)
                    {
                        // Remove the depObj from the TagDictionary
                        miRemove.Invoke(tagDict, new object[] { depObj });
                    }
                }
            }
        }
    }
}

Though this is a crude solution, it does its job.

This workaround has been incorporated in WPFSpark v1.2 which I will be releasing soon.

I hope Microsoft fixes this issue in the next release. :)

FloTiles v1.0 released!

Logo

I am really excited to say that the next game which I was working on is finally complete and released in the Windows Store. It is called FloTiles  and it is a Windows 8 Metro application. It is also my entry to The Windows 8* & Ultrabook™ App Innovation Contest sponsored by Intel and hosted in CodeProject.

There were two rounds in this contest. In the first round, we had to write an article in CodeProject summarizing our idea for the app for this contest. Based on that, Intel would be providing us an Ultrabook as a 3 year loan. I passed the first round and got the Ultrabook within a few weeks. The deadline for the second round was Nov 21 for the app to be submitted to either the Windows Store or Intel’s AppUp store. But the judging would be done only after December 1st. This gap gave me ample time to add more tweaks and features to my first submission.

You can read in detail about the FloTiles game in my CodeProject article which I updated yesterday. It is the longest article I have written yet as it details the various components and  features incorporated during the development of this app.

The FloTiles game is available for download from the Windows Store here.

Accessing Dropbox via .NET

One of my recent assignments involved storing of a configuration file in Dropbox so that it can be accessed by my application from anywhere around the world. This was a new area of exploration for me as I had no idea how to make a .NET application communicate to Dropbox. This gave me an opportunity to learn something new and I jumped at it.
My first step was to create a Dropbox account and go through their documentation of the REST APIs. Dropbox does not have an official SDK to access it via .NET (though third party libraries are available).
The next step was to search online. Surely, someone would have faced a similar problem and someone else would have suggested some solution to it. I visited several forums where people had posted questions on this issue.
One such forum led me to Christophe Geers’ Blog. This guy has done a tremendous job of writing a series of excellent articles describing the various steps you need to perform to get access to the Dropbox account, creating of folders, uploading and downloading of files, etc. These articles are what a beginner needs to get an solid understanding of programmatic access to DropBox. The accompanying source code is an added bonus.
Do check out his articles here.

Back from Hibernation!

Hello again! I’m back! It has been more than 9 months since I posted in my blog. Actually I planned on taking a short break from blogging as life was becoming pretty hectic, both personally as well as professionally. Soon the short break became long enough to be classified as hibernation. :)

On the personal front, God blessed my wife and me with a boy, four months back. Life has definitely changed a lots with the arrival of our bundle of joy.
Nowadays, I get very little time to pursue personal projects which has resulted in a backlog of several projects begging to be relieved of their pending status. I have slowly started working on them once again and hopefully I shall blog more regularly describing my progress.
In one of my previous blogs, I had mentioned that I was a finalist in the Windows 8 First Apps contest organized by Microsoft. Well, I am happy to say that I was one of the 8 winners of this competition. As the prize, I got a Samsung tablet (the same that was given to the attendees in Build 2011), 2 years of Windows Store membership and 1 year of Azure membership.

Here are a few of the personal projects that I am currently working on:

  • WPFSpark 1.2 : Minor bug fixes and addition of features requested by the users. Plus, addition of a new control.
  • Porting of WPFSpark controls to Windows 8 : Updating the code to utilize the WinRT libraries and take advantage of the asynchronous programming model.
  • Updating FlipSaw to the Windows 8 Release Preview (and then to RTM) : This has been a long pending task. Progress on this has been real slow, though I am happy to say that I am in the final phase of updation and am hoping to upload it to the Windows Store before the release of Windows 8 to the world.
  • FloTiles: This is the name of my next game which I am currently developing. It is a Windows 8 Metro application. It is also my entry to The Windows 8* & Ultrabook™ App Innovation Contest sponsored by Intel and hosted in CodeProject.

WPFSpark v1.1 released!

WPFSpark v1.1 is now released!

WPFSpark v1.1 brings a major revamp of the FluidWrapPanel control.


The core logic of FluidWrapPanel class has been rewritten from scratch to make it more robust and usable in various scenarios, resulting in a faster, optimized code.
These changes are breaking changes, meaning if you are using the latest WPFSpark library (v1.1) then your old code using the old FluidWrapPanel will not compile unless you update it. The interface IFluidDrag has been removed. Child elements no longer need to implement the IFluidDrag interface to participate in the drag and drop interaction. Instead I have added a new Behavior called FluidMouseDragBehavior which would facilitate the child element with drag and drop interaction. Child elements must add this behavior to participate in drag and drop.

Get the latest WPFSpark source code here.

Follow

Get every new post delivered to your Inbox.