I Am Not Myself

Bills.Pay(Developer.Skills).ShouldBeTrue()

Category Archives: Development

Useful Tool of the Day: smtp4dev

We send a lot of emails to our users at Cheezburger. Sign up for an account, get a new user email. Submit some funny content, get a message with a link to the content so you can find it. Make the homepage and get a congratulatory message. You get the idea. As you can image our marketing team loves to wordsmith and prettify these messages. So we update them often.

I primarily work out of a Virtual Machine and try to keep running background tasks to a minimum. So, I don’t particularly want a SMTP server running unless I am actively working on email code. Enter smtp4dev, a simple light weight dummy SMTP server. It runs in your system tray and gives you an easy way to capture email messages and view them.

So some simple code like this

using System.Net.Mail;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var message = new MailMessage("dirk@diggler.com", "jack@horner.com")
                {
                    Subject = "I AM THE STAR!",
                    Body = @"You're not the boss of me, Jack. You're not the king
                            of Dirk. I'm the boss of me. I'm the king of me. I'm 
                            Dirk Diggler. I'm the star."
                };

            new SmtpClient("localhost", 25)
                .Send(message);

        }
    }
}

smtp4dev will capture it like this

MvFABVU

You can simply double click the message and open the EML file in your default email application to view it.

ASP.NET Html Helper for Enumeration Based Drop Downs

Not a particularly mind-blowing post today, but I found this little bit of code helpful and it might help someone else. So here you go. A simple html helper for ASP.NET MVC for creating drop downs based on Enumeration values. The nice bit is that it will respect Data Annotations Describe attributes.

The helper:

 public static class HtmlEnumHelper
    {
        private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
        {
            var realModelType = modelMetadata.ModelType;

            var underlyingType = Nullable.GetUnderlyingType(realModelType);
            if (underlyingType != null)
            {
                realModelType = underlyingType;
            }
            return realModelType;
        }

        private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

        public static string GetEnumDescription<TEnum>(TEnum value)
        {
            var fi = value.GetType().GetField(value.ToString());

            var attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,
                                                                       Expression<Func<TModel, TEnum>> expression,
                                                                       object htmlAttributes = null)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var enumType = GetNonNullableModelType(metadata);
            var values = Enum.GetValues(enumType).Cast<TEnum>();

            var items = from value in values
                        select new SelectListItem
                            {
                                Text = GetEnumDescription(value),
                                Value = value.ToString(),
                                Selected = value.Equals(metadata.Model)
                            };

            if (metadata.IsNullableValueType)
                items = SingleEmptyItem.Concat(items);

            return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
        }
    }

And some tests that demonstrate it’s usage:

[TestFixture]
    public class HtmlEnumHelperTests
    {
        [Test]
        public void CanGetDropDownForDecoratedEnum()
        {
           var result = CreateHtmlHelper<SimpleModel>()
                           .EnumDropDownListFor(x => x.DecoratedType)
                           .ToHtmlString();

            Assert.That(result, Contains.Substring("foo"));
            Assert.That(result, Contains.Substring("bar"));
            Assert.That(result, Contains.Substring("baz"));

        }

        [Test]
        public void CanGetDropDownForUndecoratedEnum()
        {
            var result = CreateHtmlHelper<SimpleModel>()
                            .EnumDropDownListFor(x => x.UndecoratedType)
                            .ToHtmlString();

            Assert.That(result, Contains.Substring("Fiz"));
            Assert.That(result, Contains.Substring("Buz"));
            Assert.That(result, Contains.Substring("FizBuz"));

        }

        [Test]
        public void CanGetDropDownForMixedEnum()
        {
            var result = CreateHtmlHelper<SimpleModel>()
                            .EnumDropDownListFor(x => x.MixedType)
                            .ToHtmlString();

            Assert.That(result, Contains.Substring("foo"));
            Assert.That(result, Contains.Substring("Buz"));
            Assert.That(result, Contains.Substring("FizBuz"));

        }

        [Test]
        public void CanGetDropDownForNullableEnum()
        {
            var result = CreateHtmlHelper<SimpleModel>()
                            .EnumDropDownListFor(x => x.NullableType)
                            .ToHtmlString();

            Assert.That(result, Contains.Substring("<option value=\"\">"));


        }

        public static HtmlHelper<TModel> CreateHtmlHelper<TModel>()
        {
          var viewContext = new ViewContext
               {
                   HttpContext = new FakeHttpContext(),
                   ViewData = new ViewDataDictionary()
               };

            return new HtmlHelper<TModel>(viewContext, new FakeViewDataContainer());
        }
    }

    public class FakeViewDataContainer : IViewDataContainer
    {
        public FakeViewDataContainer()
        {
            ViewData = new ViewDataDictionary();
        }

        public ViewDataDictionary ViewData { get; set; }
    }

    public class FakeHttpContext : HttpContextBase
    {
        private readonly Dictionary<object, object> items = new Dictionary<object, object>();

        public override IDictionary Items
        {
            get
            {
                return items;
            }
        }
    }

    public class SimpleModel
    {
        public DecoratedType DecoratedType { get; set; }
        public UndecoratedType UndecoratedType { get; set; }
        public MixedType MixedType { get; set; }
        public UndecoratedType? NullableType { get; set; }
    }

    public enum DecoratedType
    {
        [Description("foo")]
        Fiz,
        [Description("bar")]
        Buz,
        [Description("baz")]
        FizBuz
    }

    public enum UndecoratedType
    {
        Fiz,
        Buz,
        FizBuz
    }

    public enum MixedType
    {
        [Description("foo")]
        Fiz,
        Buz,
        FizBuz
    }

