WPF Round Table Part 2: Multi UI Threaded Control – Fixes

Introduction

Click here to download code and sample project – Fixed

Here are the past articles in the WPF Round Table Series:

In my last post I discussed a control I made that allowed for a user to create inline XAML on different UI threads. Today, I am going to discuss a couple of the pitfalls I ran into when attempting to resolve an issue a user asked about

FrameworkTemplates

So, a user, rajesh, asked about how to solve a particular issue with having 4 controls with busy indicators loading all on separate threads. As I was attempting to construct a solution my first instinct was to simply use the ThreadSeparatedStyle property and set the Style’s Template property with the look you want, sort of like this:

<Style TargetType="{x:Type Control}">
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="{x:Type Control}">
				<multi:BusyIndicator IsBusy="True">
					<Border Background="#66000000">
						<TextBlock Text="Random Text" HorizontalAlignment="Center" VerticalAlignment="Center"/>
					</Border>
				</multi:BusyIndicator>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>

Suddenly, I was hit with a UI thread access exception when attempting to do this. The problem arises from how WPF allows users to design FrameworkTemplates. WPF instantiates the templates immediately, which will cause threading issues when attempting to access this setter value on our separate UI thread. The key to solving this is by deconstructing the template into a thread safe string by using XAML serialization. First we will grab any FrameworkTemplates from the style:

var templateDict = new Dictionary<DependencyProperty, string>();
foreach ( var setterBase in setters )
{
	var setter = (Setter)setterBase;

	var oldTemp = setter.Value as FrameworkTemplate;

	// templates are instantiated on the thread its defined in, this may cause UI thread access issues
	// we need to deconstruct the template as a string so it can be accessed on our other thread
	if ( oldTemp != null && !templateDict.ContainsKey( setter.Property ) )
	{
		var templateString = XamlWriter.Save( oldTemp );
		templateDict.Add( setter.Property, templateString );
	}
}

Then, while recreating our Style on the newly created UI thread, we reconstruct the template:

foreach ( var setterBase in setters )
{
	var setter = (Setter)setterBase;

	// now that we are on our new UI thread, we can reconstruct the template
	string templateString;
	if ( templateDict.TryGetValue( setter.Property, out templateString ) )
	{
		var reader = new StringReader( templateString );
		var xmlReader = XmlReader.Create( reader );
		var template = XamlReader.Load( xmlReader );
		setter = new Setter( setter.Property, template );
	}

	newStyle.Setters.Add( setter );
}

Now we are able to design our UI thread separated control inline our main Xaml and also any FrameworkTemplates that are defined within.

XAML Serialization Limitations

I actually ran into another error when attempting to insert my custom UserControl into the UI thread separated Style’s template. It involved a ResourceDictionary duplicate key error. This problem absolutely dumbfounded me; not only in trying to understand why the same resource would try to be defined twice, but also how can there be duplicates on a newly created UI thread. After racking my head for hours to come up with a work around solution I eventually found out the direct cause of the error in question. It had to do with how the XamlWriter class serializes the given XAML tree. To give you an idea let’s say we have our ThreadSeparatedStyle defined like this:

<Style TargetType="{x:Type Control}">
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="{x:Type Control}">
				<Border Width="100" Height="50" VerticalAlignment="Bottom">
					<Border.Resources>
						<converters:ColorValueConverter x:Key="ColorValueConverter"/>
					</Border.Resources>
					<Border.Background>
						<SolidColorBrush Color="{Binding Source='Black', Converter={StaticResource ColorValueConverter}}"/>
					</Border.Background>
					<TextBlock Text="Random Text" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/>
				</Border>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>

When Xaml.Save attempts to serialize the ControlTemplate here is our string result:

<ControlTemplate TargetType="Control" 
				 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
				 xmlns:cpc="clr-namespace:Core.Presentation.Converters;assembly=Core" 
				 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
	<Border Width="100" Height="50" VerticalAlignment="Bottom">
		<Border.Background>
			<SolidColorBrush Color="#FF000000" />
		</Border.Background>
		<Border.Resources>
			<cpc:ColorValueConverter x:Key="ColorValueConverter" />
		</Border.Resources>
		<TextBlock Text="Random Text" Foreground="#FFFFFFFF" HorizontalAlignment="Center" VerticalAlignment="Center" />
	</Border>
</ControlTemplate>

Now, if we decided to wrap this into a UserControl, called RandomTextUserControl, it may look like this:

<UserControl x:Class="MultiUiThreadedExample.RandomTextUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:converters="clr-namespace:Core.Presentation.Converters;assembly=Core">
	<UserControl.Resources>
		<converters:ColorValueConverter x:Key="ColorValueConverter"/>
	</UserControl.Resources>
	<Border Width="100" Height="50" VerticalAlignment="Bottom">
		<Border.Background>
			<SolidColorBrush Color="{Binding Source='Black', Converter={StaticResource ColorValueConverter}}"/>
		</Border.Background>
		<TextBlock Text="Random Text" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/>
	</Border>
</UserControl>

When we replace our current XAML with this control we will receive the ResourceDictionary XamlParseException because it is trying to include ‘ColorValueConverter’ more than once. If we go back to our Xaml.Save result we will find our culprit:

<ControlTemplate TargetType="Control"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:mute="clr-namespace:MultiUiThreadedExample;assembly=MultiUiThreadedExample"
                 xmlns:cpc="clr-namespace:Core.Presentation.Converters;assembly=Core"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
	<mute:RandomTextUserControl>
		<mute:RandomTextUserControl.Resources>
			<cpc:ColorValueConverter x:Key="ColorValueConverter" />
		</mute:RandomTextUserControl.Resources>
		<Border Width="100" Height="50" VerticalAlignment="Bottom">
			<Border.Background>
				<SolidColorBrush Color="#FF000000" />
			</Border.Background>
			<TextBlock Text="Random Text" Foreground="#FFFFFFFF" HorizontalAlignment="Center" VerticalAlignment="Center" />
		</Border>
	</mute:RandomTextUserControl>
</ControlTemplate>

As you can see, XamlWriter.Save is actually including our parent level resources from RandomTextUserControl. This will cause duplication issue since it will attempt to add the resources displayed here plus the ones already defined inside RandomTextUserControl. The reason is because XamlWriter tries to keep the result self-contained. Meaning, the final result will be a single page XAML tree. Unfortunately, the process tends to add any referenced resources that may come from the overall application. This limitation, along with others, are actually documented by Microsoft. So, the solution here is to either put all your resources into the first content elements resources property or define the design of your control using a template, like this:

<UserControl x:Class="MultiUiThreadedExample.RandomTextUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:converters="clr-namespace:Core.Presentation.Converters;assembly=Core"
             xmlns:multiUiThreadedExample="clr-namespace:MultiUiThreadedExample">
	<UserControl.Template>
		<ControlTemplate TargetType="{x:Type multiUiThreadedExample:RandomTextUserControl}">
			<ControlTemplate.Resources>
				<converters:ColorValueConverter x:Key="ColorValueConverter"/>
			</ControlTemplate.Resources>
			<Border Width="100" Height="50" VerticalAlignment="Bottom">
				<Border.Background>
					<SolidColorBrush Color="{Binding Source='Black', Converter={StaticResource ColorValueConverter}}"/>
				</Border.Background>
				<TextBlock Text="Random Text" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/>
			</Border>
		</ControlTemplate>
	</UserControl.Template>
