One think I’ve learned today: Vim!

I was recently struck with how productive a developer could be when using a text editor and keeping his hands on the keyboard.  Sure, I’d coped with Vi 20 years ago in university but I’d been relieved when “better” graphical editors eventually came along for my mouse-driving pleasure.

But still:  Productivity such as I was witnessing was worth investigating.  So with courage in hand I installed Vim and went through the tutorial to learn the basic commands.  Now, I’m inventing reasons to use Vim just so I can get more adept at it.

I’m still young enough to learn new tricks.  What have you learned today?

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!

Kids and Code: Where to start?

Though I am a software developer, I am not a born educator so when my children demonstrated a spark of interest in learning how to program a computer, I turned to the internet and searched for resources appropriate to their age and personalities.

I performed my first search several years ago and the results were less than encouraging. I found a few books aimed at an audience much older than my children were at the time, a few antiquated programs that oftentimes did not install correctly on my home computer, and very little else. Much has changed with every year adding more exciting options to the mix. Here are a few of the options I would have been glad to find back then and may yet be making use of.

Please note that while I may not have personally tried all of these and cannot vouch for their suitability or effectiveness, I do like what I’ve heard and seen so far. I’ve tried to organize the list by age but here again, your individual mileage may vary as every child is unique. I provide some links to online resources but I strongly encourage you to search for more as there are often several excellent sites out there dealing with the same topic. Finally, I’ve deliberately kept the links visible so this list could be printed and remain useful.

How to train your Robot: http://drtechniko.com

Dr. Techniko developed a “programming language” that 5 – 7 year old children can master and write their own program with. It involves no computer and no typing. The programmer uses a series of pre-defined symbols to program their “robot” to perform a certain task. Too bad my own children are too old for this. Looks like fun!

The only requirement is the information from the web site, a goal to accomplish and a patient and willing robot (parent). :)

Scratch: http://scratch.mit.edu

Scratch is a simple drag-and-drop language designed to enable children to create their own interactive stories, games, and art. It has a healthy online community and a huge amount of resources. It is free and can be downloaded from the web site.

LOGO:

I remember learning LOGO as a child and was pleasantly surprised to see that this lovely language still exists though some of the web sites are a bit dated. LOGO is primarily a geometric shape drawing language.

The list of LOGO commands can be found at http://mia.openworldlearning.org/voctable.htm though much of the rest of this web site is not publicly accessible. There is a nice editor to type your programs into at http://learninglogo.com.

LEGO Mindstorms NXT: http://education.lego.com/en-us/preschool-and-school/upper-primary/8plus-mindstorms-education

LEGO’s Mindstorms NXT line of programmable robot controllers is an amazing though unfortunately expensive teaching tool. Out of the box, I was a bit dismayed to see that the controller comes with very little in terms of instructions or sample projects but there is a large amount of material online. This means that once your child has happily torn the wrapping paper off the box, the next stop will be the computer to find something to build with the kit.

LEGO recommends this for children 8 and older. Access to the internet is necessary in order to read up on how to program the controller and to research all the neat creations that can be built.

Alice: http://www.alice.org

Alice is an object-oriented language used for creating 3-D animated stories, videos or games. It uses a drag-and-drop development environment to avoid unwieldy syntax or complex development tools found in other languages. Alice also has a very active online community.

Targeted to children in middle grade and up, Alice is freeware and can be downloaded from the web-site.

Computer Science Unplugged: http://csunplugged.org

Computer Science Unplugged is a series of interactive group activities that teach computer science concepts without the use of a computer. Aimed at the 5 to 12 year-old group, all you need is a small group of willing participants and someone to lead the activity.

Phrogram: http://phrogram.com

Phrogram is a Visual-Basic-like language that doesn’t attempt to shield the programmer from syntax or the complexity of development tools. Indeed, combined with the appropriate extension libraries, Phrogram applications can be written to access a database, do complex mathematical calculations or read and write to a file on disk. Aimed at the more sophisticated programmer, Phrogram can be downloaded from the web site for a reasonable fee.

Codecademy: http://www.codecademy.com

Codecademy is an excellent web-based resource for learning web-based development languages and tools such as JavaScript, HTML, CSS, Python and more. It goes through material in a gradual manner. This web site is suitable for anyone who doesn’t require animated characters leading them through their training as if it were a game. A browser is all you need to get started. I know several adults who have learned programming through Codecademy.

Microsoft XNA Game Studio 4.0: Learn Programming Now! http://www.microsoft.com/learning/en/us/Book.aspx?ID=14907&locale=en-us