See, I can still write C#. 8)

Today I Learned: You Cannot Transfer Ownership of iOS Applications

I have recently completed my first iOS application on behalf of Furnishly, the local furniture exchange. All the release bugs have been worked out and the app is available on the app store. Yesterday, I started looking into how to transfer all the assets over to the owner of Furnishly so he could continue development and review download data on iTunes connect.

On github, this was a snap. Simply go into the administration section for the private repository, scroll down to the Danger Zone and click the transfer button under transfer ownership. Then type in the name of the repository and the new owners user name and hit transfer. Simple, easy.

In iTunes connect, it is a completely different story. There is no obvious way to transfer the application in the UI. Searching around in the FAQ surfaced this gem.

I sold my app to another developer and can no longer distribute it on the App Store. Can I transfer the app to the new developer’s iTunes Connect account?
No, you can’t transfer the app to another developer account on iTunes Connect. To add the app to another account, remove the app from the current account and upload it to the new iTunes Connect account.

Note that uploading the app to a new iTunes Connect account will disable current customers from receiving automatic and free updates of your application. All customer reviews, rating, and ranking information will be reset. You will not be able to reuse the app name and SKU in the old account. If you have uploaded a binary or used the app with the iAd Network, your Bundle ID will not be reusable either.

So apparently the way to transfer ownership of this app to the non technical owner is to:

  1. ask him to create a apple developer account
  2. wait to get accepted
  3. generate new application keys
  4. rebuild the application with the new keys
  5. delete the old application build from my account
  6. resubmit the new application via his account

Oh and all the folks that have downloaded the app in the mean time from my account are pretty much never going to get an update. All the ratings you might have received will disappear.

Seriously this is a horrible way to handle what seems to me would be a common occurrence. Did Zinga have to follow this process when they bought DrawSomething?

Anyone have advice?

Using System.Threading.Tasks On MonoTouch

I ran into an issue this week where I was attempting to load data from a web service asynchronously using System.Threading.Tasks on MonoTouch. I was able to fire the task off but kept getting an error trying to update UI elements when callback was fired.

After a little beating my head against a wall, I took a walk and grew a neuron and this is what I came up with to resolve the issue. Note the call to InvokeOnMainThread.

private IEnumerable<Product> GetProducts(Position position)
{
	return productsService.GetProductsNear(position);
}

private void BeginGetProducts()
{
	Activity.PushNetworkActive();
	var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
	
	Task.Factory.StartNew(() => GetProducts(currentPosition))
			.ContinueWith(OnProducts, scheduler);
}

private void OnProducts(Task<IEnumerable<Product>> task)
{
	if(task.IsFaulted)
		HandleException(productsTask.Exception);
	else 
	{
		InvokeOnMainThread(() => {
			this.products = task.Result;
			ShowProducts();
		});
	}
	Activity.PopNetworkActive();
}

Sinister Bug is Sinister