</UserControl>

I actually prefer this method since it reduces an unnecessary ContentPresenter from being created and allows for more seamless TemplateBinding with the parent and Triggering.

WPF Round Table Part 2: Multi UI Threaded Control

Introduction

Click here to download code and sample project – Fixed

Here are the past articles in the WPF Round Table Series:

In this series I want to express some of the knowledge I gained in WPF over the years when tackling unique situations. For today’s post though I would like to discuss something that was created quite recently after a brief discussion with coworkers about multi UI threaded controls. I always knew how to create a window on a separate UI thread, but what if you wanted a control to be part of a main window, yet have its own dispatcher message pump?

New Window UI

Well to start off we need to understand how to even spawn a new WPF supported UI thread. This article explains how to launch a window on a completely new UI thread. The creation process is actually quite simple as demonstrated in this code snippet:

Thread thread = new Thread(() =>
{
	Window1 w = new Window1();
	w.Show();
	w.Closed += (sender2, e2) =>
	w.Dispatcher.InvokeShutdown();
	System.Windows.Threading.Dispatcher.Run();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

Here we start by simply creating a new thread which will host our new Window. Inside the thread we create a window and make sure the Dispatcher (which will get automatically created on demand for this thread when accessed) starts the message pump. We also handle shutting down the message pump on the window’s Closed event. At the end we set the thread’s ApartmentState to be single-threaded apartment (STA) rather than multithreaded partment (MTA) since WPF UI threads cannot be multithreaded. Once we start the thread we can see our new window now runs on its own UI thread.

Non-Interacting Host

Although a new window has its benefits, what if you want a UI independent control placed inside your main window? Well this MSDN article explains how this process can occur using a HostVisual class. The greatest benefit HostVisual provides is a way to arbitrarily connect any Visual to a parent visual tree. Unfortunately, there is not a way to fully measure, arrange, and render an item through a HostVisual without a presentation source. So we create our own presentation source which simply contains and displays our HostVisual to show in our window. Here is the main components of the class:

private readonly VisualTarget _visualTarget;

public VisualTargetPresentationSource( HostVisual hostVisual )
{
	_visualTarget = new VisualTarget( hostVisual );
	AddSource();
}

public override Visual RootVisual
{
	get
	{
		return _visualTarget.RootVisual;
	}

	set
	{
		Visual oldRoot = _visualTarget.RootVisual;

		// Set the root visual of the VisualTarget.  This visual will
		// now be used to visually compose the scene.
		_visualTarget.RootVisual = value;

		// Tell the PresentationSource that the root visual has
		// changed.  This kicks off a bunch of stuff like the
		// Loaded event.
		RootChanged( oldRoot, value );

		// Kickoff layout...
		UIElement rootElement = value as UIElement;
		if ( rootElement != null )
		{
			rootElement.Measure( new Size( Double.PositiveInfinity, Double.PositiveInfinity ) );
			rootElement.Arrange( new Rect( rootElement.DesiredSize ) );
		}
	}
}

protected override CompositionTarget GetCompositionTargetCore()
{
	return _visualTarget;
}

And running the sample project you can test this by toggling the busy indicator:

toggleThe main caveat with this method is that you are unable to interact with the control, which is fine for the purpose I want for this control. But even though I was able to create a control independent of the UI I still had issues positioning the thread separated control in relation to my main window.

Decorator with Child Elements

I managed to stumble upon another article that not only addressed the issue of alignment, but goes one step further by allowing the control to have child elements as well. I’ll include a ‘Child’ property along with a ‘ContentProperty’ attribute at the header of my class so that I can create UIElements right into XAML. Here is the logic that helps display our UI content onto a separate thread:

protected virtual void CreateThreadSeparatedElement()
{
	_hostVisual = new HostVisual();

	AddLogicalChild( _hostVisual );
	AddVisualChild( _hostVisual );

	// Spin up a worker thread, and pass it the HostVisual that it
	// should be part of.
	var thread = new Thread( CreateContentOnSeparateThread )
	{
		IsBackground = true
	};
	thread.SetApartmentState( ApartmentState.STA );
	thread.Start();

	// Wait for the worker thread to spin up and create the VisualTarget.
	_resentEvent.WaitOne();

	InvalidateMeasure();
}

Since we are creating a new HostVisual we need to make sure we define the parent-child relationship between the HostVisual and our UI control by calling ‘AddLogicalChild’ and ‘AddVisualChild’. Let’s take a look at how we are creating our UI content on a separate thread:

private void CreateContentOnSeparateThread()
{
	if ( _hostVisual != null )
	{
		// Create the VisualTargetPresentationSource and then signal the
		// calling thread, so that it can continue without waiting for us.
		var visualTarget = new VisualTargetPresentationSource( _hostVisual );

		_uiContent = CreateUiContent();

		if (_uiContent == null)
		{
			throw new InvalidOperationException("Created UI Content cannot return null. Either override 'CreateUiContent()' or assign a style to 'ThreadSeparatedStyle'");
		}
		_threadSeparatedDispatcher = _uiContent.Dispatcher;

		_resentEvent.Set();

		visualTarget.RootVisual = _uiContent;

		// Run a dispatcher for this worker thread.  This is the central
		// processing loop for WPF.
		Dispatcher.Run();

		visualTarget.Dispose();
	}

}

Here we can see us using our VisualTargetPresentationSource custom class to contain the HostVisual. The ‘CreateUiContent’ method is simply a protected virtual method that creates our content for us and can be overrided by inheriting classes. To make sure both our child content and the HostVisual is represented in our control we need to override the ‘VisualChildrenCount’, ‘LogicalChildren’, and ‘GetVisualChild’ methods to take both elements into account. Although this will allow for allow our content to render, our UI separated content will have measuring issues if the Child content has limited size or merely does not exist. To fix this we are going to override the ‘Measure’ and ‘Arrange’ methods like so:

protected override Size MeasureOverride( Size constraint )
{
	var childSize = new Size();
	var uiSize = new Size();

	if ( Child != null )
	{
		Child.Measure( constraint );

		var element = Child as FrameworkElement;
		childSize.Width = element != null ? element.ActualWidth : Child.DesiredSize.Width;
		childSize.Height = element != null ? element.ActualHeight : Child.DesiredSize.Height;
	}

	if ( _uiContent != null )
	{
		_uiContent.Dispatcher.Invoke( DispatcherPriority.Background, new Action( () => _uiContent.Measure( constraint ) ) );
		uiSize.Width = _uiContent.ActualWidth;
		uiSize.Height = _uiContent.ActualHeight;
	}

	var size = new Size( Math.Max( childSize.Width, uiSize.Width), Math.Max( childSize.Height, uiSize.Height) );;
	return size;
}

protected override Size ArrangeOverride( Size finalSize )
{
	if ( Child != null )
	{
		Child.Arrange( new Rect( finalSize ) );
	}

	if ( _uiContent != null )
	{
		_uiContent.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action( () => _uiContent.Arrange( new Rect( finalSize ) ) ) );
	}

	return finalSize;
}

As you can see I am treating our main parent control mostly like a panel where I either fill out the space given or take the max size of either my Child element or the size of the element on the separate thread.

Thread Separated Style

Although we have our ‘CreateUiContent’ method to instantiate our control from code, what if we want to create our control from a style right within XAML? Well we can create a DependencyProperty called ‘ThreadSeparatedStyle’, but the style itself must be instantiated on the new UI thread or else we’ll run into thread exceptions. In order to get around this issue we are going to recreate the style on the fly using reflection through an anonymous call. Here you can see how this occurs when the style changes:

private static void OnThreadSeparatedStyleChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
	var control = (UiThreadSeparatedControl)d;
	var style = e.NewValue as Style;
	if ( style != null )
	{
		var invokingType = style.TargetType;
		var setters = style.Setters.ToArray();

		control._createContentFromStyle = () =>
		{
			var newStyle = new Style
			{
				TargetType = invokingType,
			};
			foreach ( var setter in setters )
			{
				newStyle.Setters.Add( setter );
			}

			var contentt = (FrameworkElement)Activator.CreateInstance( newStyle.TargetType );
			contentt.Style = newStyle;

			return contentt;
		};
	}
	else
	{
		control._createContentFromStyle = null;
	}
}

