Monday, June 29, 2015

Temporary Directory

I needed a way to make sure a folder was deleted after using it in a unit test, this was what I came up with...

To create a new folder with "." as the parent folder:
TemporaryDirectory.CreateNew(".")


To wrap a round a previously created folder "C:\Temp\unit_test":
TemporaryDirectory.Wrap("C:\Temp\unit_test")


Sample unit test:
[TestMethod]
public void create_remove()
{
    string folderPath;
    using (var folder = TemporaryDirectory.CreateNew("."))
    {
        folderPath = folder.Folder;
        var path = Path.Combine(folderPath, "test.txt");
        File.WriteAllText(path, "Test");
    }
    Assert.IsFalse(Directory.Exists(folderPath));
}


And finaly the TemporaryDirectory class, with a DeleteDirectory method that ensures the deletion of the folder even if its open in Windows Explorere.
public sealed class TemporaryDirectory : IDisposable
{
    private static int MaximumAttempts = 10;
    public string Folder { get; private set; }

    private TemporaryDirectory(string path)
    {
        Folder = Path.GetFullPath(path);
        Directory.CreateDirectory(Folder);
    }

    public void Dispose()
    {
        DeleteDirectory(Folder);
    }

    public static TemporaryDirectory CreateNew(string pathToParentDirectory)
    {
        var path = Path.Combine(pathToParentDirectory, Guid.NewGuid().ToString());
        return new TemporaryDirectory(path);
    }

    public static TemporaryDirectory Wrap(string path)
    {
        return new TemporaryDirectory(path);
    }

    public static void DeleteDirectory(string path)
    {
        if (path == null) throw new ArgumentNullException("path");
        var attempts = 0;
        var exists = Directory.Exists(path);
        while (exists)
        {
            try
            {
                attempts++;
                if (Directory.Exists(path)) Directory.Delete(path, true);
                exists = false;
            }
            catch (IOException)
            {
                Thread.Yield();
                if (attempts >= MaximumAttempts) throw;
            }
            catch (UnauthorizedAccessException)
            {
                Thread.Yield();
                if (attempts >= MaximumAttempts) throw;
            }
        }
    }
}

Tuesday, December 2, 2014

xUnit.net, JUnit & Jenkins

How to publish xUnit.net 2.0 results in Jenkins.

Files in attached zip file to put in the root folder of the Jenkins workspace are runxunit.bat and xUnit2ToJUnit.xslt.
xunit.net_jenkins_v1.zip
  1. Add Jenkins xUnit Plugin
  2. Add NuGet packages.
  3. Add Build command for running tests.
  4. Add Post-build Action for publishing test result. 



1. Add Jenkins xUnit Plugin

Add the xUnit Plugin to your Jenkins server.



2. Add NuGet packages.

Add the following nuget packages.
xunit
xunit.abstractions
xunit.assert
xunit.core
xunit.runners



3. Add Build command for running tests.

Add a build command as in this image, after the project build command.
Exchange PATH_TO_DLL_WITH_TESTS with the actual path to the dll with tests.




4. Add Post-build Action for publishing test result.

Add a post build action like in this image.

Tuesday, March 12, 2013

PropertyWrapper

One way to fake indexed properties in C# 

In .NET framework indexed properties is allowed, but not in the C# language.
Whether that's good or bad is debatable, but sometimes they would be very convinient.

When converting a large VB.NET application I encountered a massive amount of indexed properties that I had to fix in some way.

The solution I came up with was to create PropertyWrapper classes.
public class PropertyWrapper<TK, T>
{
    private readonly Func<TK, T> _getMethod;
    private readonly Action<TK, T> _setMethod;

    public PropertyWrapper(Func<TK, T> getMethod,
                           Action<TK, T> setMethod)
    {
        _getMethod = getMethod;
        _setMethod = setMethod;
    }

    public T this[TK key]
    {
        get
        {
            if (_getMethod == null) return default(T);
            return _getMethod(key);
        }
        set
        {
            if (_setMethod == null) return;
            _setMethod(key, value);
        }
    }
}
public class PropertyWrapperRead<TK, T>
{
    private readonly Func<TK, T> _getMethod;

