Author Archives: Travis

Testing ASP.NET with Sessions and HttpContext

In my last post I advocated strongly for writing tests for any project that you inherit that does not have them.

As I begin to build a test suite for the code I am now responsible for, I am going to be writing about challenges I run into writing tests in a framework with which I am not heavily experienced.

Mocks Are Your Friend

When writing tests, it is important to isolate the code that you are testing to make sure that only it is being tested. You usually want to test specific behavior from a specific scenario.

One of the ways you can do this is by mocking or faking the responses from any other parts of the code that it calls.

The framework that I have decided to use for this is called Moq and makes it pretty easy to create a small stand in object that fakes the response you want.

Using these I was able to isolate problem areas in the test to determine the resources I needed to get the code to operate correctly.

HttpContext in Your Test

The project I am working on is an ASP.NET application. The way it was designed relies on redirects, the HttpContext.Current, and Sessions. This means that testing things can get tricky.

I was trying to Mock out the responses I needed for my test and made good headway doing so. But after doing a bunch of research along with trial and error, the best place I found to create the HttpContext for the test is in the TestInitialize portion of the test.

        public void TestInit()
            var request = new HttpRequest("", "http://localhost", "");
            var response = new HttpResponse(new StringWriter());
            var testHttpContext = new HttpContext(request, response);
            HttpContext.Current = testHttpContext;

Their are many cases where you would just want to make a simple Mock of the HttpContext and whatever you were trying to get out of it in the function, but the function I was testing used so many aspects of it that it just made sense to create one in the test initialization.

Session in Your Test

The main problem I ran into was with Session. Every use of Session in the code I was testing gave an error of “Object reference set to Null.” Additionally their did not seem to be a good way to Mock it out. It is not created by default in a new HttpContext, so putting that in the TestInitialize section did not work.

After doing a lot of digging, I finally found a way to add a new Session to the HttpContext. You have to create a HttpSessionStateContainer and then use the SessionStateUtility to add it to your HttpContext object in the TestInitialize code.

var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                            new HttpStaticObjectsCollection(), 10, true,
                                            SessionStateMode.InProc, false);
SessionStateUtility.AddHttpSessionStateToContext(testHttpContext, sessionContainer);

If you are tearing your hair out trying to figure out how searching for things like “C# test set httpcontext” or “C# test mock session”, then hopefully this helps you.

Happy Testing

Inheriting a Large Project with No Tests

Recently I have begun working part time for a small startup that has had a base version of their software already created by a company that used an overseas team. The codebase is large and in a language and framework that I have not worked in recently and uses features that I had not previously heard of.

On top of that their are large blocks of commented code, hardcoded values for things that need to be in a config file, and not one test.

As a professional software developer, when you are creating a large project for the company you work for, for a client or even for yourself, you absolutely should write test. Many people would even say you should write the tests first (TDD).

So what do you do when you inherit a large, legacy project that has zero tests?

Step One: Get a Build Working

Code is really difficult to test if the code doesn’t work or you don’t know how it should work. First you need to make sure you have a build that runs. If it doesn’t run, time to debug and get it running. It helps if you have someone who knows how it should be working so that even if it does not work properly, you can make it.

Step Two: Begin to Eat the Elephant

How do you eat an Elephant? One bite at a time.

Pick a small piece of the code and write a test for it. For the first test, try for a simple piece of code that does not rely on a bunch of things being mocked out (learned this the hard way).

Step Three: Take Another Bite

Repeat step 2 until you have reasonably good test coverage of the project. This does not necessarily mean 100% test coverage.


If the code is particularly troublesome to get working, it is actually a good idea to write tests for sections of the code that do not work properly as you go through step 1. When something does not work, write a test that will pass when it does work and then fix the code.

Most importantly, remember to be a professional and write tests.

The ONE Thing Book Review

I heard several people discussing a book called The ONE Thing with very positive things to say about it. It was recently available for free through one of the many benefits you get through Amazon Prime, called Prime Reading although it does not appear to be any longer, and I took the opportunity to read it. I am so very glad that I did.

The basic principle is simple. Have one thing that is your focus, your priority. Work on it everyday. This is the key to success.

It is all centered around asking something like this:
What is one thing I can do, that if I do it, would make everything else easier or unnecessary?

The author identified these 7 areas of your life to ask that question about. The order is important.

  1. Spiritual Life
  2. Physical Health
  3. Personal Life
  4. Key Relationships
  5. Job
  6. Business
  7. Finances