Since I use the style’s target type to instantiate the control, the assigned target type in the style should not refer to a base control. I am also holding onto all the setter values for the style so they are preserved on recreation. Although I could avoid using reflection and recreating the style altogether by placing the style in a Themes defined folder Generic.xaml, by doing it this way it allows me to define the style at the same time I create the control:


<multi:UiThreadSeparatedControl IsContentShowing="{Binding ElementName=Toggle, Path=IsChecked}">
	<multi:UiThreadSeparatedControl.ThreadSeparatedStyle>
		<Style TargetType="multi:BusyIndicator">
			<Setter Property="IsBusy" Value="True"/>
		</Style>
	</multi:UiThreadSeparatedControl.ThreadSeparatedStyle>
</multi:UiThreadSeparatedControl>

The convenience of having this as an option seemed to outweigh trying to avoid reflection. Especially since it is much more intuitive to define your styles anywhere in XAML, not just UI independent resource dictionaries.

FrozenProcessControl

Now how could we use this type of control in our application? One scenario could be a case where you want to display a busy cursor if the window happens to freeze. Although it is quite a bad practice for your application to ever freeze. Usually this problem can be circumvented by offloading certain functionality onto a separate, non-UI thread. But sometimes you are left without a choice in the matter. For instance, say you are using a third party control that has become an integral part of your application and suddenly adding new, large amount of data causes the control to inefficiently load all its components on the UI thread. You may not have access to the controls source code or do not have time to replace the control. It would be a much better user experience to at least display something to the user to let it know some form of action is still happening rather than staring at a frozen screen. This is where our FrozenProcessControl comes into play.

At first we will extend our UiThreadSeparatedControl and override the ‘CreateUiContent’ method:

protected override FrameworkElement CreateUiContent()
{
	return new BusyIndicator
	{
		IsBusy = true,
		HorizontalAlignment = HorizontalAlignment.Center
	};
}

We will also have two Timers; one for polling the main window for no response, and another when the window is non-responsive for too long. Here is how our polling method is handled:

private void PollMainWindowTimerOnElapsed( object sender, ElapsedEventArgs elapsedEventArgs )
{
	_pollMainWindowTimer.Stop();
	_nonResponseTimer.Start();
	if ( _mainWindowProcess.Responding )
	{
		_nonResponseTimer.Stop();
		if ( _isContentDisplaying )
		{
			_isContentDisplaying = false;

			_threadSeparatedDispatcher.BeginInvoke( DispatcherPriority.Render, new Action( () =>
			{
				_uiContent.Visibility = Visibility.Hidden;
				_pollMainWindowTimer.Start();
			} ) );
		}
		else
		{
			_pollMainWindowTimer.Start();
		}
	}
}

As you can see we immediately start our non-responsive timer because if the main window’s process is unable to respond, accessing the process will cause the thread to freeze until activity happens again. If we do happen to gain response again and our busy indicator is displaying we need to update its visibility using its UI thread dispatcher to access the separate UI thread. Here we can see how our non-response timer is handled:

private void NonResponseTimer_Elapsed( object sender, ElapsedEventArgs e )
{
	_pollMainWindowTimer.Stop();
	_nonResponseTimer.Stop();

	_isContentDisplaying = true;

	_threadSeparatedDispatcher.BeginInvoke( DispatcherPriority.Render, new Action( () =>
	{
		_uiContent.Visibility = Visibility.Visible;
	} ) );
}

This is pretty straight forward, if the poll timer is frozen from accessing the process we do not want any further events to happen until the window is active again. After that we update the visibility using the separate UI thread to show our busy indicator. Here we can see the control in action in our demo by hitting the Freeze button, viewing the busy indicator on the far right freeze, and then suddenly seeing our thread separated control run on top:

frozen

Conclusion

Overall, this is quite a useful control, but the major caveat to using this is there is no ability to accept user input. Other than that this could easily help offload the build time for certain, display-only controls.

WPF Round Table Part 1: Simple Pie Chart

Introduction

Click here to download code and sample project

Over the years I have been presented with many different situations while programming in WPF, which required a certain Control or class to be created to accommodate. Given all the various solutions I created throughout the years I thought it might be helpful to someone else. During this ongoing series I am going to post some of the more useful classes I have made in the past.

Simple Pie Chart

In one project I was assigned to redesign, there was data coming in that we wanted represented in the form of a pie chart. Initially, we simply displayed the information in the form of one out of many static pie chart images. A specific image would get selected based on what the percentage was closest. Although this solved our immediate needs I believed generating this with GeometryDrawing would make the chart much more accurate and should not be too difficult to create. My immediate goal was to try and represent some type of pie chart in XAML to get an idea of how it could be represented dynamically. Initial searching led to this solution involving dividing a chart into thirds. Following the example given will produce a subdivided geometric ellipse:

Pie Chart Example - 1

Programmatically Build Chart

Unfortunately, using strictly XAML will not work when attempting to create a pie chart dynamically. This is definitely a great starting point in how we could create this Control, but I needed a better understanding how to create geometric objects programmatically. Doing some more searching I came across this Code Project that describes how to create pie charts from code. My pie chart will be much simpler containing only two slices and taking in a percentage value to represent how the slices will subdivide. I still use an Image to represent how the geometry will be drawn and begin the creation of the root elements:

