Programming

Here’s a bunch of regexes which help pares things in notepad++.

Get revision numbers of svn log

This parses the svn log and just returns the revision numbers, comma separated.
You need to add “—-” at the end of the file.
Revision: ([0-9]+).*?----[\r\n]*

If you want to comment out a XAML attribute, follow the following scheme to complete this:

  1. Import the Open XML markup compatibility elements:
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  2. Add another xmlns statement mapping a prefix of your choice (like “ignore”) to an URI of your choice. This URI does not need to point to anything on the web. This is just a unique resource identifier.
    xmlns:ignore="http://something.com/ignore"
  3. Use the mc:Ignorable property to set the new prefix as ignorable.
    mc:Ignorable="ignore"

    Note: If you already had one ignorable prefix defined (for example the “d” prefix that Expression Blend and the Visual Studio designer use), no problems. Just add the new prefix to the Ignorable list with a space to separate the prefixes.

    mc:Ignorable="d ignore"

(Source)

If there is an assembly which was not created as a WCF assembly you cannot add for example a new WPF Window with the “Add new Item”. To solve this, the assembly need to be marked as a “WPF”-assembly.

Follow the following steps to complete this:

  1. Edit the .proj file
  2. Add {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} into the first property group

So the final .proj file looks someting like:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{2842585C-0E4F-4A4A-92D6-FCC062A3C0F8}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>ArxWidgetManager</RootNamespace>
    <AssemblyName>ArxWidgetManager</AssemblyName>
    <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <WarningLevel>4</WarningLevel>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    ...

For completeness sake, here’s a list of some other project types:

ASP.NET MVC 1.0 {603C0E0B-DB56-11DC-BE95-000D561079B0}
ASP.NET MVC 2.0 {F85E285D-A4E0-4152-9332-AB1D724D3325}
ASP.NET MVC 3.0 {E53F8FEA-EAE0-44A6-8774-FFD645390401}
ASP.NET MVC 4.0 {E3E379DF-F4C6-4180-9B81-6769533ABE47}
C# {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
C++ {8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}
Database {A9ACE9BB-CECE-4E62-9AA4-C7E7C5BD2124}
Database (other project types) {4F174C21-8C12-11D0-8340-0000F80270F8}
Deployment Cab {3EA9E505-35AC-4774-B492-AD1749C4943A}
Deployment Merge Module {06A35CCD-C46D-44D5-987B-CF40FF872267}
Deployment Setup {978C614F-708E-4E1A-B201-565925725DBA}
Deployment Smart Device Cab {AB322303-2255-48EF-A496-5904EB18DA55}
Distributed System {F135691A-BF7E-435D-8960-F99683D2D49C}
Dynamics 2012 AX C# in AOT {BF6F8E12-879D-49E7-ADF0-5503146B24B8}
F# {F2A71F9B-5D33-465A-A702-920D77279786}
J# {E6FDF86B-F3D1-11D4-8576-0002A516ECE8}
Legacy (2003) Smart Device (C#) {20D4826A-C6FA-45DB-90F4-C717570B9F32}
Legacy (2003) Smart Device (VB.NET) {CB4CE8C6-1BDB-4DC7-A4D3-65A1999772F8}
Model-View-Controller v2 (MVC2) {F85E285D-A4E0-4152-9332-AB1D724D3325}
Model-View-Controller v3 (MVC3) {E53F8FEA-EAE0-44A6-8774-FFD645390401}
Model-View-Controller v4 (MVC4) {E3E379DF-F4C6-4180-9B81-6769533ABE47}
Mono for Android {EFBA0AD7-5A72-4C68-AF49-83D382785DCF}
MonoTouch {6BC8ED88-2882-458C-8E55-DFD12B67127B}
MonoTouch Binding {F5B4F3BC-B597-4E2B-B552-EF5D8A32436F}
Portable Class Library {786C830F-07A1-408B-BD7F-6EE04809D6DB}
SharePoint (C#) {593B0543-81F6-4436-BA1E-4747859CAAE2}
SharePoint (VB.NET) {EC05E597-79D4-47f3-ADA0-324C4F7C7484}
SharePoint Workflow {F8810EC1-6754-47FC-A15F-DFABD2E3FA90}
Silverlight {A1591282-1198-4647-A2B1-27E5FF5F6F3B}
Smart Device (C#) {4D628B5B-2FBC-4AA6-8C16-197242AEB884}
Smart Device (VB.NET) {68B1623D-7FB9-47D8-8664-7ECEA3297D4F}
Solution Folder {2150E333-8FDC-42A3-9474-1A3956D46DE8}
Test {3AC096D0-A1C2-E12C-1390-A8335801FDAB}
VB.NET {F184B08F-C81C-45F6-A57F-5ABD9991F28F}
Visual Database Tools {C252FEB5-A946-4202-B1D4-9916A0590387}
Visual Studio Tools for Applications (VSTA) {A860303F-1F3F-4691-B57E-529FC101A107}
Visual Studio Tools for Office (VSTO) {BAA0C2D2-18E2-41B9-852F-F413020CAA33}
Web Application {349C5851-65DF-11DA-9384-00065B846F21}
Web Site {E24C65DC-7377-472B-9ABA-BC803B73C61A}
Windows (C#) {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
Windows (VB.NET) {F184B08F-C81C-45F6-A57F-5ABD9991F28F}
Windows (Visual C++) {8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}
Windows Communication Foundation (WCF) {3D9AD99F-2412-4246-B90B-4EAA41C64699}
Windows Phone 8/8.1 Blank/Hub/Webview App {76F1466A-8B6D-4E39-A767-685A06062A39}
Windows Phone 8/8.1 App (C#) {C089C8C0-30E0-4E22-80C0-CE093F111A43}
Windows Phone 8/8.1 App (VB.NET) {DB03555F-0C8B-43BE-9FF9-57896B3C5E56}
Windows Presentation Foundation (WPF) {60DC8134-EBA5-43B8-BCC9-BB4BC16C2548}
Windows Store (Metro) Apps & Components {BC8A1FFA-BEE3-4634-8014-F334798102B3}
Workflow (C#) {14822709-B5A1-4724-98CA-57A101D1B079}
Workflow (VB.NET) {D59BE175-2ED0-4C54-BE3D-CDAA9F3214C8}
Workflow Foundation {32F31D43-81CC-4C15-9DE6-3FC5453562B6}
Xamarin.Android {EFBA0AD7-5A72-4C68-AF49-83D382785DCF}
Xamarin.iOS {6BC8ED88-2882-458C-8E55-DFD12B67127B}
XNA (Windows) {6D335F3A-9D43-41b4-9D22-F6F17C4BE596}
XNA (XBox) {2DF5C3F4-5A5F-47a9-8E94-23B4456F55E2}
XNA (Zune) {D399B71A-8929-442a-A9AC-8BEC78BB2433}

(Source)

Trying to be MVVM compliant is not always easy.

Take the following scenario:

There is a model with a property “Status”. This property changes values according to some logic in the model. This property should now be presented in the view. To have correct MVVM, the ViewModel has also a property “Status”, which is bound to the view.
So, now how can the model inform the viewmodel when the “Status” of the model changed?

The best bet is to have a StatusChanged event on the model and let the viewmodel subscribe to it and fire the viewmodel’s own propertychanged for it’s “Status” property. This can get quite tedious so I created a small helper: PropertyChangedProxy

For this, the model and the viewmodel need to implement INotifyPropertyChanged. Then on the viewmodel, you can create new a new instance of the PropertyChangedProxy for each property of the model where you want the viewmodel to be notified, in a typesafe way.

Such an instance would look like this:

var statusPropertyChangedProxy = new PropertyChangedProxy<MainModel, StatusType>(
	_model, m => m.Status,
	newValue => OnPropertyChanged("Status"));

So as you see, you just need to give the source (which is the model), the property of the source (as a nice expression) and an action, that should be called when the source’s property changes (which in this case is just to fire a OnPropertyChanged on the ViewModel itself).

Here’s a complete small example of a model and viewmodel, where the viewmodel is automatically notified when the model’s “Status” changes so that the viewmodel can forward this to the view:

public class MyModel : INotifyPropertyChanged
{
	private string _status;
	public string Status
	{
		get { return _status; }
		set { _status = value; OnPropertyChanged(); }
	}

	// Default INotifyPropertyChanged
	public event PropertyChangedEventHandler PropertyChanged;
	protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
	{
		var handler = PropertyChanged;
		if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
	}
}

public class MyViewModel : INotifyPropertyChanged
{
	public string Status
	{
		get { return _model.Status; }
	}

	private PropertyChangedProxy<MyModel, string> _statusPropertyChangedProxy;
	private MyModel _model;
	public MyViewModel(MyModel model)
	{
		_model = model;
		_statusPropertyChangedProxy = new PropertyChangedProxy<MyModel, string>(
			_model, myModel => myModel.Status, s => OnPropertyChanged("Status")
		);
	}

	// Default INotifyPropertyChanged
	public event PropertyChangedEventHandler PropertyChanged;
	protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
	{
		var handler = PropertyChanged;
		if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
	}
}

Here’s the source of the PropertyChangedProxy:

/// <summary>
/// Proxy class to easily take actions when a specific property in the "source" changed
/// </summary>
/// Last updated: 20.01.2015
/// <typeparam name="TSource">Type of the source</typeparam>
/// <typeparam name="TPropType">Type of the property</typeparam>
public class PropertyChangedProxy<TSource, TPropType> where TSource : INotifyPropertyChanged
{
	private readonly Func<TSource, TPropType> _getValueFunc;
	private readonly TSource _source;
	private readonly Action<TPropType> _onPropertyChanged;
	private readonly string _modelPropertyname;

	/// <summary>
	/// Constructor for a property changed proxy
	/// </summary>
	/// <param name="source">The source object to listen for property changes</param>
	/// <param name="selectorExpression">Expression to the property of the source</param>
	/// <param name="onPropertyChanged">Action to take when a property changed was fired</param>
	public PropertyChangedProxy(TSource source, Expression<Func<TSource, TPropType>> selectorExpression, Action<TPropType> onPropertyChanged)
	{
		_source = source;
		_onPropertyChanged = onPropertyChanged;
		// Property "getter" to get the value
		_getValueFunc = selectorExpression.Compile();
		// Name of the property
		var body = (MemberExpression)selectorExpression.Body;
		_modelPropertyname = body.Member.Name;
		// Changed event
		_source.PropertyChanged += SourcePropertyChanged;
	}

	private void SourcePropertyChanged(object sender, PropertyChangedEventArgs e)
	{
		if (e.PropertyName == _modelPropertyname)
		{
			_onPropertyChanged(_getValueFunc(_source));
		}
	}
}

I finally started using GitHub for some of my projects. And as usual, I try what is possible 😉
This time, I played around with Continuous Integration. The way to go seems to be with Travis CI. It has (beta) support for .Net with Mono. And it seems to work quite well as long as your projects are Mono compliant.

Basic Travis usage in github
To use Travis in github is pretty straight forward. Just register for Travis, link to your github and add a .travis.yml file to your github project.
The basic file can look like:

language: csharp
solution: src/<yoursolution>.sln

This just compiles all the projects which are in your solution.

Skip / fix unsupported code when compiling with Mono
If you’re project is almost Mono compliant, you can think of using the precompiler directive with the variable __MonoCS__ to get it to build on mono as well but use the “real” thing in your Visual Studio.
Here’s an example which uses the CommandManager of WPF which does not exist in Mono:

#if __MonoCS__
        public event EventHandler CanExecuteChanged;
#else
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
#endif

This makes at least sure, that it compiles on Mono.

Using nUnit tests with Travis
To run nUnit tests with travis is also fairly easy. Just add your unittest project and modify the Travis file like this:

language: csharp
solution: ./src/yoursolution.sln

install:
  - sudo apt-get install nunit-console
  - nuget restore ./src/yoursolution.sln

script:
  - xbuild ./src/yoursolution.sln
  - nunit-console ./src/SomeLibrary.Tests/bin/Debug/SomeLibrary.Tests.dll

This installs the nunit-console package, makes sure that the nuget libraries are fetched, compiles your solution with xbuild and runs the test library with nunit-console.

That’s it. Now Travis compiles and tests your github project and fails in case that it can’t compile or at least one unit test fails.

Sometimes you want to output multiple lines in a kind of table form to the console or a file. The main problem here is, that you need to know for each column the maximum number of characters any element has so that you can pad them correctly.

So take this example:

Title Name Street
Mr. Roman Sesamstreet
Mrs. Claudia Abbey Road

wouldn’t it be nicer to look like:

Title   Name       Street
Mr.     Roman      Sesamstreet
Mrs.    Claudia    Abbey Road

To make it easier, I created a small function which helps in doing so:

public static class ConsoleUtility
{
	/// <summary>
	/// Converts a List of string arrays to a string where each element in each line is correctly padded.
	/// Make sure that each array contains the same amount of elements!
	/// - Example without:
	/// Title Name Street
	/// Mr. Roman Sesamstreet
	/// Mrs. Claudia Abbey Road
	/// - Example with:
	/// Title   Name      Street
	/// Mr.     Roman     Sesamstreet
	/// Mrs.    Claudia   Abbey Road
	/// <param name="lines">List lines, where each line is an array of elements for that line.</param>
	/// <param name="padding">Additional padding between each element (default = 1)</param>
	/// </summary>
	public static string PadElementsInLines(List<string[]> lines, int padding = 1)
	{
		// Calculate maximum numbers for each element accross all lines
		var numElements = lines[0].Length;
		var maxValues = new int[numElements];
		for (int i = 0; i < numElements; i++)
		{
			maxValues[i] = lines.Max(x => x[i].Length) + padding;
		}

		var sb = new StringBuilder();
		// Build the output
		bool isFirst = true;
		foreach (var line in lines)
		{
			if (!isFirst)
			{
				sb.AppendLine();
			}
			isFirst = false;

			for (int i = 0; i < line.Length; i++)
			{
				var value = line[i];
				// Append the value with padding of the maximum length of any value for this element
				sb.Append(value.PadRight(maxValues[i]));
			}
		}
		return sb.ToString();
	}
}

A sample on how to use it would be:

var lines = new List<string[]>();
lines.Add(new[] { "What", "Before", "After"});
lines.Add(new[] { "Name:", name1, name2});
lines.Add(new[] { "City:", city1, city2});
lines.Add(new[] { "Zip:", zip1, zip2});
lines.Add(new[] { "Street:", street1, street2});
var output = ConsoleUtility.PadElementsInLines(lines, 3);

An application folder can look quite crowded if you have some assemblies or 3rd party references in use.

Like in this image: proj_folder_before Wouldn’t it be much nicer to have it look like:proj_folder_after

When it comes to having dll-files somewhere else than in the “app-folder, things can get quite cumbersome.

Here’s how to achieve this:

Moving files into subfolder

There are multiple ways to achieve this.

One way is to add a solution folder with the desired name of the subfolder and add the assemblies / dependencies as files (best way is to add them as links) there with build action=none and copylocal=true. If you add assemblies there used as references as well, set the copylocal for the references to false.

Another way is to leave the dll’s where they are (just adding dependent dlls as files/links into the project’s root directory) and create a post-build event or (my preferred way) add an AfterBuild task to the project to move all *.dll files into the subfolder.

For the post-build event just edit the project’s properties and add the commands into the post-build in the Build Events.

For the preferred way, just edit the csproj file (unload the project, then right-click and edit, open in any text-editor or use the visual studio addon EditProj) and add the following code at the bottom:

<Target Name="AfterBuild">
	<ItemGroup>
		<FilesToMove Include="$(OutDir)*.dll" />
	</ItemGroup>
	<Move SourceFiles="@(FilesToMove)" DestinationFolder="$(OutDir)Libs" />
</Target>

This example code uses the folder “Libs” for the dlls. Feel free to adjust it to your needs.

Telling the application to search other directories for libraries

This is actually quite simple. The current way of doing this is to edit the app.config and adding the following code into the configuration:

<runtime>
	<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
		<probing privatePath="Libs" />
	</assemblyBinding>
</runtime>

That’s it. With those two things you can have a “clean” application folder where all the assemblies or 3rd-party dependencies (like sqlite or sqlce dlls) are nicely stored in a subfolder