Getting Started with Universal Apps

On a whim, I decided to create a new Universal App. If you haven’t been following the news, Microsoft announced Universal Apps at the Build 2014 conference. The term is used to refer to an application that is created and that will share code for multiple platforms such as Windows 8.1, Windows Phone 8.1, Android and iOS, amongst others.

In order to get access to the latest project templates, I installed Visual Studio 2013 Update 2 Release Candidate which can be found here.

Once that was done, here are the steps I followed:

In Visual Studio 2013, I created a new project and selected the Blank App (Universal Apps) option. I could have picked the Hub App but I wanted to create my own application from scratch.

New Project

I called my application the CalendarEventCreator.

This created a solution that contained 3 projects: one for Windows 8.1, one for Windows Phone 8.1, and a Shared component where shared XAML and code would reside.

2

This is good but the shared component is a way of linking files into both projects above. This means that the shared files are built directly into every one of the executables within the same solution. I prefer to have the bulk of my shared code reside in a class library so that it can be unit tested and built only once but referenced by various executables. This means if the shared code changes, I am not forced to rebuild and ship every executable. Here’s an excellent blog post that helps make sense out of both types of shared components: Sharing Code Across Platforms. For my project, I chose to create both a Portable Class Library called CalendarEventCreatorShared and a matching test project. My solution now looks like:

3

As the test project will be testing the portable shared library, I went to add a reference to the library from the test project. This, however, failed with the following message:

Error message

To solve this, I had to do two things:

  1. Go into the portable class library’s properties by right-clicking the project in the Solution Explorer and add “.NET Framework 4.5.1” as a target.
    Library targets
  2. Go into the unit test project’s properties by right-clicking the project in the Solution Explorer, change the framework to version 4.5.1 and accept the warning.
    6

After having accomplished this, I was able to add a reference to the portable class library into my test project and started doing some real coding…which unfortunately will be a story for another time.

Hope this helps you get started with Universal Apps!

 

Windows Phone 8: Where did the dropdown control go?

I recently started developing my very first Windows Phone 8 (WP8) application using C# and XAML and quickly found myself in an impasse: The Visual Studio 2012 (VS2012) toolbox did not contain anything I could identify as a dropdown or combobox control. Yet, the Calendar application on my phone uses such a control for its "How Long" selector amongst others.
CalendarApp1When the user taps on the control, it opens to reveal its values. If there are more than five values, it opens full-page. With fewer values, such as when specifying the availability state for the duration of the meeting, the list opens in-place.

CalendarApp2CalendarApp3

That was exactly the functionality I was looking for.

A bit of research sent me in the entirely wrong direction and I started investigating the LongListSelector as a possible replacement for the dropdown control. The LongListSelector is ideal for displaying organized lists of items such as a list of contacts in an address book. While the LongListSelector control supports the use of grouping such as by the first letter of a name, for example, it can also be made to display a flat, ungrouped, list. This was what I thought I was looking for but where I wanted to tap an item and have it be selected, the LongListSelector expected the tap to navigate the user somewhere else as it does when tapping a contact.

Thankfully, the article linked above mentioned that the LongListSelector had been moved from the Windows Phone Toolkit to the Windows Phone SDK. So I investigated the Toolkit and found the ListPicker control. This was exactly what I’d been looking for.

I installed the Windows Phone Toolkit using Nuget as described here but was dismayed to find that, though I could now manually add the control by typing it into the XAML file, it didn’t appear anywhere in the VS2012 toolbox.

Again, I searched for instructions for adding these new controls to the VS2012 toolbox and found these. This helped get me a bit closer but didn’t entirely solve my problem. Here are my revised steps for adding the Toolkit controls to the toolbox. Please refer to the original post for screenshots and for a much more comprehensive description of the process.

  • Go to the VS2012 Toolbox tab, right click over General and select Add Tab from the context menu.
  • Give a name to the newly created toolbox section.
  • Right-click the newly added section and select Choose Itemsà

Chooser

  • This is where my instructions are a bit different. The original poster simply selects the controls and adds them to the section. I never found the ListPicker in any of the Choose Toolbox Items tabs. In order to see it and its toolkit mates, I had to click the Browse button and navigate to the toolkit library located by default in \Documents\Visual Studio 2012\Projects\DataCollector2\packages\WPtoolkit.4.2012.10.30\lib\wp8.
  • Click OK. This adds the list of toolkit controls to the "Windows Phone Components" tab. Note that they are conveniently pre-selected.

Toolbox

  • Click OK. You now should have the controls in a new section in the toolbox so you can drag and drop to your heart’s content.

Hopefully, this can help save the next person some time!

Happy coding!

How my 12-yr-old son became a C# Programmer

My 12-year old son has been scripting since he was 7 or 8 and writing C# code for about 2 years now. Now for full disclosure, both my husband and I are software developers; my husband writes C++ and Java on the Linux platform but was a long-time Windows developer while I’m a C# .Net developer. We’d thought of eventually showing our son how to program but hadn’t planned on getting him started before he’d even learned long division.

The scripting was a bit of an accident. The PC game my son loved to play came with a full-featured game extension tool for users to develop their own modules and quests. Also included was the ability to write scripts to supplement the existing library with new functionality. It’s always exciting to invent your own modules and see how far you can push the envelope so this quickly became his favourite occupation.

The Copy-Paste Era

At first, his father provided him with a few key scripts that he could hook up to strategic locations and that would trigger a particular behaviour. For example, a “teleporter” script could be hooked up to a particular square in the game. When a character stepped onto the square, they would be “magically” transported elsewhere. But as any parent knows, children have many more hours for play than we parents have for fulfilling all their requests. Tired of waiting for daddy to have free time to write more scripts, my son begged for access to the scripting tool and started copying the scripts he’d already been given and tweaking them to fit the new functionality he wanted. That’s how he realized that programming was fun and not particularly difficult once he understood the logic and the syntax.