_pieChartImage.Width = _pieChartImage.Height = Width = Height = Size;

var di = new DrawingImage();
_pieChartImage.Source = di;

var dg = new DrawingGroup();
di.Drawing = dg;

Since I know my starting point of the pie will always be at the top I then calculate where my line segment will end (the PieSliceFillers are brushes representing the fill color):

var angle = 360 * Percentage;
var radians = ( Math.PI / 180 ) * angle;
var endPointX = Math.Sin( radians ) * Height / 2 + Height / 2;
var endPointY = Width / 2 - Math.Cos( radians ) * Width / 2;
var endPoint = new Point( endPointX, endPointY );

dg.Children.Add( CreatePathGeometry( InnerPieSliceFill, new Point( Width / 2, 0 ), endPoint, Percentage > 0.5 ) );
dg.Children.Add( CreatePathGeometry( OuterPieSliceFill, endPoint, new Point( Width / 2, 0 ), Percentage <= 0.5 ) );

My CreatePathGeometry method creates both the inner and outer pie slices using a starting point, the point where the arc will end, and a boolean for ArcSegment to determine how the arc should get drawn if greater than 180 degrees.

private GeometryDrawing CreatePathGeometry( Brush brush, Point startPoint, Point arcPoint, bool isLargeArc )
{
	var midPoint = new Point( Width / 2, Height / 2 );

	var drawing = new GeometryDrawing { Brush = brush };
	var pathGeometry = new PathGeometry();
	var pathFigure = new PathFigure { StartPoint = midPoint };

	var ls1 = new LineSegment( startPoint, false );
	var arc = new ArcSegment
	{
		SweepDirection = SweepDirection.Clockwise,
		Size = new Size( Width / 2, Height / 2 ),
		Point = arcPoint,
		IsLargeArc = isLargeArc
	};
	var ls2 = new LineSegment( midPoint, false );

	drawing.Geometry = pathGeometry;
	pathGeometry.Figures.Add( pathFigure );

	pathFigure.Segments.Add( ls1 );
	pathFigure.Segments.Add( arc );
	pathFigure.Segments.Add( ls2 );

	return drawing;
}

A better to visualize this is through a XAML representation:





And with that we are able to create quick an easy pie charts as shown here:

Pie Chart Example - 2

Multi Pie Chart

Although this is suitable for a two sided pie chart, but what if you wanted more? That process is pretty straight forward based off what we already created. By including two dependency properties to represent our collection of data and brushes, we only need to rewrite how my segments are created:

var total = DataList.Sum();
var startPoint = new Point( Width / 2, 0 );
double radians = 0;

for ( int i = 0; i < DataList.Count; i++ ) { 	var data = DataList[i]; 	var dataBrush = GetBrushFromList( i ); 	var percentage = data / total; 	Point endPoint; 	var angle = 360 * percentage; 	if ( i + 1 == DataList.Count ) 	{ 		endPoint = new Point( Width / 2, 0 ); 	} 	else 	{ 		radians += ( Math.PI / 180 ) * angle; 		var endPointX = Math.Sin( radians ) * Height / 2 + Height / 2; 		var endPointY = Width / 2 - Math.Cos( radians ) * Width / 2; 		endPoint = new Point( endPointX, endPointY ); 	} 	dg.Children.Add( CreatePathGeometry( dataBrush, startPoint, endPoint, angle > 180 ) );

	startPoint = endPoint;
}

As you can see, the main difference is now we are accumulating the radians as we traverse the list to take into account any number of data objects. The result allows us to add any number of data items to our pie chart as shown here:
Pie Chart Example - 3

Conclusion

Although I did not get as much use for this class as I would have preferred, developing this helped me gain experience in manipulating geometry objects, which does not happen often enough.

MVC Series Part 3: Miscellaneous Issues

Introduction

In my first MVC series post, I discussed how to dynamically add items to a container using an MVC controller. Afterwards, I went through the process of unit testing the AccountController. The main purpose of this series was to explain some troublesome hiccups I ran into considering I did not come from a web development background. In this post I want to highlight a few of the minor issues while developing in MVC. One of them is not even related to MVC specifically, but it still caused enough of a headache that hopefully someone reading this can be spared the confusion.

HttpContext in Unit Tests

When I first started unit testing controllers, the HttpContext would return null when attempting to be accessed. The reason for this is because the controllers never assign the class on creation. Instead, controllers are typically created by the ControllerBuilder class. In my last post about unit testing the AccountController, I described a way to mock out the HttpContext, but in the beginning I wanted to try and keep my test project as lean as possible. Since I had not approached testing the AccountController yet and did not want to include a package to mock out an object I only needed to resolve NullReferenceExceptions, I found this clever post to quickly bypass this issue. By providing the HttpContext with a simple Url I no longer received an exception and was able to test the other components of a controller. I decided to wrap this functionality inside a class:

public class TestHttpContext : IDisposable
{
	public TestHttpContext()
	{
		HttpContext.Current = new HttpContext(
			new HttpRequest( null, "http://tempuri.org", null ),
			new HttpResponse( null ) );
	}

	public void Dispose()
	{
		HttpContext.Current = null;
	}
}

Since I am creating a new controller for each test, I needed the HttpContext to be recreated and destroyed each time. So, I went ahead and placed this inside a base test class that all controller tests will inherit:

public class TestBase
{
	private TestHttpContext _testContext;

	[TestInitialize]
	public void Initialize()
	{
		_testContext = new TestHttpContext();
	}

	[TestCleanup]
	public void TestCleanup()
	{
		_testContext.Dispose();
	}
}

Mocking out the HttpContext would provide better unit testing standards, but my minimalist personality found this solution too good to pass for the time being.

DbContext Non-Thread Safe

After updating my project to use Unity, I decided to take better advantage of the dependency injection design pattern by making the DbContext a singleton to prevent having to constantly re-initialize the connection to our Azure database. Early on after this change it became apparent our website was very inconsistent when trying to write to the database. Since many changes were occurring during this time, I did not immediately presume the DbContext as a singleton was the cause until I ran into this post.

So it seems I could still gain a performance boost by only creating the DbContext once per thread call, but how could I do this implementation using dependency injection? “Fortunately”, a new version of Unity provides a LifetimeManager catered specifically to this called PerRequestLifetimeManager.

This solution dramatically reduced my refactoring costs to close to zero, which was very desirable at this point in the project where time constraints were becoming out of reach. Later, I did a more thorough research into DbContext and you will notice this is why I put ‘Fortunately’ in quotes. As this MSDN post mentions, PerRequestLifetimeManager is bad practice to use when dealing with the DbContext. The reason is because it can lead to hard to track bugs and goes against the MVC principle of registering objects with Unity that will remain stateless. Although our application never ran into issues after implementing this LifetimeManager, in the future it is best to simply create and destroy the DbContext every time.

Ajax Caching in IE