Though not strictly an online resource, this is an excellent book by Rob Miles (Microsoft Press) that teaches a beginner the basics of the C# language and the XNA framework in order to develop games for the XBox platform.

My son devoured the previous edition of this book when he was 10 years old. He read cover-to-cover and tried the first few examples on his own. Then, over spring-break that year, the two of us sat down and went through the remaining exercises till he had a working game and an reasonable grasp of object-oriented programming.

A Windows 7 computer is required. Visual Studio Express and the XNA Framework can be downloaded for free. Access to an XBox 360 makes the end result more exciting but is not required.

Coursera: https://www.coursera.org

Coursera is a collection of free university-level online courses. These courses start a pre-defined date, go for a set number of weeks and require assignments and evaluations to the handed in at specific times. A certificate is presented upon successful completion of the course. Great for teens and adults.

For this, you need to be able to dedicate time each week to view the several hours of lecture videos and complete the assignments.

 

Along with the above online or book resources, I also recommend looking at community or library education programs, summer camps and other organizations in your community. A quick search of my community guide shows me the following programs are being offered for a reasonable fee:

  • Summer Day Camps: There’s an animation and Web design session for children 8 – 13 and a LEGO Mindstorms NXT program aimed at children 6 – 10.
  • Weekly sessions: Introduction to programming with Scratch is offered to children 11 – 15. Various robot building sessions using LEGO’s Mindstorms NXT are targeted to children 5 – 16 years old. Java, C++, and web design courses, on the other hand, are offered to the 12 – 16 age group.

And finally, there may be private tutoring companies in your community that offer programming courses. For example, Real Programming 4 Kids offers game programming classes for children of various ages in my community. This particular company has at most a 4:1 student to teacher ratio, ensuring that each child gets a fair amount of individual attention. Organization of this type may exist in your community though they may come with a higher price tag than you’re willing to spend.

While I have highlighted the resources I’m familiar with, there are many more excellent ones out there that have simply not crossed my radar. If you know of them and can recommend them, leave me a comment and I’ll gladly update my list.

One thing I’ve learned today: Learning new technologies via samples results in Frankencode

I was asked to develop an internal tool that would manage the advertisements we would display in our application. My requirements were simple: I needed to provide the user the ability to view the list of existing ads, create an ad by uploading an image along with the ad metadata, update and ad or delete an ad. Since our customers would never see this application, I went on a limb and chose a technology I’d never tried and knew nothing about: .Net Web Api. I figured I’d adapt one of the many excellent examples I found on the web so that it would serve my purpose. How difficult could it be?

I wrote the service component first and left the ad management user interface till last and for that, I chose a simple product catalog sample application that used jQuery and Knockout.js, two more technologies I had no previous experience with. Again, I knew there were lots of code snippets available on the web for those libraries so, armed with a decent search engine and StackOverflow, how could I go wrong?

The product catalog sample provided me with code for a basic grid and a set of detail fields. The user would enter the row id in an edit field and click a button to fill the detail fields with the data for that particular ad. An Update and a Delete button at the bottom of the page would update or delete the selected ad. This wasn’t quite what I had in mind but it was a close approximation. I figured adding a delete button to the appropriate row in the grid and providing the ability to click a row to populate the detail fields would be simple to implement once I had the basic functionality working.

I looked for examples of image uploading and found several, all with their quirks and limitations. Figuring out which limitations I could live with and which I couldn’t took some time. I really wanted to be able to upload an image and its associated metadata (name, width and height) all in a single POST request but most of the samples either dealt with uploading just the file or uploading a whole slew of files…but no other data. I tried all sorts of file upload methods with various degrees of success before settling on one that used a strict HTML page with a form tag and a submit button. Have I mentioned I’d never dealt with uploading files over HTTP POST requests before?

Frankencode monster

Once I got the file upload working (though I’m now working on the functionality that will inform the user whether the upload succeeded), I stepped back and took a cold hard look at my application. What I saw was a Frankenstein-type application. The samples I combined were never meant to go together. I know I’m not validating my fields in an even remotely optimal manner. I’ve tried to hide the delete button for images that are still referenced by an ad and therefore can’t be deleted but haven’t figured it out yet. It should be a simple matter of making the delete button’s visibility conditional upon whether the image is referenced by an ad but my condition always evaluates to true so I still have to do a bit more work on the project.

Have I learned something? A resounding yes! I can now claim to know some jQuery, a bit of Knockout.JS and something of .Net Web APIs. However, I’m lacking a lot of the very basic knowledge that I would have gained if I’d picked up a book about any of these topics and read the first few chapters. I liken it to trying to learn C# by trying out async samples. You might eventually understand how the async functionality works but without an understanding of basic C# constructs, you won’t be able to extend those samples without creating a monster and without looking for yet another sample to base your next bit of code on.