It is important that the answer to the question be both big and specific. If it is not big, it won’t change much and won’t actually make other things easier or unnecessary. If it is not specific, you won’t know what your next step is.

The process that is setup is to take this guiding question and look at five years in the future at where you want to be. Then ask what needs to be done in the next year to reach that goal. Ask the same question about six months, three months, one month, this week, and finish by asking what you need to do today.

Then do it.

Strong recommendation on reading this book and asking yourself this question. You may be surprised at your own answer.

Xamarin Forms: ListView with SQLite

Previously we stored our entry in a SQLite database. Now we want to be able to look at a list of the things we previously saved.


When you want to display a list of objects, your best option is most likely the aptly named ListView. The ListView binds to a dataset and then displays each item according to a template in a scrollable list.

This is exactly what we want to use to view our saved properties for the cashflow calculator.

Getting the Data

There are several ways to get the data out of the SQLite database and into the ListView. Two of the most common ways are returning the result to a List or creating a CursorAdapter.

I chose to use the List method as it is simple and worked well with how I have set up the database calls to be asynchronous.

A New Page

We need to create a SavedProperties Page and set up our ListView there.

In the XAML file, we need to create our ListView and our template for each item. For now I just want to display the property name and its value.

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="" xmlns:x="" x:Class="SimpleCashflowCalculator.SavedPropertiesPage">
    <ListView x:Name="saved_properties_list">
                    <StackLayout Orientation="Horizontal" 
                        Margin="20, 10, 20, 0" >
                        <Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" />
                        <Label Text="{Binding Value}" />

This creates a ListView called saved_properties_list and gives it an item template with 2 text labels. It is now expecting a Name field and a Value field for whatever objects are bound to this ListView.

Setting the ItemSource

The way to actually tell the ListView which dataset to use is by setting its ItemSource. We want to refresh this view every time we switch to it so that it always has the latest data. To do that we are going to set the ItemSource in the OnAppearing event.

        protected override async void OnAppearing()
            saved_properties_list.ItemsSource = await SimpleCashflowCalculatorPage.Database.GetPropertiesAsync();

This is a parent class method so we override it and then call what is often called the super method or the parent method before adding our changes.

From the previous post we added this method to our Database class.

public Task> GetPropertiesAsync()
    return database.Table().ToListAsync();

We use this to set the ItemSource of the ListView to be all of our Properties in the database.

The next thing we want to add is a click event listener so that when a ListView Item is clicked, it will go to the edit page for that Property and pass its database ID to allow it to be edited.

Xamarin Forms Local Storage with SQLite

In the process of rewriting the rental property cashflow calculator app from Android and Java to Xamarin, I have gotten to the point where the calculator part is working pretty much how I want and already has some improvements over the Java version.

Today I added the ability to save the properties to a local SQLite database.

Add a NuGet Package

Since this is a Xamarin Forms application, I am trying to write as little platform specific code as possible. The SQLite-net PCL NuGet package helps significantly in this regard.

You will end up adding it to your main Forms project as well as to each of the platform specific projects that you want to build for.

FileHelper Interface and Implementation

The only thing you end up needing platform specific code for when using this package is for implementing the interface to find where the SQLite file is stored on the device.

In the Forms project, add a new interface called IFileHelper that looks like this:

    public interface IFileHelper
        String GetLocalFilePath(string filename);

Then in your YourAppName.Droid project, you would create a new class that implements this interface. It would look something like this:

using System;
using System.IO;
using Xamarin.Forms;
using YourAppName.Droid;

[assembly: Dependency(typeof(FileHelper))]
namespace YourAppName.Droid
    public class FileHelper : IFileHelper
        public string GetLocalFilePath(string filename)
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            return Path.Combine(path, filename);

Note the [assembly …] part of the code. This is a metadata attribute that registers this class as a FileHelper to the DependencyService. If you do not register your interface, the DependencyService will not be able to find it at run time and will throw an error.

Creating a Model

The easiest way of handling the data that goes in and out of your database is with a class that models all of the attributes of your SQLite table. In my case that is a property. Your model will be a basic class with a few fields. You will most likely want an ID field that auto increments. Here is the Property model I used for an example.

using SQLite;
namespace YourAppName
    public class Property
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
        public string Mortgage { get; set; }
        public string Rent { get; set; }
        public string Vacancy { get; set; }
        public string Repair { get; set; }
        public string Management { get; set; }
        public string Tax { get; set; }

Creating Your Database Class