This last problem is not so much an MVC issue, but a cross browser bug. And it is not so much a bug as it is more of understanding there are different specifications for each browser. As I mentioned in my post for creating Dynamic Items, I was using ajax calls to dynamically modify the DOM of a container. Throughout the project though we would intermittently hear bugs when attempting to add an item and trying to save. Each time the bug would re-occur, I would view the problem area, look stupefied at the cause of the issue, check in a fix, and the problem would go away, only to show up again a week later. What was going on here? Especially since the files in this area had been untouched for weeks!

The problem? Internet Explorer and its aggressive caching. The other browsers are not this adamant about caching ajax calls, at least when it comes to developing testing. And the solution to the problem was a bit more demoralizing:

$.ajax({
	async: false,
	cache: false,
	url: '/Controller/Action',
}).success(function (partialView) {
	// do action
});

One line of code solved weeks of headache Although any fairly seasoned web developer would probably speculate the browser being at fault, as someone who only ever has to deal with one set of specifications (.NET/WCF/EF/WPF/SQL) our team and I were not use to meticulously testing each new feature on every available browser. This meant although someone would find the bug in IE, but in retesting they may have coincidentally retested the feature in Chrome. Or, even worse, republishing the test caused the caching to reset so retesting the feature would get the pass the first time, but would not realize how broken it was until days later. All this means is we need to have a different method for testing web projects and to continue our understanding of how web development can act.

Summary

Working in MVC has been a great learning experience and helped continue my growth in developing in web. Despite my complaints and the hair-splitting, alcohol consuming  problems I do enjoy the breadth and stability MVC provides to the web world. I will continue my progress in the realms of web development and hope these small roadblocks will become less frequent, at the very least for my sanity’s sake.

MVC Series Part 2: AccountController Testing

Introduction

Click here to download code and sample project

In my first post of the series, I explained the perils and pitfalls that I had to overcome with dynamically adding items. One of the next problem I ran into was dealing with unit testing the AccountController. More specifically, attempting to represent the UserManager class. Since unit testing is a fundamental necessity for any server project, testing the controller was a necessity.

Attempting to Test

So, let’s first create a test class for the AccountController and include a simple test for determining if a user was registered. Here is how my class first appeared:

[TestClass]
public class AccountControllerTest
{
	[TestMethod]
	public void AccountController_Register_UserRegistered()
	{
		var accountController = new AccountController();
		var registerViewModel = new RegisterViewModel
		{
			Email = "test@test.com",
			Password = "123456"
		};

		var result = accountController.Register(registerViewModel).Result;
		Assert.IsTrue(result is RedirectToRouteResult);
		Assert.IsTrue( _accountController.ModelState.All(kvp => kvp.Key != "") );
	}
}

When running the unit test I get a NullReferenceException thrown when attempting to access the UserManager. At first I assumed this was due to not having a UserManager created, but debugging at the location of the thrown exception led me to this:

ApplicationUserManager UserManager
{
     get
     {
          return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
     }
     private set
     {
          _userManager = value;
     }
}

The exception is actually getting thrown on the HttpContext property that is part of ASP.Net internals. We cannot assign HttpContext directly on a controller since it is read-only, but the ControllerContext on it is not, which explains how to do that here. We can create this easily enough by installing the Moq NuGet package to help mock this out. We will install the package and place the initialization of our AccountController into a initialize test class that will get called prior to every unit test:

private AccountController _acocuntController;

[TestInitialize]
public void Initialization()
{
     var request = new Mock<HttpRequestBase>();
     request.Expect( r => r.HttpMethod ).Returns( "GET" );
     var mockHttpContext = new Mock<HttpContextBase>();
     mockHttpContext.Expect( c => c.Request ).Returns( request.Object );
     var mockControllerContext = new ControllerContext( mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object );

     _acocuntController = new AccountController
     {
          ControllerContext = mockControllerContext
     };
}

Now when we run our application we no longer have to worry about the HttpContext, but still there is another NullReferenceException being thrown. This time it is from the call to ‘GetOwinContext’.

Alternative Route

At this point, attempting to mock out all of HttpContext’s features seems like a never ending road. All we really want is the ability to use UserManager’s feature to register a user. In order for us to do that we will need to mock out the IAuthenticationManager. This is no easy feat considering how well embedded the UserManager is within the AccountController. Fortunately, a post mentioned here mentions the right direction for substituting the ApplicationUserManager.

What we want to do is create a new class, called AccountManager, that will act as an access to the UserManager. The AccountManager will take in an IAuthenticationManager and also a IdentityDbContext, in casewe need to specify the specific context. I decided to place this class in a separate library that both the MVC and unit test libraries can access. If you decide to do the same and copy the class from the sample project, most of the dependencies will get resolved except for the HttpContextBase extension ‘GetOwinContext’. The reason is because that extension needs Microsoft.Owin.Host.SystemWeb. You can simply install this dependency in your library as a Nuget package through this command:

  • Install-Package Microsoft.Owin.Host.SystemWeb

Now that we have our AccountManager, we need to make sure our AccountController will use this class rather than attempting to create the UserManager from HttpContext. This starts with the constructor, where now we will have it accept our manager rather than passing in a UserManager:

public AccountController( AccountManager<ApplicationUserManager, ApplicationDbContext, ApplicationUser> manager)
{
	_manager = manager;
}

Then we will change the access to AccountController.UserManager to use the AccountManager:

public ApplicationUserManager UserManager
{
	get
	{
		return _manager.UserManager;
	}
}

Dependency Injection

Now the immediate problem with this is that MVC’s controllers are stateless and handle the creation of all the classes, including any objects that are injected into the class. Fortunately, Unity has dependency injection specifically for MVC that will allow us to inject our own objects. As of this writing, I went ahead and installed Unity’s MVC 5, which is referenced here. It’s a very seamless process to integrate Unity into your MVC project. After installing the package, open the Global.asax.cs, where your Application_Start() method is stored and add in ‘UnityConfig.RegisterComponents();’. Afterwards, in the App_Start folder, open the UnityConfig.cs file and register our AccountManager:

container.RegisterType<AccountManager<ApplicationUserManager, ApplicationDbContext, ApplicationUser>>(new InjectionConstructor());

We will also need to override our initialization process for the AccountController to ensure the AccountManager either gets the embedded HttpContext from the AccountController or one we provide during test:

protected override void Initialize( RequestContext requestContext )
{
	base.Initialize( requestContext );
	_manager.Initialize( HttpContext );
}

We will also need to remove the references to AuthenticationManager and instead have our AccountController reference the AccountManager’s AuthenticationManager. This will also cause our SignInAsync method to this:

private async Task SignInAsync( ApplicationUser user, bool isPersistent )
{
	await _manager.SignInAsync( user, isPersistent );
}

Mocking AccountController

Now we can run our application and register a user using our AccountManager. With this implementation in place, we simply need to mock out our IAuthenticationManager. Here is a post that describes a bit of the process. So, following suit, we go ahead and mock out the necessary classes for initializing up our test AccountController, all under the same Initialization class:

private AccountController _accountController;