Can you spot the bug in this flags enumeration?

    [Flags]
    public enum ItemCoreChangeType
    {
        ViewStyleChanged = 1,
        VaryByStructureChanged = 2,
        LayersChanged = 4,
        LayerContentsChanged = 8,
        PropertiesChanged = 16,
        ErrorsChanged = 32,
        ChangeHistoryCleared = 64,
        EditableCommentChanged = 128,
        NeedsValidation = 256,
        AffectsPropertyChangeHistory = 512,
        AffectsLayerChangeHistory = 1024,
        PushFormatters = 2048,
        ResetValueGroups = 4096,
        SkipChangeTrackingUpdate = 8092,
        StatusChanged = 16384,
        Flexible2DIndicesChanged = 32768,
    }

In case you can’t spot it with the naked eye (I couldn’t, coworker Alex caught it.), watch this video. Pay attention to the binary display as I enter in the values of my enumeration above. Notice how the bit is steadily walking down the display? What happens when I hit SkipChangeTrackingUpdate?

So it seems that when I use the SkipChangeTrackingUpdate value I am actually sending many of the other values in this flags enumeration. Nasty bug to track down eh?

What makes this bug so sinister is just how long it took to find. Using the blame command in git, I see the following result. The names have been changed to protect the guilty.

72fe38b4 (dirk.diggler 2010-02-10 23:49:28 -0800 33) SkipChangeTrackingUpdate = 8092,

So this particular flaw has been in the code base unnoticed for close to two years. Two years worth of code has been written with the assumption that SkipChangeTrackingUpdate actually sends the value of 9 different flag values. Fixing the flag value could potentially effect any part of that code.

What do?

Lucky for me, a search for that flag in the entire code base returned 3 usages, one of which was the definition of the flag, one was the usage of the flag and one consuming the flag.

Crisis averted but it could have been much worse.

SSDNUG Presents: James Thigpen – Moar Cats Please: Software Development at Cheezburger

The South Sound .NET Users group is proud to present James Thigpen on Thursday Feburary 9th at 7:00PM at the Olympia Center in the heart of downtown Olympia, WA.

There is a lot of talk in an abstract sense about how agile software practices work. James is going to talk about how Cheezburger does agile with a remote team spread across the US and Europe. This isn’t theory, this is how Cheezburger ships code every day. Expect to hear what has worked and what failed.

Cheezburger is heavily invested in TDD, Continuous Deployment, Automated Testing, Split Testing, agile/lean methodologies, and continuous improvement. They have doubled the size of their team in the past year and lived to tell the tale. Cheezburger usually ships code more than ten times a day without interrupting the 1.8 million daily active users visiting their sites and they have a lot of fun doing it.

James Thigpen is the Director of Engineering at Cheezburger Network, one of the largest online humor companies in the world. James has a deep passion for agile and lean software development practices. He has a wide variety of experience developing software and leading teams in industries such as municipal inventory, biomedical imaging, IT management, and online media.

If you missed the January meeting with Adron Hall, you can still catch it online.

Displaying a Map of the Current Location with MonoTouch

Today, I started spiking on displaying maps in iOS using MonoTouch. I wanted to discover the minimum amount of code needed to get the users current location via the iOS GPS services and then display that location on the a map.

To get the devices current location you need an instance of CLLocationManager found in the MonoTouch.CoreLocation namespace. The location manager accesses the actual hardware on the device and can be a real power drain, so you want to use it as little as possible.

using System;
using MonoTouch.CoreLocation;

namespace App.UI
{
	public class LocationService
	{
		private CLLocationManager locationManager;

		public LocationService()
		{
			locationManager = new CLLocationManager();
		}

		public CLLocationCoordinate2D GetCurrentLocation()
		{
			//dirty for now just to get some info.
			locationManager.StartUpdatingLocation();
			while(locationManager.Location == null);
			locationManager.StopUpdatingLocation();

			return locationManager.Location.Coordinate;
		}
	}
}

This simple service shows the absolute minimum needed to retrieve the devices current location. First, we tell the manager to StartUpdatingLocation which will trigger a dialog to the user requesting access to the devices location services. The current location is then available from the Location property. It takes a few seconds to populate though, which is why most of the demo code you will find uses a LocationDelegate to consume the data. I wanted something a little simpler because I don’t actually need updates to the location, so I spin until the Location property is not null. I then grab the Coordinate from the Location property and tell the manager to StopUpdatingLocation.

