C#

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));
		}
	}
}

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

Following code will remove all non-printable characters from a string.

 StringBuilder cleanString = new StringBuilder();
 foreach (char character in inputString)
 {
     if (Char.IsControl(character))
     {
         if (Char.IsWhiteSpace(character))
         {
             cleanString.Append(" ");
         }
         continue;
     }
     cleanString.Append(character);
 }

I’m using Selenium for some browser-controlling stuff and mostly use Chrome with the ChromeDriver. But in Version 2.x, ChromeDriver only takes screenshots for the visible area of the screen.

So I created a Script in C# which scrolls around the page, taking screenshots and then stitches it all together.

The code should be easy to port into other languages.

// Get the Total Size of the Document
int totalWidth = (int)EvalScript("return document.width");
int totalHeight = (int)EvalScript("return document.height");

// Get the Size of the Viewport
int viewportWidth = (int)EvalScript("return document.body.clientWidth");
int viewportHeight = (int)EvalScript("return document.body.clientHeight");

// Split the Screen in multiple Rectangles
List rectangles = new List();
// Loop until the Total Height is reached
for (int i = 0; i < totalHeight; i += viewportHeight)
{
	int newHeight = viewportHeight;
	// Fix if the Height of the Element is too big
	if (i + viewportHeight > totalHeight)
	{
		newHeight = totalHeight - i;
	}
	// Loop until the Total Width is reached
	for (int ii = 0; ii < totalWidth; ii += viewportWidth)
	{
		int newWidth = viewportWidth;
		// Fix if the Width of the Element is too big
		if (ii + viewportWidth > totalWidth)
		{
			newWidth = totalWidth - ii;
		}

		// Create and add the Rectangle
		Rectangle currRect = new Rectangle(ii, i, newWidth, newHeight);
		rectangles.Add(currRect);
	}
}

// Build the Image
var stitchedImage = new Bitmap(totalWidth, totalHeight);
// Get all Screenshots and stitch them together
Rectangle previous = Rectangle.Empty;
foreach (var rectangle in rectangles)
{
	// Calculate the Scrolling (if needed)
	if (previous != Rectangle.Empty)
	{
		int xDiff = rectangle.Right - previous.Right;
		int yDiff = rectangle.Bottom - previous.Bottom;
		// Scroll
		RunScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
		System.Threading.Thread.Sleep(200);
	}

	// Take Screenshot
	var screenshot = ((ITakesScreenshot)_driver).GetScreenshot();

	// Build an Image out of the Screenshot
	Image screenshotImage;
	using (MemoryStream memStream = new MemoryStream(screenshot.AsByteArray))
	{
		screenshotImage = Image.FromStream(memStream);
	}

	// Calculate the Source Rectangle
	Rectangle sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height);

	// Copy the Image
	using (Graphics g = Graphics.FromImage(stitchedImage))
	{
		g.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel);
	}

	// Set the Previous Rectangle
	previous = rectangle;
}
// The full Screenshot is now in the Variable "stitchedImage"

The EvalScript just executes the Javascript and returns the Value, so it should look like:

public override T EvalScript(string script)
{
	IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
	return (T)js.ExecuteScript(script);
}

Sometimes, you want to get the XPath of an element. Here are two working solutions, one in pure XSLT and one in C#.
Both of them return XPath in the form of: /html[1]/body[1]/div[1]/div[2]/div[3]/div[1]/p[2]/img[1]

C#

/// <summary>
/// Gets the X-Path to a given Node
/// </summary>
/// <param name="node">The Node to get the X-Path from</param>
/// <returns>The X-Path of the Node</returns>
public string GetXPathToNode(XmlNode node)
{
	if (node.NodeType == XmlNodeType.Attribute)
	{
		// attributes have an OwnerElement, not a ParentNode; also they have             
		// to be matched by name, not found by position             
		return String.Format("{0}/@{1}", GetXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);
	}
	if (node.ParentNode == null)
	{
		// the only node with no parent is the root node, which has no path
		return "";
	}

	// Get the Index
	int indexInParent = 1;
	XmlNode siblingNode = node.PreviousSibling;
	// Loop thru all Siblings
	while (siblingNode != null)
	{
		// Increase the Index if the Sibling has the same Name
		if (siblingNode.Name == node.Name)
		{
			indexInParent++;
		}
		siblingNode = siblingNode.PreviousSibling;
	}

	// the path to a node is the path to its parent, plus "/node()[n]", where n is its position among its siblings.         
	return String.Format("{0}/{1}[{2}]", GetXPathToNode(node.ParentNode), node.Name, indexInParent);
}

XSLT

  <xsl:template name="GeneratePath">
	<xsl:param name="node" select="." />
	<xsl:message terminate="no">
	  <xsl:copy-of select="$node"/>
	</xsl:message>
	<xsl:apply-templates select="$node" mode="StartGeneratePath" />
  </xsl:template>

  <xsl:template match="*" mode="StartGeneratePath">
	<xsl:call-template name="genPath" />
  </xsl:template>
  
  <xsl:template name="genPath">
	<xsl:param name="prevPath"/>
	<xsl:variable name="currPath" select="concat('/',name(),'[',count(preceding-sibling::*[name() = name(current())])+1,']',$prevPath)"/>
	<xsl:for-each select="parent::*">
	  <xsl:call-template name="genPath">
		<xsl:with-param name="prevPath" select="$currPath"/>
	  </xsl:call-template>
	</xsl:for-each>
	<xsl:if test="not(parent::*)">
	  <xsl:value-of select="$currPath"/>
	</xsl:if>
  </xsl:template>

XSLT-Usage

<xsl:variable name="path">
  <xsl:call-template name="GeneratePath">
	<xsl:with-param name="node" select="./div[@class='eintrag2']//img[1]"/>
  </xsl:call-template>
</xsl:variable>