[TestInitialize]
public void Initialization()
{
	// mocking HttpContext
	var request = new Mock<HttpRequestBase>();
	request.Expect( r => r.HttpMethod ).Returns( "GET" );
	var mockHttpContext = new Mock<HttpContextBase>();
	mockHttpContext.Expect( c => c.Request ).Returns( request.Object );
	var mockControllerContext = new ControllerContext( mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object );

	// mocking IAuthenticationManager
	var authDbContext = new ApplicationDbContext();
	var mockAuthenticationManager = new Mock<IAuthenticationManager>();
	mockAuthenticationManager.Setup( am => am.SignOut() );
	mockAuthenticationManager.Setup( am => am.SignIn() );

	var mockUrl = new Mock<UrlHelper>();

        var manager = new AccountManager<ApplicationUserManager, ApplicationDbContext, ApplicationUser>( authDbContext, mockAuthenticationManager.Object );
	_accountController = new AccountController( manager )
	{
		Url = mockUrl.Object,
		ControllerContext = mockControllerContext
	};

	// using our mocked HttpContext
	_accountController.AccountManager.Initialize( _accountController.HttpContext );
}

Now we can effectively test our AccountController’s logic. It’s unfortunate this process was anything but straight forward, but at least we are able to have better unit test code coverage over our project.

MVC Series Part 1: Dynamically Adding Items Part 3

Collections named with same substring in a Dynamic Item

Click here to download code and sample project

In the second part of the series, I discussed how to include a collection inside a dynamic item. Here is one gotcha that I ran into during development. Let’s say we decide to add a Publisher for every new book and you want the ability to add a few books the publisher has distributed. Here is the PublisherViewModel class I created:

public class PublisherViewModel
	{
		public PublisherViewModel()
		{
			Books = new List<PublisherBookViewModel>();
			for ( int i = 0; i < 3; i++ )
			{
				Books.Add( new PublisherBookViewModel() );
			}
		}
		public string Name { get; set; }

		public IList<PublisherBookViewModel> Books { get; set; }
	}

Here is how the html would look for PublisherViewModel:

<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor( model => @Model.Name )
    </dt>
    <dd>
        @Html.EditorFor( model => @Model.Name )
    </dd>
    <br />

    <dt>
        @Html.DisplayNameFor( model => @Model.Books )
    </dt>
    <dd>
        @for ( int i = 0; i < @Model.Books.Count(); i++ )
        {
            @Html.EditorFor( model => @Model.Books[i] )
        }
    </dd>
</dl>

I went ahead and created a new class for the books collection called PublisherBookViewModel. It simply contains one property for Name. Here is how the Html looks:

@using ( Html.BeginCollectionItem( "Books" ) )
{
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor( model => @Model.Name )
        </dt>
        <dd>
            @Html.EditorFor( model => @Model.Name )
        </dd>
    </dl>
}

But when I go to create one new Book and post back, I actually end up receiving 4 items in my ‘NewBooks’ collection. How did this even happen?

Well, the reason this occurred is again thanks to our BeginCollectionItem HtmlHelper class. The extra logic that we added in the last article seems to merely grab the first occurrence of our collection name:

collectionName = htmlFieldPrefix.Substring( 0, htmlFieldPrefix.IndexOf( collectionName ) + collectionName.Length );

If we look at what the HtmlFieldPrefix string looks like coming in we can start to spot the problem:

"NewBooks[18fe8281-9b41-43ff-bcc9-a14ce3e99dc8].Publisher.Books[0]"

So, our parent dynamic item is being bounded to a collection called ‘NewBooks’, but the PublisherViewViewModel has its own collection of items called ‘Books’. Our Substring method needs to be a little bit smarter by replacing ‘IndexOf’ with ‘LastIndexOf’. And with that, we will no longer have issues with sub collection binding.

This is as far as I took with dynamically adding items in MVC, but at some point it would be nice to be able to add dynamic items to a dynamic item (i.e., instead of pre-populating our Characters collection, we let the user add as many as they need). Perhaps another day I will delve into this.

MVC Series Part 1: Dynamically Adding Items Part 2

Collections in a Dynamic Item

Click here to download code and sample project

In the first part of the series, I discussed how to add items dynamically. So, why don’t we expand on our idea and let’s say we want to add the ability to include another collection into our original dynamic item. We will expand our BookViewModel editor template to include a collection of 5 story Characters a user can insert:

<dl id="booksContainer">
        @foreach ( var classicBook in @Model.ClassicBooks )
        {
            <dl>
                <dt>
                    @Html.DisplayNameFor( model => classicBook.Title )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Title )
                </dd>

                <dt>
                    @Html.DisplayNameFor( model => classicBook.Author )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Author )
                </dd>
            </dl>
        }
</dl>

And we included a CharacterViewModel editor template that only includes the ability to insert first and last name. But when you attempt to add a book with a characters we run into the same problem originally where the new Characters are not binding correctly. The reason this exists is because our HtmlHelper is not able to uniquely identify sub items inside a recently dynamically added item. Makes sense?

No? Well, let’s discuss first what the BeginCollectionItem Html helper generates when injected into the Html element. Here is the BookViewModel’s partial view for the title:

<dt>
    @Html.DisplayNameFor( model => @Model.Title )
</dt>
<dd>
    @Html.EditorFor( model => @Model.Title )
</dd>

And here is the output that actually gets injected into the Html element after passing through the Html helper:

<dt>
    Title
</dt>
<dd>
    <input class="text-box single-line"
           id="NewBooks_3ad36db7-7685-4c8e-aadd-a2309f65e858__Title"
           name="NewBooks[3ad36db7-7685-4c8e-aadd-a2309f65e858].Title"
           type="text" value="" />
</dd>

Here you can see how the Html helper is inserting a Guid into the id and name fields so MVC can uniquely identify the property back to the item. But if we use the same comparison for Character, here is the partial view for name:

<dt>
    FirstName
</dt>
<dd>
    <input class="text-box single-line"
           id="Characters_dd611290-f64b-4b1a-9add-bad035f7b94f__FirstName"
           name="Characters[dd611290-f64b-4b1a-9add-bad035f7b94f].FirstName"
           type="text" value="" />
</dd>
<dt>
    LastName
</dt>
<dd>
    <input class="text-box single-line"
           id="Characters_dd611290-f64b-4b1a-9add-bad035f7b94f__LastName"
           name="Characters[dd611290-f64b-4b1a-9add-bad035f7b94f].LastName"
           type="text" value="" />
</dd>

Although the character model is correctly getting a Guid assigned, there is no way for MVC to know that CharacterViewModel belongs to a NewBooks sub item. In order to solve this, we need to delve into our BeginCollectionItem Html helper and make sure it retains the ‘NewBooks’ guid. This is quite straightforward if we do a comparison on the incoming collection name:

var htmlFieldPrefix = html.ViewData.TemplateInfo.HtmlFieldPrefix;
if ( htmlFieldPrefix.Contains( collectionName ) )
{
        collectionName = htmlFieldPrefix.Substring( 0, htmlFieldPrefix.IndexOf( collectionName ) + collectionName.Length );
}