On a side note the user can disable location globally on the device. You can check to see if the user has done so via the static member LocationServicesEnabled. You could use this to display a dialog to ask the user to put in a zip code maybe as an alternative.

To display the location on a map for the user you will need to use the MKMapView from the MonoTouch.MapKit namespace. I have chosen to create a MapViewController class that extends UIViewController to wrap all this code in.

using System;
using System.Drawing;

using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.MapKit;
using MonoTouch.CoreLocation;

namespace App.UI
{
	public class MapViewController : UIViewController
	{
		private LocationService locationService;
		private MKMapView mapView;

		public ProductsViewController(LocationService locationService)
		{
			this.locationService = locationService;
		}

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();

			var currentLocation = locationService.GetCurrentLocation();
			var visibleRegion = BuildVisibleRegion(currentLocation);

			mapView = BuildMapView(true);
			mapView.SetRegion(visibleRegion, true);

			this.View.AddSubview(mapView);
		}

		private MKMapView BuildMapView(bool showUserLocation)
		{
			var view = new MKMapView()
			{
				ShowsUserLocation = showUserLocation
			};

			view.SizeToFit();
			view.Frame = new RectangleF(0, 0, this.View.Frame.Width, this.View.Frame.Height);
			return view;
		}

		private MKCoordinateRegion BuildVisibleRegion(CLLocationCoordinate2D currentLocation)
		{
			var span = new MKCoordinateSpan(0.2,0.2);
			var region = new MKCoordinateRegion(currentLocation,span);

			return region;
		}
	}
}

This simple ViewController overrides the ViewDidLoad method, consumes the LocationService to get the current location and then displays that location on with a MKMapView. We build up the map view in two steps, the first creates the instance of the map view and sizes it to fit the viewable area of the given display. The MKMapView has a property that will automatically show an indicator of where the curent location is, setting this property is all you need to do to display the map and location. There is a catch though, if you were to display this map now you would see a map of the entire United States and not a reasonable local view of the area. The second step is what zooms the map into a reasonable region to display.

If we display this controller now in the iPhone Simulator, this is what we see.

Getting Started Building iOS Applications with MonoTouch

I have been flirting with the idea of getting into mobile development in my spare time. I have went so far as to offer myself out as a developer to startups in Chicago to develop simple iOS applications in exchange for tool licenses. I am a firm believer in the idea that a craftsman buys his own tools. I am not buying them with my own money here, but I certainly am with my effort.

I also wanted to turn this experience into a few blog posts that might help someone else who has chosen to go down the same path that I have.

So what does a .NET developer need to get started writing an iOS application? There are three things to consider here. The first being picking up Objective-C as a language, second is learning the iOS API and third is relearning how to do stuff we already know like consuming a JSON service. Put another way, we need to learn a language, a platform and the idiomatic way of doing things in this particular development culture. That is a lot to bite off in a short period of time and still be productive and getting stuff done.

For this reason, I chose to develop my first few applications using Xamarin’s MonoTouch. Taking this route allows me to leverage my current skills with C# and the .NET platform while learning the iOS API and still manage to be productive. I can noodle around with Objective-C at a later time.

The first thing you will notice about MonoTouch is the price, at $399 it is quite a leap of faith. But you can install and use the evaluation version to your hearts content. You only have to pony up money once you are ready to ship to the App Store.

To get up and running with MonoTouch, you will need to install the following things in this order:

  1. XCode 4 – If you don’t mind paying $5, you can get this from the Apple App Store.
  2. MonoDevelop – This is a completely free IDE for the Mono framework.
  3. MonoTouch Evaulation

You will also need a Mac. Yes sorry, thems the breaks.

To create an iOS application simply select File > New Project and dig down to the MonoTouch iPhone project template. There are also templates for iPad and Universal. Universal allows you to create a single application that will work on both the iPhone and the iPad. You can also create library assemblies just like you would expect in Visual Studio.

There is one catch though, MonoTouch project types are limited in the amount of the framework you will have access to work against and what 3rd party libraries you can reference. It is similar to working with Client Profile projects in Visual Studio. Everything you reference needs to target MonoTouch as well.