But I have to admit it’s been a lot of fun! 😉

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.

My learning quest

Early in January, I declared this the “Year of Learning”. The year I would immerse myself in technology and absorb as much as possible in all the areas I don’t yet consider myself knowledgeable enough. This means I have started and will continue to deepen my understanding of various aspects of software development from patterns to new programming language syntax, from modern data stores to effective debugging tools and techniques, from JavaScript and its myriad helper libraries to the intricacies of asynchronous programming.

Strategy Strategy

In order to accomplish this lofty self-improvement goal, I took the plunge and subscribed to PluralSight online training. This amazing library of on-demand videos is now my introductory-level training resource. Apress, O’Reilly and Manning are three great sources for technical books and regularly offer discounts on select eBook titles so I’ll be supplementing the online training with their wares, starting with the small collection of eBooks I purchased in the past year but never got around to reading. These should help flesh out concepts to a higher degree than an online course could ever do. But skills learned and never applied get lost quickly so I’ve also committed to spending more time developing code at home so I could try out interesting techniques and tools I might not otherwise get a chance to use.

How will I measure improvement?

I’ll know I’ve improved when I’m able to read the MSDN Magazine each month without feeling that every article has been written for someone much smarter and knowledgeable than I am.

Measuring Progress

It’s only February and already, I feel I’ve woken up to all sorts of new-to-me concepts and strategies that I can’t wait to put into practice. I must be doing something right!

What next?

Now that I have been at it for almost two months, I’m ready for the next step in the journey and that is to share some of what I’ve learned with others as I go. This is prompting me to dust off my “One Thing I’ve learned Today” series. I’m not aiming to write every day but I’ll post something here as often as I can in the hopes that someday, someone else may find a useful bit of information that will help them along their own journey.

Please join me!

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!

Hackathon: An experience worth living

Last Friday, I participated in my first ever Hackathon. It was the second such event sponsored by my employer. The event was held from noon to midnight and attended by approximately 13 developers from various geographical locations.

Two of us participated from the Canadian office and partnered on a small feature. Others connected via VPN (Virtual Private Network) while a small core group ran a tight ship in the bowels of our main development centre* in central US.

First, a bit of background information. My company creates and sells assessment software for use in kindergarten to grade 12 schools with a focus on math and reading comprehension. Students are encouraged to take quizzes to validate their understanding of curriculum concepts. Teachers can then report on results and identify which concepts need to be taught more in-depth or which students require more assistance.

The challenge for this Hackathon? Given an event notification that a student has started or completed a quiz, what useful subsidiary steps could we take? My partner and I chose to code a book recommendation engine. When Student A clicks to start a quiz, our engine would get notified with information about the book such as its author, reading difficulty level, number of words, and whether the book was fiction or non-fiction. Given that information, our engine would search a library of available books to find three titles Student A might like to read next.

Books by the same author would be favoured*. So would books of the same type (fiction or non-fiction) as well as books of approximately the same length since we figured a child who’s just completed an early reader is unlikely to be ready to tackle a heavy tome.

Once Student A completes the quiz, a notification is received with the quiz results. If the student performed well on this quiz, our engine would recommend books that were slightly more difficult than the one just read. If, however, the student struggled, it would take that into consideration and recommend books that were slightly easier. Our goal was not to discourage a reader by recommending something too difficult.

The engine would then send an email to Student A’s parents to inform them that their child has just taken a quiz and here are three books we recommend they read next.

A snapshot of our Kanban board towards the end of the evening.

 

Another team chose to sent notification to Twitter whenever a child passed a quiz while yet another chose to create a live heat map that would show where quizzes are being taken in the last few minutes. The solutions were all very different from one another and used a wide variety of available technologies.

This project was a lot of fun to do though, naturally, it was built on a slew of assumptions that would not hold in real-life. For example, that library of books to search through for books to recommend? We made it up. We have that information in the software somewhere but it would have taken too long to make it available for our purposes given that only had 12 hours to work with.

We also made the simplifying assumption that only one quiz was being taken at a time and that the quiz would be started and ended reliably. Limitations that can’t work in real life but make it possible to build a simple prototype which was all we were hoping to produce.

Will we ever implement this kind of functionality in our product? Who can tell? But I sure had fun coding it and I’m already looking forward to the next Hackathon!

* These are not spelling mistakes. I am Canadian! 😉

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.