The Bounce-Stuff-Around-The-Screen Era

Writing scripts for your favourite game is one thing. But wouldn’t it be even more interesting to write a game of your own from scratch? So father and son sat down together and coded Pong, Asteroids, and other such simple games. At this point, it was mostly my husband coding but explaining what he was doing. This can keep a boy interested only so long and since we’d recently bought an XBox, it made sense to delve into XNA programming next.

My husband bought the wonderfully kid-friendly Learn Programming Now MS XNA Game Studio 3.0 book by Rob Miles (there’s a newer edition out now) and worked through the first few chapters with our son who took to it like a duck to water. Soon, he’d sped through the book and was writing all sorts of games that bounced a lot of objects on the screen.

That kept him occupied for a while but eventually, he realized there was more to the games he liked to play than images moving on a screen. He did not have the words to express what he was looking for but I could tell he wasn’t satisfied with the games he was producing. By then, he could handle simple C# data types, conditional statements and loops and had a basic understanding of classes and inheritance. He also understood XNA sprite batches, timers and the Draw method.

The Era of Enlightenment

I came back from Codemash v2.0.1.2 with the EverCraft Kata Dungeons&Dragons-style game instructions and, on a whim, suggested working on it with him. We’d do it using Red-Green-Refactor Test-Driven Development; an agile technique I’d been introduced to at Codemash and wanted to practice. As a huge D&D fan, I figured it was right down my son’s alley. I wrote the first failing test, he wrote the code to make the test pass and I refactored his code, explaining what I was doing and why. Then we traded places and he wrote a failing test for the functionality I was to implement next.

We spent hours implementing the character class with its hit-points, abilities, and more and by the end of that day, my son’s eyes were shining. Finally, he’d uncovered the missing piece of the puzzle. He now knew how to add substance to his games: that logic that made characters tick and non-visual things happen. We did a few more sessions but that project was abandoned long before we reached the end of the Kata document in favour of the sims-based game he’d been aching to write; the one where a few thing might move on the screen but many of the underlying parameters change as time passes.

And that’s when he started flying solo. Now, I hardly ever see his code but the things he creates have me wondering if I could do half as well.

File Upload with ASP.Net Web API

I recently had the opportunity to create a new RESTful service for the project I was developing for my employer. As this service would be used internally, it was the perfect opportunity to try a technology that was new to me: ASP.NET Web API.

This new service would enable the caller to upload and download images. This is nothing particularly unique as there are many excellent examples on the web that demonstrate some flavor of this. All these solutions call System.Net.Http.MultipartFormDataStreamProvider to write the image file to disk. In my case, I wanted to store the image binary in a SQL Server table so I used the System.Net.Http.MultipartMemoryStreamProvider class to allow me to read the contents of the request and send the image stream to the method that wrote to the database.

As I was developing with Visual Studio 2010, I could not use the new await functionality.

public Task<IEnumerable<int>> Post()
{
  if (!Request.Content.IsMimeMultipartContent())
  {
    throw new HttpResponseException(Request.CreateResponse(
	HttpStatusCode.NotAcceptable, 
	"This request is not properly formatted"));
  }

  try
  {
    var streamProvider = new MultipartMemoryStreamProvider();
    var task = Request.Content.ReadAsMultipartAsync(streamProvider)
	      .ContinueWith<IEnumerable<int>>(t =>
    {
      if (t.IsFaulted || t.IsCanceled)
      {
        throw new HttpResponseException(HttpStatusCode.InternalServerError);
      }

      var addedId = streamProvider.Contents.Select(i =>
      {
        Stream stream = i.ReadAsStreamAsync().Result;                      

        // Insert your own code to deal with the Stream.  
        // In my case, I called my code that wrote the image to 
        // database and returned the image's id in imageId such as below.
        int imageId = DatabaseCode(stream);
        return imageId;
      });
      return addedId;
    });
    return task;
  }
  catch (Exception ex)
  {
    throw new HttpResponseException(Request.CreateResponse(
	HttpStatusCode.NotAcceptable, 
	"Error: " + ex.Message));
  }
}

This is a minor tweak to the code from the samples linked above but I thought this might be of use to the next person, or even my future self, who attempts to store images elsewhere than directly to disk as I had to do.

If you found this post helpful or wish to constructively point out improvements, leave me a comment!

Happy coding!

One Thing I’ve Learned Today: MVC Custom HtmlHelper

This week, I’ve spent some time learning MVC and one of the things I was trying to do was to display an image given the path to an image file. Using an <img /> tag in a Razor view seemed crude and less than optimal. That’s when I started watching the MVC PluralSight course offered for free here.

I wanted to be able to use

 @Html.Image(item.ImageUrl, item.Name)

 

Unfortunately, no such thing exists out of the box. However, making this work is surprisingly straight-forward:

Create a custom HtmlHelper class.

using System.Web.Mvc;

namespace MvcApplication1.Infrastructure
{
	public static class HtmlHelpers
	{
		public static MvcHtmlString Image(this HtmlHelper helper,
			string src, string altText)
		{
			var builder = new TagBuilder("img");
			builder.MergeAttribute("src", src);
			builder.MergeAttribute("alt", altText);
			return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
		}
	}
}

Now, all I need to do is add a using statement to my view and add my Image tag where needed:

@using MyProject.Infrastructure
 ... blah blah blah...
 @Html.Image(item.ImageUrl, item.Name)


Quick, simple, and elegant. And if this custom HtmlHelper class is used in more than one view, you may want to forego the adding of the using statement in the view and instead, modify the Views\Web.config file and add the namespace to the list of namespaces defined for razor.