For instance, I have been working on an application that consumes a Xml-Rpc service.  There is already a fairly awesome OSS library from Cook Computing for all your Xml-Rpc needs. You cannot simply download the dll and reference it in your project. The dll needs to be compiled as a MonoTouch assembly. And all code needs to conform to the limited framework profile of MonoTouch. Cook Computing’s library has both client and server components in one library. The server components depend on HttpResponse & HttpReqeust which are not available in a MonoTouch application.

I was able to solve this problem fairly easily by creating my own fork of the Cook Computing library and pulling in only the types needed for client communication. I even went so far as to publish this work on GitHub so others can simply use my fork and get back to making things awesome. Yay, OSS!

If you would like to look at a couple nontrivial applications written using MonoTouch to get an idea of where to start, the Washington State Department of Transportation has a great application published to the App Store now that is fully open source. I used this application as a guide post when creating my first MonoTouch app which you can find here.

This should be enough to get you on your way to writing your first application. I have some more tips around using OSS libraries and Unit Testing, but that will have to wait for another day in another blog post. Enjoy and happy non-conformist .NET application development day.

Adron Hall Visual Studio AWS Toolkit & SDK Presentation Video

Overview

During this presentation I will provide an overview of what is needed to get started using Visual Studio 2010 with the AWS Toolkit & SDK. We’ll also cover the basic design ideas behind the do’s and don’ts of cloud architecture and development. There will be some hands on coding (if you’d like to bring a laptop to follow along) and we will deploy code (wireless/cat5 connection pending) into AWS Cloud Services & get EC2 instances up and running live!

About Adron

I’m a jovial, sometimes TDD (Test Driven Development), sometimes BDD (Behavior Driven Development), get things done well, software architect, engineer, code monkey, coder, or what have you. I run the gamut of development stacks between the .NET Framework & Microsoft Technologies but will admit my latest favorite is Ruby on Rails and .NET MVC work with a touch of Sinatra’s clean architecture covered with an awesome layer of Javascript for tasty perfection. I love what I do and commonly add a very business oriented, get the job done, agile (sometimes eXtreme Agile, sometimes whatever it takes), and entrepreneurial effort to my work. I also like to mentor (teach), write (re: blog, etc), and even work on projects in addition to work related things.

You can find more on his site.

Video

Slides

Source

The source for this presentation can be found on Adron’s github account.

Testing Rendered Output of NancyFx with the Razor View Engine Gotchas

I have been working on a small sample application called SignMeUp. My intention is to practice concepts I am learning while reading Growing Object Oriented Software Guided by Tests. I am using the awesome NancyFx micro-framework my web delivery mechanism and Razor as my view engine.

To start I have the following unit test.

    [TestFixture]
    public class when_visiting_the_root_of_the_site : with_a_browser
    {
        private BrowserResponse response;

        public override void Given()
        {
            Configure(with =>
            {
                with.Module<RootModule>();
                with.Dependency<IEmailService>(Substitute.For<IEmailService>());
                with.Dependency<DataContext>(TestDataContextFactory.Build());
            });

            base.Given();
        }
        
        public override void When()
        {
            response = subject.Get("/");
        }

        [Test]
        public void it_should_be_successful()
        {
            response.StatusCode.ShouldBe(HttpStatusCode.OK);
        }

        [Test]
        public void it_should_show_the_signup_form()
        {
            response.Body["form"].ShouldExistOnce()
                    .And.Attribute["action"].ShouldBe("/");
        }
    }

I have been beating my head against a problem for a few days (over the course of several 1-2 hour development sessions) that has been baffling me. This test compiles and executes and the first test returns successful. The second test has always failed because the Body collection was always empty. The truly enraging thing is I could fire up the site in IISExpress and see that it worked properly.

After searching the internet high and low, trolling source repositories of example apps and finally breaking down and scouring the NancyFx source I have discovered the root of my problem.

Gotcha #1: When executing end to end tests like this from a test library you need to makes sure that your test assembly has knowledge of your views. The simplest solution for this is to set all your views to “Copy if newer” in the properties dialog in visual studio. The default view location should work from here.

Gotcha #2: Your test assembly needs to reference Nancy.ViewEngines.Razor. If you do not have this reference, Nancy will happily process your request and simply return an empty body. No error, no warning, nothing.