And let’s take a look again at our injected output:

<dt>
     FirstName
</dt>
<dd>
    <input class="text-box single-line"
           id="NewBooks_1a95a483-e5c7-4696-ac91-bd9f0563b83b__Characters_e3e949f5-aae7-44cd-9aa8-419658c25e75__FirstName"
           name="NewBooks[1a95a483-e5c7-4696-ac91-bd9f0563b83b].Characters[e3e949f5-aae7-44cd-9aa8-419658c25e75].FirstName"
           type="text" value="" />
</dd>
<dt>
    LastName
</dt>
<dd>
    <input class="text-box single-line"
           id="NewBooks_1a95a483-e5c7-4696-ac91-bd9f0563b83b__Characters_e3e949f5-aae7-44cd-9aa8-419658c25e75__LastName"
           name="NewBooks[1a95a483-e5c7-4696-ac91-bd9f0563b83b].Characters[e3e949f5-aae7-44cd-9aa8-419658c25e75].LastName"
           type="text" value="" />
</dd>

Now our character items will get posted back onto our dynamic item.

MVC Series Part 1: Dynamically Adding Items Part 1

Introduction

Recently, I have been exposed to working on a project using ASP.NET MVC 5. My experience working with MVC for the first time was overall positive, but it did run into quite a few hair pulling scenarios. My background up to this point primarily dealt with C# WPF applications, but with a little bit of web development on the side.  In this series, I will discuss some of the major issues that led to many sleepless nights working on this project. And although these scenarios may not seem to be the most difficult to an experienced MVC developer, these are the problems that caused major hiccups to a first timer like myself.

Dynamically Adding Items

Click here to download code and sample project

In one of the first major issues I needed to attempt to solve was trying to add items dynamically to a View. Representing a collection already populated is fairly straight forward using MVC’s Razor, as represented here in my collection of classical books:

<dl class="dl-horizontal" id="booksContainer">
        @foreach ( var classicBook in @Model.ClassicBooks )
        {
            <dl class="dl-horizontal">
                <dt>
                    @Html.DisplayNameFor( model => classicBook.Title )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Title )
                </dd>

                <dt>
                    @Html.DisplayNameFor( model => classicBook.Author )
                </dt>
                <dd>
                    @Html.DisplayFor( model => classicBook.Author )
                </dd>
            </dl>
        }
</dl>

We can even go one step further and place this inside a ‘DisplayTemplate’ and push the display content into a partial view:
dynamic img 1

<dl class="dl-horizontal" id="booksContainer">
        @foreach ( var classicBook in @Model.ClassicBooks )
        {
            @Html.DisplayFor(model => classicBook);
        }
</dl>

But how do we add content on the fly?

Well, we could have a button that inserts javascript into our ‘booksContainer’ element and this would provide a seamless experience for the user. But what if we decide to change how the view looks? And how could we get this to post back to MVC server? What about if we decided to take in an image file as well?

Given I did not want to update the view in two places, I managed to find a solution that managed to do all of the above, linked here.

In summary, I was able to use an ajax call to retrieve my BookViewModel’s partial html view from the server and inject it into an html element:

  • Adding an editor partial view for the BookViewModel

dynamic img2

  • Including the html element that will take in new books:
    <div id="newBooks">
        @for ( int i = 0; i < @Model.NewBooks.Count(); i++ )
    
        {
    
            @Html.EditorFor( model => @Model.NewBooks[i] )
    
        }
    
    </div>
  • On the server, the HomeController’s method that simply returns my partial view:
    public ActionResult CreateNewBook()
    {
    
        var bookViewModel = new BookViewModel();
    
        return PartialView( "~/Views/Shared/EditorTemplates/BookViewModel.cshtml", bookViewModel );
    
    }
    
    
  • The ajax call that handles the add book button click and injects the returned partial view:
    @section Scripts {
        <script type="text/javascript">
    
            $("#addbook").on('click', function () {
    
                $.ajax({
                    async: false,
                    url: '/Home/CreateNewBook'
                }).success(function (partialView) {
    
                    $('#newBooks').append(partialView);
    
                });
            });
    
        </script>
    }
    

And now we can dynamically add items on button click! The user is able to add as many books as they want, click submit, and the collection of books will get received on HttpPost. But, when we put a break post on our post method, the NewBooks collection comes back as empty. Why is this happening?

Well the reason is because MVC can only bind back a collection of items if it can uniquely identify each one. This article actually describes how you can get a collection of items to bind appropriately on post back, linked here.

Unfortunately, this does not apply when items are getting added dynamically. Luckily, the previous article also solved this problem by creating a Html Helper class, BeginCollectionItem, that adds a unique identifier to every new inserted item. All we need to do is modify our BookViewModel editor template to include it:

@using ( Html.BeginCollectionItem( "NewBooks" ) )
{
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor( model => @Model.Title )
        </dt>
        <dd>
            @Html.EditorFor( model => @Model.Title )
        </dd>

        <dt>
            @Html.DisplayNameFor( model => @Model.Author )
        </dt>
        <dd>
            @Html.EditorFor( model => @Model.Author )
        </dd>

        <dt>
            @Html.DisplayName( "Book Cover File Image" )
        </dt>
        <dd>
            @Html.TextBoxFor( m => @Model.BookCoverUrl, null, new { type = "file", @class = "input-file" } )
        </dd>

    </dl>
}

And with that we can now dynamically add items and they will uniquely get posted back onto the server.

Android Development with Android Studio

Click here to download code and sample project

Currently, developing mobile applications is one of the most popular environments to program. So, I decided to go ahead and take a step back into the world of Java to create an Android app. I went ahead and decided to give Google’s IDE, Android Studio, a try during this process. The IDE, which is based on IntelliJ IDEA, is still in early access preview though, but already looks quite promising.

To get started I went ahead and downloaded the Android Studio. As a preface, Android Studio requires at least JDK 6 installed before beginning. The entire installation process may take a while if the JDK needs to be installed first. Also, I would highly recommend downloading Genymotion as an Android Emulator replacement since the one on Android Studio is extremely slow. As for learning how to develop an Android application, the tutorial on Android’s site works quite well located here.

So, during this project I decided to port my coworkers TicTacToe concept into Android. The game is similar to regular TicTacToe, except the game is expanded into a 3×3 grid of TicTacToe games. Each individual game that is won is considered a marker for the overall game. There is also a bit of strategy that was added to force the player to consider where their next move should. Needless to say, it is quite an interesting take on TicTacToe and I encourage you to try it.

Since I am coming from a C#/WPF world I am going to bring over some of the concepts of MVVM into this architecture. If you are not familiar with MVVM it is simply a way to decouple business logic from the UI. This way the UI can change however it needs to while keeping the main logic the same.

To get started, open up Android studio and create a new project. When created you can see there is already a pretty verbose folder structure created for a default project.