    public PropertyWrapperRead(Func<TK, T> getMethod)
    {
        _getMethod = getMethod;
    }

    public T this[TK key]
    {
        get
        {
            if (_getMethod == null) return default(T);
            return _getMethod(key);
        }
    }
}
And this is how to use it.
public class ClassWithIndexedProperty
{
    private List<Person> _persons = new List<Person>()
        {
            new Person(1,"First"),
            new Person(2,"Second"),
            new Person(4,"Fourth"),
        };

    public PropertyWrapper<int, string> Name
    {
        get
        {
            return new PropertyWrapper<int, string>(
                (key) =>
                    {
                        var person = _persons.FirstOrDefault(p => p.Number == key);
                        return person != null ? person.Name : null;
                    },
                (key, value) =>
                    {
                        var person = _persons.FirstOrDefault(p => p.Number == key);
                        if (person == null)
                        {
                            _persons.Add(new Person(key, value));
                        }
                        else
                        {
                            person.Name = value;
                        }
                    });
        }
    }
}
If properties with more indexes is needed just create more classes with signatures like this...
public class PropertyWrapper<TKey1, TKey2, TResult>
public class PropertyWrapper<TKey1, TKey2, TKey3, TResult>
public class PropertyWrapper<TKey1, TKey2, TKey3, TKey4, TResult>

Thursday, November 8, 2012

Debugging python in Google App Engine with Visual Studio

This guide might not work anymore, try this instead:
http://joesdevnotepad.blogspot.co.at/2014/07/remote-debug-google-app-engine.html

This is what you need, download and install in this order:
  1. Visual Studio 2012
  2. Python  (latest 2.7.? version) 
  3. Python Tools for Visual Studio
  4. Google App Engine SDK for Python
Read the Getting started tutorial when you get to the Hello World example instead of creating a directory,  you just create a "Python Application" project in Visual Studio with the name helloworld, then just continue follow the tutorial and create the files needed in Visual Studio instead.

To be able to run and debug the application from Visual Studio there are some project properties you need to fill in:

General->Startup File: C:\Program Files (x86)\Google\google_appengine\dev_appserver.py
General->Working Directory: ..
General->Interpreter: Python 64-bit 2.7 or Python 32-bit 2.7
Debug->Search Paths: C:\Program Files (x86)\Google\google_appengine;.
Debug->Script Arguments: --use_sqlite helloworld

Start debugging.

You will get a ZipImportError exception.
This exception can be ignored and this is how you do that:
  • Open Debug->Exceptions... 
  • click the Add button.
  • Set type to "Python Exceptions" and in the name field write this:
  • google.appengine.dist.py_zipimport.ZipImportError 
  • click the OK button and uncheck the User-unhandled checkbox
  • click OK and continue execution.
Now you're good to go, enjoy.


References:
PTVS - Setup and Debugging of Google App Engine with Python Tools for Visual Studio

Monday, November 5, 2012

Bitbucket

A couple of months ago I created an account on bitbucket.org.

The first project I published was LightWpfControls, it's the start of a collection of WPF controls.

The first control in the collection is what I choose to call a tracker. A tracker is what I would call a two dimensional slider control. I spent quite some time to find, using search terms like "2D Slider", "track pad", "joy stick" and many more. But I struck out, so I ended up creating one my self.


There is two different shapes of the tracker square and circular.


The project can be found here: LightWpfControls

Thursday, October 18, 2012

Visual Studio 2012 Extensions...

Updated 2013-05-08

I'm not going to bring up the obvious extensions like ReSharper, CodeRush, NuGet or Sourcecode Control Providers.

This one's for the "unknown" extensions...

It started almost 30 years ago with a boy growing up in the middle of nowhere. There where a lot of trees and a lot of grass and almost no computers anywhere.
I didn't start my career with punch cards or anything like that, don't get me wrong but that's ancient.
How ever IBM Dos 2.16 isn't far from punch cards compared to an iPhone.

But I digress..