Now that you have your model and file helpers, you will most likely want a class to handle common operations for your Model like fetching multiple records, adding a new record, fetching a single record, and deleting a single record.

Here is an example of a class that handles these actions.

    public class PropertyDatabase
        readonly SQLiteAsyncConnection database;

        public PropertyDatabase(string db_path)
            database = new SQLiteAsyncConnection(db_path);

        public Task> GetPropertiesAsync()
            return database.Table().ToListAsync();

        public Task GetPropertyAsync(int id)
            return database.Table().Where(p => p.ID == id).FirstOrDefaultAsync();

        public Task SavePropertyAsync(Property property)
            if (property.ID != 0)
                return database.UpdateAsync(property);
            else {
                return database.InsertAsync(property);

        public Task DeletePropertyAsync(Property property)
            return database.DeleteAsync(property);

You may want to add the ability to get a specific set of records, for example all properties that have a value above or below a certain amount.

Also notice that we create an asynchronous database connection that is only designed to be opened once and left open waiting for commands during the lifecycle of the app. This avoids the overhead of creating a new database connection for every operation.

Setting It All Up

Now that we have a class set up to allow us to easily access the database, we need to create an instance of it and start performing some operations.

        static PropertyDatabase database;

        public static PropertyDatabase Database
                if (database == null)
                    database = new PropertyDatabase(DependencyService.Get().GetLocalFilePath("YourAppNameSQLite.db3"));
                return database;

Here we use the DependencyService to ask for the platform specific FileHelper that we created earlier so we can access the SQLite database file.

Now you are all ready to start using the database instance. For an example, I created a Save Property button that calls the following method on the ‘Clicked’ event:

        void SaveProperty(object sender, EventArgs e)
            var property = new Property();
            property.ID = property_id;
            property.Value = property_value.Text;
            property.Mortgage = mortgage.Text;
            property.Rent = monthly_rent_cash.Text;
            property.Vacancy = vacancy_cash.Text;
            property.Repair = repair_cash.Text;
            property.Management = property_management_cash.Text;
            property.Tax = property_tax_cash.Text;


My next step is to create a page for the app that lists the currently saved properties. This should be pretty straightforward with the PropertyDatabase class I created and a ListView.

Xamarin Tutorials and Documentation

If you get stuck, the tutorials on Xamarin’s Developer Center were very helpful for learning this and the source code for their ToDo app ended up being invaluable as well.

Also you can reach out to me at travis at

First Monkey-X Game: Images and Theme

Games in general can get by with just basic shapes like squares, circles and triangles if the gameplay is good enough.

But we don’t want to just get by, so we are going to add images to our game that have a theme.

If you recall from earlier in the series, our theme is being underwater in a submarine fighting various kinds of biological and mechanical enemies.

We Need Art

The first thing we need is art.

There are a variety of ways to acquire game art. You can make your own, hire someone to draw you custom art, buy some already created art assets, or use some free art from a site like

Personally I like to draw and make little art assets. There are a lot of free tools that you can use and the images you make don’t have to be great, especially not for your first game.

What Will We Draw?

Let’s start by making a list of the objects in our game that we want to have art for.

  1. The Player
  2. 3 or more Enemy types
  3. 1 or more Bosses
  4. 1 or more Projectiles
  5. 1 or more Power Ups

For now we are going to start with the Player, some Enemies, some Projectiles, and a Boss. We will save the power ups and other images for later.

What Style Will We Use

One of the important things about your art is that is has a consistent style. Most of the time you don’t want to be mixing some 8 bit pixel art with cartoonish drawing style art.

You also want a style that lends itself to the theme and setting of your game. For example, you probably don’t want a cartoony and silly style for a horror game.

If you want you can pick a different style but for this I chose a simple flat basic shape style.

Adding the Images to the Game

Pack it Up

One of the ways to make your images more efficient for your game is to pack it into something called a sprite sheet. There is a free tool that will help with this called Texture Packer that works with FantomEngine.

You simply bring in the set of images that you want to turn into a sprite sheet and it puts them all together and allows you to export them into a single image. It then lets you save a file that describes that image so your game knows how to grab each one.

Fantom Engine only knows how to read the LibGDX and Sparrow data file formats for sprite sheets so make sure you pick one of those in the Texture Packer output file settings.

The Player

Let’s just start with the player and a single image and animation.

I created a simple set of 3 images to represent the player’s submarine. The only difference being the propeller so when we animate it, it will look like the propeller is spinning.

We are going to put it into our games ‘.data’ folder so we can load it later.

Loading the Images and Animation

Now that we have created an image, we need to load it into the game and associate it with the player.

What we are doing here is loading the image into memory, then creating an Animation object to replace our regular box that we had before. The Animation needs an image, it needs to know where in the image the animation starts, how big each frame is, and how many frames there are.

Everything else about the Fantom object remains the same so collision, movement, and everything else still works but now we have an animated little submarine instead of a box.

Using a Sprite Sheet

Now that we have a single image and animation working, we will see how to use a full sprite sheet.

I created an image for 3 different enemies, 2 different projectiles, the player, and a boss.

We then put all of the images into Texture Packer and publish the sprite sheet and the atlas mapping file. Remember to use the LibGDX or Sparrow formats for the atlas mapping file. Then we are going to put both into our games ‘.data’ folder.

Let’s start adding our new sprite atlas to the game and by getting our player’s animation from the new combined sprite sheet.

As you can see, this is not all that different from using an individual image for the animation, but it saves our game time and resources.

Fewer Enemy Types

Previously, we had all sorts of randomly sized enemies flying around the screen. Now since we have images or animations for 3 enemies, we will limit our enemy characters to being 1 of the 3 that we have images for. This is going to be a major overhaul of our enemy generator function.

First we need to pick our next enemy type at random. Then we will build the animation or regular image from our sprite sheet based on which enemy type it is.


The final 2 things that need to use our sprite atlas currently our the projectiles and the Boss.
Let’s start with projectiles.

And the Boss

Last but not least the Boss.

Now just by adding some images our game has a little underwater theme going on.

Xamarin TextChanged Event on Two Fields That Change Each Other

In the new version of the Cashflow Calculator I am making with Xamarin, I wanted to create the ability to input most of the expenses as both exact money values if you knew them or percentages of the monthly rent. This is a very common method of estimating repairs, vacancies, and property management fees.

I Change You, You Change Me

The idea was to have the percentage get set whenever the cash value was changed and the cash value get set whenever the percentage was changed.

But if you just create a normal TextChanged event on both of them, as soon as you make a change to one, it fires its TextChanged event which changes the other field and fires the other field’s TextChanged event which sets the one you are working on.

This does not work.

Stop Listening For a Sec

The solution to this is to disconnect the field you are about to change from its TextChanged listener and reconnect it when you are done changing it. We will use the event for calculating our rent percentage from the price of the property as an example.

async void CalculateRentCash(object sender, TextChangedEventArgs e)
    monthly_rent_cash.TextChanged -= CalculateRentPercent;
    await Task.Yield();
    var percent_val = GetFloat(monthly_rent_percent.Text);
    var new_rent_cash = GetFloat(property_value.Text) * (percent_val/100.0);
    monthly_rent_cash.Text = new_rent_cash.ToString();
    monthly_rent_cash.TextChanged += CalculateRentPercent;

The important parts of this function are the async in the function definition and the await Task.Yield() after removing CalculateRentPercent from the monthly_rent_cash.TextChanged listener.

Without the await Task.Yield() the function would tell the app that it needs to remove the listener but it would not do it right away. The task would be queued up but put on hold until the current task finished. It would then proceed through the function and the monthly_rent_cash field would still fire CalculateRentPercent.

With the await Task.Yield() line, the app pauses its execution of the current function and lets the Task we just created to remove the TextChanged listener finish before it continues.

If you are new to C# or Xamarin, remember that anytime you have a line that uses await in your function definition, you need async as part of the function description.

There may be other solutions to this problem, but this is the easiest one I came across so far. If you know a better solution, email me at travis at and let me know.

Found the solution on the Xamarin forums.

Xamarin Forms Entry

I am rewriting the Cashflow calculator app that I made last fall from Java to a Xamarin Forms app. If I ever decide to release to iOS this will make it much easier.

One of the workhorses for this app is the Entry form element. This is your standard input field from the keyboard.

There are two features that I want to talk about today. Setting the keyboard type and Completed and TextChanged events.

Setting the Keyboard

The Entry element lets you specify the keyboard type like you would expect. There is the Default – the standard keyboard on your device, Numeric – number only entry for things like calculators and money (the one I am using the most), also Telephone, Url, Email, and Chat.

If you have done any sort of UI programming before, you know that limiting the characters that your user can put in significantly reduces the number of potential errors.

XAML Example:

<Entry Keyboard="Numeric" />

The Completed Event

Whenever the user finishes filling out the field and hits the enter or next key, the Completed event gets fired. You can hook up your Entry field to call a function whenever this happens.

For me whenever the user changes one of the values in my form, I recalculate the cashflow value of the property they are putting in. This way they get instant feedback on what one value has to the overall calculation.

XAML Example:

<Entry Completed="CalculateCashflow" />

Where CalculateCashflow is a function in the XAML’s code behind file.

TextChanged Event

This allows you to call a function as soon as the text in a field gets changed, not just when you are done changing it. It might seem like an odd thing to have since we already have a Completed event, but I will give you an instance I plan on using it for.

A couple of my form fields will be connected and be different representations of the same value. For instance, when estimating cashflow of a property it is common to estimate the repair and vacancy costs as percents of the rent.

In this case I will have a pair of split fields that are related. A repair_cash Entry and a repair_percent Entry. Whenever one of them changes, I want the other one to be updated.

XAML Example:

<Entry x:Name="repair_cash" TextChanged="SetRepairPercent" />
<Entry x:Name="repair_percent" TextChanged="SetRepairCash" />

Where SetRepairPercent and SetRepairCash are functions in the XAML’s code behind file.

Note that the Completed event callback function takes a sender object and an EventArgs object while the TextChanged event callback function takes a sender object and a TextChangedEventArgs object.

Really enjoying Xamarin so far. Looking forward to releasing a couple apps with it this year.

Getting Started with Xamarin: Gathering Resources

One of the first steps with learning anything is finding available learning resources for it. So today I am just finding a list of various tutorials, blogs, podcasts, books, and video to use for self teaching.

Note: I did not thoroughly inspect any of the resources in this list. Just basic searches and brief scan of the site to come back to later if it looks like it might be useful.


Some people hate reading. If thats you, go ahead and skip this category. I for one love reading, though I definitely prefer good fiction to technical books.

A quick Amazon search will give you books like:

  1. Xamarin Mobile Application Development: Cross-Platform C# and Xamarin.Forms Fundamentals 1st ed. Edition
  2. Xamarin: Cross-Platform Mobile Application Development
  3. Mastering Xamarin.Forms

I would encourage you to go to amazon and search for Xamarin and see what comes up.



Written Tutorials

Video Tutorials/ Youtube

There’s More

There are other resources out there but this is just to get started with. Also some of these links are to another list of link.

After getting an understanding of the breadth and scope of what learning Xamarin will cover, I will be picking a more narrow topic and exploring it further.

Cross Platform Development

The last 2 years of writing has been primarily focused on making games with Monkey-X. While I will continue to make games, the focus of my writing will be changing a little.

Last fall as I was getting ready to try to release games to mobile, I built my first Android app. It is a little rental property cashflow estimation calculator and I had a lot of fun making it and figuring out some of the Android development basics. But I didn’t write about it because the focus of this blog was about making games.

This is going to change.

New Focus

I am a web developer by day, and one of the reasons I like the web and web development is because you can write an application one time and as long as someone has a web browser they can use it. Not only that, but most of the logic can be kept on your server so you are really in charge of the environment the code is hosted in. Client heavy web apps using various Javascript libraries have changed some of this but for the most part it is true. And it has gotten even better as web browsers are converging better on standards.

One of my strong dislikes is having to do the same work twice. If I can find a way to do it only once I will. If I can build a system that does it for me so I never have to do it again I will.

This is one of the reasons I chose Monkey-X as I started making games. It deploys cross platform. Whether you want to put it on the web, on a phone, or on the desktop you can write your game logic in a single code base with usually some small tweaks per platform. The basic game logic remains the same.

Starting this month I will be adjusting the overall focus of the blog to cross platform development in general, no longer just games. The primary focus will be on the Xamarin platform.


Xamarin is a company and the name of their framework or toolset. It is a .NET based framework for allowing you to write apps that share as much code as possible between Windows 10, iOS, and Android.

Microsoft bought Xamarin last year (2016) and at time of this writing it is free for solo developers to get started with them.

The reason I am choosing it is the same reason I chose Monkey-X. Giving me the ability to write something once and then use that multiple times is exactly what I am looking for. And I want to create apps that work well on the phone. Their are some hybrid web solutions using things like Cordova where you write your app in Javascript, HTML, CSS and build it for the phone but that is not what I am looking for right now.

Bonus, Xamarin has a platform for making games with it called CocosSharp (part of the Cocos2D family) that I may utilize.

So look for coming updates on making cross platform apps and games.