Project ViewLet us start off with adding basic information for our application by looking into the AndroidManifest.xml. In here I will simply add a title for our app by setting the  android:label property. Then to include an app icon, I must include an image into each of the res/drawable-xxxx folders with the image resized appropriately. Here is a rough break down of the dimensions:

    • drawable-ldpi (120 dpi, Low density screen) – 36px x 36px
    • drawable-mdpi (160 dpi, Medium density screen) – 48px x 48px
    • drawable-hdpi (240 dpi, High density screen) – 72px x 72px
    • drawable-xhdpi (320 dpi, Extra-high density screen) – 96px x 96px
    • drawable-xxhdpi (480 dpi, Extra-Extra-high density screen) – 144px x 144px

From <http://stackoverflow.com/questions/5350624/set-icon-for-android-application>

After that we will go back to our manifest file and set the android:icon to our new app icon. Once we compile the app successfully and attempt to run though, the studio brings up the Device Manager to choose an emulator. If you decided to install Genymotion (which I still highly recommend), run it and add a new device to emulate. Once added, select the new device and click play. You will see the device represented in a new window and back in Android Studio when you look in the Device Manager you should see your new emulator.

2014-04-16 15_16_17-Choose Device

So selecting our new emulator we’re able to start running our application. Great, now let us start developing our custom View. I created a MiniBoardView class that extends View which will handle the drawing of the board, markings, and whether the board is in a playable, win, or draw state. You can download the project and view the class file to see all the logic that goes into place, but here are a few main points:

  • We will need to create a custom Paint object that handles the drawing to the screen
  • Any new action that can apply to the board needs a call to invalidate to update the UI
  • To view the control in the designer, certain logic will need to get ignored on rendering. This can be done by doing a check on isInEditMode
  • For all our rendering purposes, make sure to override the onDraw method

Once our view is ready for usage, I went ahead and started implementing the business logic. After setting up the base Model-ViewModel classes I went ahead and tried out my first hit test logic.

First Hit Test Response

Now that the basis for our application is done, the rest is simply filling out the logic for our game.  Here is our final result:

Final Output

This should go without saying, but Android Studio is not even at version 1.0. Because of that the IDE is quite unstable. This led to many different frustrations throughout the learning process. Sometimes I would have to restart Android Studio simply because it refused to successfully build anymore. Another peculiar issue I ran into was opening up my project one day, running my app, and suddenly view this:

2014-04-16 15_27_16-Genymotion for personal use - Galaxy S4 - 4.3 - API 18 - 1080x1920 (1080x1920, 4

What happened to the sizes of my boxes? Did the logic change? No. Did I mistype something? No. Maybe restarting will help? No. I tried many different solutions and even recoded much of the design to no avail. Out of frustration I stepped away for a while and came back to find everything was back to normal. Never saw this problem again. Also, I use to update the product periodically as well until one update caused my whole project to fail. Several hours of snooping online pointed me to updating certain gradle files to get my project working again. Needless to say, I ceased doing that for the rest of my development.

Overall, I enjoyed the development process going back into Java and using Android Studio. I did not take full advantage of what the Android stack has available but I look forward to attempting another project using this IDE.

Text On A Path With Alignment

Click here to download code and sample project

In past WPF projects, design specifications given by artists are sometimes challenging to attempt to implement. One scenario I have ran into multiple times was trying to display custom text around a curved object. Most of the time this problem was avoided by the artist providing the content as images, but, fortunately, this was only feasible because the text was finite and static. Recently I came across this same scenario again except this time the incoming text could be dynamic. The immediate reaction was to simply read the text as images stored in a folder provided by the customer. This solution tends to create problems in the future because:

  • The user must be familiar with some image editing tool
  • If not accustomed to any, then the user has to be trained
  • The user must be aware of the exact font, weight, and color the artist intended
  • The user must also have the same eye for lining up text as the original artist intended (which many tools can aid in)

With all these issues, it would be better to assume that if a user could get something wrong then they will, which will result in an application that seems off. Not happy with this path I decided to look into creating text on a path.

Fortunately, a majority of the work had already been developed by Charles Petzold described in his article Render Text On A Path With WPF.

The article provides a comprehensive description of his algorithm for placing text on a path. It is worth a read to get an in-depth understanding of how the algorithm works. To try and sum it up though, the algorithm uses a PathFigure object to shape the path the text will render and the class comes equipped with a method to help simplify calculations. In sizing the text font onto the path, the text is scaled to fit entirely on the length of the path. For the best performance, we render the text as DrawingVisual objects so they only need to be created once when the text changed. The result comes out as this:

Fantastic! This worked well for what I wanted, except for one problem; the text scaling. I knew the path I wanted my text to render, but not the length of the text since that could change dynamically. When attempting to apply this algorithm to a path I had in mind, the results were less than pleasing (red curve represents the path for the text):

I needed the text to render the same size despite the length of the path, but the current algorithm would require me to resize the path dynamically based on the size of the text. This did not seem reasonable, especially since I would prefer the text to rest on the center of the path.

So, in order to accomplish this the first thing I needed was a Dependency Property of type HorizontalAlignment to set the content alignment. Setting the alignment to Stretch will keep the original behavior of the algorithm by resizing the text to fit the path. Then we need another Dependency Property for font size, which will only get applied if the content alignment was not Stretch. Now, when calculating the text length we need to substitute our font size over the default 100

private void OnTextPropertyChanged()
{
    _formattedChars.Clear();
    _textLength = 0;

    if (!String.IsNullOrEmpty(Text))
    {
        foreach (char ch in Text)
        {
            var fontSize = ContentAlignment == HorizontalAlignment.Stretch ? 100 : FontSize;

            var formattedText =
                new FormattedText(ch.ToString(), CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight, _typeface, fontSize, Foreground);

            _formattedChars.Add(formattedText);
            _textLength += formattedText.WidthIncludingTrailingWhitespace;
        }

        GenerateVisualChildren();
    }
}

Then we move onto our TransformVisualChildren method and make sure the scaling factor stays at 1 since we no longer want the text to rescale to the path

private void TransformVisualChildren()
{
    ...
    var scalingFactor = ContentAlignment == HorizontalAlignment.Stretch ? _pathLength / _textLength : 1;
    ...
}

Since content alignment can be set as Center, or Right aligned, the initial progress will need adjusting to push the text further along the path

private void TransformVisualChildren()
{
    ...
    double progress = 0;

    switch (ContentAlignment)
    {
        case HorizontalAlignment.Left:
        case HorizontalAlignment.Stretch:
            progress = 0;
            break;
        case HorizontalAlignment.Center:
            progress = Math.Abs(_pathLength - _textLength) / 2 / _pathLength;
            break;
        case HorizontalAlignment.Right:
            progress = Math.Abs(_pathLength - _textLength) / _pathLength;
            break;
    }
    ...
}

And that is all we have to do since the scaling factor will be set to 1 if content is not stretched. Here is the result with content alignment set to Center. Also, you can see all the various alignments applied:

Although I was very satisfied with the results, a change in the scope of our project made this solution obsolete. Just another day in the life of a programmer.