What I wanted to say is, find the fun stuff in life; I know I have and that's writing code.

So, to have more time to write code you use tools that makes every keystroke count.
I like Visual Studio, but there is always room for improvment...

Here is my favorite Visual Studio Extensions in alphabetical order:

 What's yours?

Thursday, March 11, 2010

Multi boolean compare

I run in to a problem where I had multiple boolean values each corresponding to a string value.
When one of the boolean values was true the corresponding string value would be used to populate a field in a report, but if more than one boolean value was true or all boolean value was false, empty string would be used to populate the report field.

This was solved by a lot of if´s, something like this:

if (boolean1 && !boolean2 && ...)
{
 SetField("value1");
}
else if (!boolean1 && boolean2 && ...)
{
 SetField("value2");
}
...
else
{
 SetField("");
}

When there was a lot of boolean/string value pairs there was a massive amount of if´s.
It made it kind of hard to read when most reports had about 150 fields.
That made me think, there has to be something I can do about it...
There might be a solution with linq involved but, I had to deal with .net 2.0 so no linq.

This is the solution I came up with:

public class MultiBooleanComparer
{
 private readonly List<bool> _keys;
 private readonly List<string> _values;

 public MultiBooleanComparer()
 {
  _keys = new List<bool>();
  _values = new List<string>();
 }

 public void Add(bool key, string value)
 {
  _keys.Add(key);
  _values.Add(value);
 }

 public string GetValue()
 {
  return ToString();
 }

 public override string ToString()
 {
  return _keys.FindAll(WhereTrue).Count != 1 ? string.Empty : _values[_keys.IndexOf(true)];
 }

 private static bool WhereTrue(bool obj)
 {
  return obj;
 }
}

MultiBooleanCompare multi = new MultiBooleanCompare();
multi.Add(boolean1, "value1");
multi.Add(boolean2, "value2");
multi.Add(boolean3, "value3");
multi.Add(boolean4, "value4");
multi.Add(boolean5, "value5");
SetField(multi.ToString());

Tuesday, September 29, 2009

Thread-safe general delegate invoke method

When dealing with events and delegates in a UI with worker threads you have to check if check if invocation is required in the eventhandler.
Instead of doing the test in all eventhandlers I made a general Invoke method to handle this.
When invocation is not required this method is slower, but when invocation is required it´s faster.
The thing for me is that if I always use this method I don´t have to worry about dealing with this in every eventhandler or when raising events.

public static class ThreadUtility
{
 public static void Invoke(Delegate source, params object[] args)
 {
  if (source == null) return;
  int paramCount = source.Method.GetParameters().Length;
  if (paramCount != args.Length) throw (new ArgumentException(string.Format("Invalid number of parameters. {0} was expected, {1} was supplied", paramCount, args.Length)));
  foreach (Delegate invocationItem in source.GetInvocationList())
  {
   if (IsDisposed(invocationItem.Target)) continue;
   ISynchronizeInvoke target = invocationItem.Target as ISynchronizeInvoke;
   if (target != null && target.InvokeRequired)
   {
    target.BeginInvoke(invocationItem, args);
   }
   else
   {
    invocationItem.DynamicInvoke(args);
   }
  }
 }

 private static bool IsDisposed(object target)
 {
  PropertyInfo propertyInfo = target.GetType().GetProperty("IsDisposed");
  if (propertyInfo == null) return (false);
  return ((bool)propertyInfo.GetValue(target, null));
 }
}

This is how it looks the old way...

public event EventHandler ThreadUtilTest;
public void OnThreadUtilTest()
{
 EventHandler temp = ThreadUtilTest;
 if (temp != null)
 {
  temp(this, new EventArgs());
 }
}

private void ThreadUtilTestHandler(object sender, EventArgs e)
{
 if (InvokeRequired)
 {
  Invoke(temp, sender, e);
  return;
 }
 // Execute operation
}

...and this is how it looks the with my method...

public event EventHandler ThreadUtilTest;
public void OnThreadUtilTest()
{
 ThreadUtility.Invoke(ThreadUtilTest, this, new EventArgs());
}

private void ThreadUtilTestHandler(object sender, EventArgs e)
{
 // Execute operation
}

When using events you usualy don´t want to add multiple instances of the same eventhandlers for the same object.
Here´s a way to avoid that...

private object _eventSychLock = new object();
private EventHandler _event;
public event EventHandler ThreadUtilTest
{
 add
 {
  lock (_eventSychLock)
  {
   if (!ThreadUtility.InInvocationList(_event, value))
   {
    _event += value;
   }
  }
 }
 remove
 {
  lock (_eventSychLock)
  {
   _event -= value;
  }
 }
}

public void OnThreadUtilTest()
{
 ThreadUtility.Invoke(_event, this, new EventArgs());
}

public static class ThreadUtility
{
 public static bool InInvocationList(Delegate source, Delegate subscriber)
 {
  if (source == null) return (false);
  if (subscriber == null) return (true);
  foreach (Delegate invocationItem in source.GetInvocationList())
  {
   if (invocationItem == subscriber) return (true);
  }
  return (false);
 }
}

Monday, June 22, 2009

How to use comments wisely

How can comments be a security issue?

  1. If you have to use comments to explain your code, the code is probably too complicated. When creating a complicated solution to solve a problem you insert errors, bugs or just making it har to maintain.
  2. A comment that doesn´t describe the code correctly may lead readers of the code to think it does something it doesn´t, making it harder to maintain.
  3. Comments gets stale, when you change/refactor your code you´ll forget to change your comments. Se #2.
  4. It may be hard to correctly describe what the code does in plain text. Se #2.

Code should be written in a way to make comments redundant.
For example give methods, variables and fields names to describe what they do or what they are representing is a good start.

Use comments to document how to use classes and methods, for other programmers using them to know how to. Be sure to update the documentation as you change/refactor the code.

Finally a quote I really like:
"When I have a specific goal in mind and a complicated piece of code to write, I spend my time making it happen rather than telling myself stories about it." - Steve Yegge

Thursday, June 11, 2009

To TryParse or not, is it a question?

Use TryParse when converting a string to a ValueType.

Why?
There´s really no reason not to, it is:
- faster.
- safer, you will not have to be bothered with exceptions.
- easy, for all but DateTime.
and it will always work, unless you want an exception to be propagated.

Using Xxx.Parse or Convert.ToXxx will throw an exception if the string is not valid for conversion.
You may think that when an invalid value is rare the Xxx.Parse or Convert.ToXxx is not gonna throw an exception and it will be faster for most cases.

If you do, my opinion is you´re wrong.
Throwing exceptions when you can avoid it is bad practice and (cpu)time consuming.
Making it a habit to ignore this sort of basic rules is going to lead to other bad decisions when writing code.

I have tried it my self but I have no data to support it.
Others have, look at the result they´ve made:

Parsing Performance @stackoverflow
TryParse and the Exception Tax @codinghorror
int.Parse for Integer Conversion in C# @dotnetperls


Examples
public static Int32 ToInt32(string text)
{
   Int32 result;
   if (Int32.TryParse(text, out result))
   {
       return (result);
   }
   return (0);
}
The only reason to convert to a data type from string and depending on try-catch is if you are using a method with a generic data type as input and you know that invalid values is rare.
public static T ConvertToType<T>(string text)
{
   try
   {
       if (string.IsNullOrEmpty(text))
       {
           return (default(T));
       }
       return (T)Convert.ChangeType(text, typeof(T), CultureInfo.CurrentUICulture);
   }
   catch
   {
       return (default(T));
   }
}
Or a general method for conversion of string to an unknown(at design time) datatype:
public static object ConvertToType(string text, Type type)
{
   object defaultValue = GetDefault(type);
   try
   {
       if (string.IsNullOrEmpty(text))
       {
           return (defaultValue);
       }
       return (Convert.ChangeType(text, type, CultureInfo.CurrentUICulture));
   }
   catch
   {
       return (defaultValue);
   }
}


Conclusion
Use TryParse if you don´t want an exception to propagate or you want to use a generic method and you know that an invalid value is rare.