API Controllers (More Stuff!)

My last post demonstrated a few details that I learned about API controllers.  There was one other detail I forgot to mention.  Serialization.  I ran into an issue involving an API controller that worked OK, and then it quit sending JSON data completely.  I traced it down to the fact that I moved an object to another project (containing most of my business layer code) and I also added some methods to the object.  I discovered that I needed to add the [Serializable] attribute to the objects that I used to pass JSON data.  Like this:

[Serializable]
public class PersonnelType
{
    public string First;
    public string Last;
}


[Serializable]
public class TestType
{
    public int Number;
}

Also, the first sample I used in my previous article used a GET API controller and I named it “PostOne”.  That was a typo on my part, but it does demonstrate that the name of the method doesn’t really matter.

Working With Entity Framework

OK, this week I’m going to try to build something a bit more complex.  I’m going to add an Entity Framework database to the mix and show how you can shuttle data between an AJAX call and an MVC API controller.

First, we need a blank MVC4 project.  Next, add a controller using the technique I demonstrated in the previous article.  Name it HomeController.cs, then add a view to it.  Just use the default name.  Now you can run your program and you should get a basic web page.  Now create a scripts folder and add a personnel.js text file to it.  Put this code in your javascript file:

$(document).ready(function() {
 $.ajax({
  type: “GET“,
  url: “api/Personnel/ReadData“,
  contentType: “json“,
  success: function(personnelData) {
   data = jQuery.parseJSON(personnelData);
   $(‘#resultText‘).val(data[0].first + ‘ ‘ + data[0].last);
  },
  error: function(error) {
   alert(error.responseText);
  }
 });

});

Also, download and add JQuery 2 into your scripts directory.  Then modify your view.cshtml file to this:

<!doctype html>
<html>
    <head>
        <title></title>
        <script src=”~/scripts/jquery-2.1.0.js“></script>
        <script src=”~/scripts/Personnel.js“></script>
    </head>
    <body>
        <div>Test Page</div><br />
        <div><input type=”textid=”resultTextvalue=”” /></div>
    </body>
</html>

Now add another controller.  This time create an API controller and name it PersonnelController.cs.  Leave it blank for now. 

The Database Project

Create a new project in your solution.  Just create a class project and name it “Database” for now.  Right click on your new project and select “add -> New Item”, then select “Data” on the left treeview control and an “ADO.NET Entity Data Model” to your project.  Go through the standard steps of creating a connection and adding a table.  I’m using the person table that I created in an earlier blog box.  I’m also connecting to a SQL database, but you can use whatever database you’re comfortable with.  Once you have added the table and saved your edmx stuff, then you’ll need to copy your app.config settings to the web.config file of your other project.  You’ll have to add all of the config stuff from the app.config file to your web.config file.

Let’s add a PersonData class to the database project and put this code in it:

namespace Database
{
    public class PersonData
    {
        public List<person> ReadData()
        {
            using (var db = new sampledataEntities())
            {
                return (from p in db.people select p).ToList();
            }
        }
    }
}

The purpose of this code is to provide a business object to handle the querying of data and maybe some business computations.  I’m just going to grab all the records in the table and return them as a list. 

Now you need to add the database project to your MVC project.  You can right-click on the References directory in your MVC project and “Add Reference”.  Then select “Projects” on the left and check the database project in the list (it should be the only one there).  Now you can add a “using Database” to your API controller (PersonnelController.cs file) and reference anything in the database project that is public.

Now add a method to your API controller (in the PersonnelController.cs file) using this code:

[HttpGet]
public string ReadData()
{
    PersonData p = new PersonData();
    List<person> data = p.ReadData();

    var json = JsonConvert.SerializeObject(data);
    return json;
}

 
You’ll have to add two usings to the top to make this code compile:

using Database;
using Newtonsoft.Json;

If your code compiles, then run it and see what happens.  You should see the name of one person from your database (assuming you have records in your person table).

You can troubleshoot this app by first putting a cursor in your controller “ReadData()” method and running the app.  This should get called when the JQuery AJAX call is made.  If it doesn’t get there, then you have a problem with your html or your javascript.  It does get there, then it’s time to step through the data read and see if that works.  If you make it to the serializeObject line, then your data should be in the list called “data” (put your cursor of this variable and you can see how many items there are in the list).  Next, you should be able to get through the C# API controller and the program resumes execution at the JQuery AJAX call under the “success” function.  There you can put a breakpoint on the deserializing of the data and you should be able to see a list of items that match the format of the table that was passed from the C# code.  I peeled off the first record (record zero) and used the first and last name.  The names are not trimmed, but this is just for demonstration purposes.

Extending the Data Sent

Let’s pretend we are going to build a CRUD interface now and we need to have an “Edit” and a “Delete” Boolean variable to handle human interaction between the html interface and the C# controller.  Also, let’s assume that some sort of framework like AngularJS is used (though I’m not going to get into that in this article) and it becomes more convenient to have Booleans for each record to track what the user is doing.

So how can we add these in a manner that is easy to troubleshoot and understand?  We could just add the fields to the person table and ignore the data in the database.  That would be a waste of space on the server and we don’t really want to actually store this data because it just tells the controller that the user wants to modify or delete a record (I’m purposely leaving out the “add” operation, just to keep this short, but in reality, you’ll need that function as well). 

There are probably a dozen other “not so cool” methods to get around this problem, such as modifying the JSon text as it is passed between the JQuery and C# controller.  But the method I’m going to demonstrate is easy and clean.  First, add a class to your Database project and name it “PersonExtended.cs”.  Inside this class, you can “append” to the existing person class that is defined in the “person.cs” file (auto-generated by the EF-6 framework when you added the table to your edmx file).  If you open up the “person.cs” file you’ll see that the person class is actually a “partial” class.  Which means that you can declare another “partial” person class anywhere else in your project.  So that’s what I’m going to do.  Here’s the code I used inside the PersonExtended.cs file:

namespace Database
{
    public partial class person
    {
        public bool Edit { get; set; }
        public bool Delete { get; set; }
    }
}


What this code does is add two Boolean properties to the complete class.  These properties are not used by EF, but they can be used by your JQuery, or HTML to exchange user interactions with the API controller.  Once you add the code above, re-compile your project and put a breakpoint in your AJAX return call and examine a record of the data that arrives.  You’ll see the two extra fields inside that data.  You can initialize these variables in the query if you’d like, or you can initialize them in the person object.  Like this:

namespace Database
{
    public partial class person
    {
        public bool Edit { get; set; }
        public bool Delete { get; set; }

        public person() : base()
        {
            Edit = false;
            Delete = false;
        }
    }
}

To confirm these results, run the program with Edit and Delete set to false and check what arrives at the “success” point of your AJAX call.  Then change Edit to true in your initialization code and check what arrives a “success” this time.  You’ll see the values you expect. 

The reason that EF uses partial classes is so you can extend the class to include additional methods and properties without modifying the auto-generated files under the edmx file.  If you were forced to modify the generated class directly, then you would need to modify the T4 script file to insert your changes into the class generation (T4 script files end with tt file types and can be modified to change the way EF generates code). 

You can download the entire project here: MVC4 EF Test Project.

Summary

This project shows how to create an MVC API controller project using JQuery to communicate between a browser and a C# controller.  I also demonstrated how to setup another project to contain an Entity Framework 6 database.  I further showed how to include that project in your MVC project and extend an ORM table object in such a way that it will remain intact if you update your EF edmx file.

I’m currently working on a couple of projects for this blog.  One project includes a sample of AngularJS and the other project has unit testing for API controllers.  These projects will add onto what has been learned in this lesson and the previous lesson.


 

 

API Controllers

Introduction

For those who follow my blog, you’ll remember that I have been working on a project using the Visual Studio MVC 4 framework.  I spent a considerable amount of time researching how the pieces of this framework fits together and I’ve discovered some nuances.  Many of these tricks I learned after starting the real project and attempt to get some real (as in, not research) work done.  So this post will cover the API Controller.


Getting Started

To begin this test example, we’ll need a new MVC 4 empty project.  You can refer to my previous post on how to create this.  Once you have an empty project, create an empty MVC controller in the “Controllers” directory (right-click on the “Controllers” directory and select “Add -> Controller”, then name it “HomeController” (make sure it’s an empty MVC controller type).  Then right-click on the View() method and “add view”.  Just leave it named “Index”.

OK, now we’re going to delete everything in the Index.cshtml file and make it look like this (you can just paste this into it):

<!doctype html>
<html>
  <head>
    <title></title>
    <script src=”~/scripts/jquery-2.0.3.js“></script>
    <script src=”~/scripts/homescript.js“></script>
  </head>
  <body>
      <div>
        <input type=”submitvalue=”Test 1id=”TestController1“/><br/>
        <input type=”submitvalue=”Test 2id=”TestController2“/><br/>
        <input type=”submitvalue=”Test 3id=”TestController3“/><br/>
        <input type=”submitvalue=”Test 4id=”TestController4“/><br/>
      </div>
  </body>
</html>



Now you’ll need a javascript file and you’ll need JQuery.  Download the JQuery JS file from JQuery.com.  I’m using version 2 for this demo, I’m pretty sure you can use either version.  We’re only going to use it for the AJAX capabilities.  Create a “scripts” directory and copy the JQuery.js file into that directory and also create an empty js file called “homescript.js” in the “scripts” directory:


Now, our JS file will start with this code:

$(document).ready(function() {

$(“#TestController1“).click(function() {

});

$(“#TestController2“).click(function() {

});

$(“#TestController3“).click(function() {

});

$(“#TestController4“).click(function() {

});

});

Next, we’ll need to add an API Controller, then we can get started.  Right-click on the “Controllers” directory and select “Add -> Controller”, then select an empty API Controller type.  Name it “DemoController”.  I’ll be adding two classes that I’ll just use as containers of information to pass back and forth using JSON.  Your API controller should look like this (I left out the usings for clarity):

namespace MvcApiControllerBlogSample.Controllers
{
    public class PersonnelType
    {
        public string First;
        public string Last;
    }

    public class TestType
    {
        public int Number;
    }

    public class DemoController : ApiController
    {

    }

}

Now it’s time to get down to business.  My first test will be very simple and should work out of the box.  First, I’m going to add some code to the homescript.js file (inside the first click function:

$(“#TestController1“).click(function() {
    $.ajax({
        type: “GET“,
        url: “api/Demo?account=TEST“,
        success: function() {

        },
        error: function(error) {
            alert(error.responseText);
        }
    });

});

Next, I’ll add a small method in the API Controller code:

public class DemoController : ApiController
{
    [HttpGet]
    public void PostOne(string account)
    {
        string result = account;
    }
}

Put a breakpoint on the line in your controller where the string “result” is assigned “account”.  Then run the application and click the first button.  You should see your program run to the breakpoint.  Now examine the text inside “account”.  It should be “TEST”.

When referring to a controller, you use the first part of the controller name (i.e. this one is called “DemoController”, but we call it “Demo” in the URL string above).  You also need to use “api” in the path name.  If you open the WebApiConfig.cs file, you’ll see a route that specifies this route:

api/{controller}/{id}

Notice the first part of the path is “api” with no braces around it.  That specifies that the first part of the path must start the word “api”.  The second parameter is the controller name, and the third parameter is an id (used by a post operation), which could also be setup as a URL parameter like I did in the above example (for post operations, a get operation always uses the URL convention like that listed above).

So now we constructed a simple “get” operation involving a parameter.  You can add more parameters just like you would add to a URL anchor link (separating with and symbols).  

Now let’s try our hand at a POST operation.  Add this code to your second controller in the homescript.js file:

$(“#TestController2“).click(function() {
    var temp = { First: ‘Joe‘, Last: ‘Smith‘ };

    $.ajax({
type: “POST“,
  url: “api/Demo/SavePersonnel/test“,
  contentType: “application/json“,
  data: JSON.stringify(temp),
success: function() {

},
error: function(error) {
            alert(error.responseText);
}
    });
});

And in the API controller:

public class DemoController : ApiController
{
    [HttpGet]
    public void PostOne(string account)
    {
        string result = account;
    }

    [HttpPost]
    [ActionName(“SavePersonnel“)]
    public HttpResponseMessage ThisMethodNameDoesntMatter(string id, PersonnelType record)
    {
        return Request.CreateResponse(HttpStatusCode.OK, record);
    }

}

The first thing you might notice is the “ActionName” attribute added to the “ThisMethodNameDoesntMatter” method.  This will be used to specify that this post action will be executed by the ajax call in the javascript when specifically cited (see the “SavePersonnel” inside the “URL” specification in the javascript above).  If you execute this code as it is, it will fail.  That’s because we need to add a route to the WebApiConfig.cs file, which should now look like this:

namespace MvcApiControllerBlogSample
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: “DefaultApi“,
                routeTemplate: “api/{controller}/{id}“,
                defaults: new { id = RouteParameter.Optional }
            );

            // Controllers with Actions
            // To handle routes like `/api/VTRouting/route`
            config.Routes.MapHttpRoute(
                name: “ControllerAndAction“,
                routeTemplate: “api/{controller}/{action}/{id}
            );
        }
    }

}

Now you can run this application and click on the second button.  If you put a breakpoint inside the “ThisMethodNameDoesntMatter” method, you’ll see that the program stops at that point and the record will contain the first and last name hard-coded in the javascript.  For a real-world application, you can feed your text fields into these javascript variables before calling the ajax command.  You’ll also notice that the id has been filled in with “test”.  This is an optional configuration.  You do not have to setup your controller to accept an id or any url parameters when a post is issued.  I’ll show you that next.

On to the third example.  Let’s add code to the javascript file for “TestController3”:

$(“#TestController3“).click(function() {
    var temp = { Number: ‘5‘ };

    $.ajax({
type: “POST“,
url: “api/Demo/SaveTestType/Ignore“,
contentType: “application/json“,
data: JSON.stringify(temp),
success: function() {

},
error: function(error) {
           alert(error.responseText);
}
    });
});

And for the controller add this method after the last one:

[HttpPost]
[ActionName(“SaveTestType“)]
public HttpResponseMessage doesntmatter(TestType testrec)
{
    return Request.CreateResponse(HttpStatusCode.OK, testrec);

}

Now run this program with a breakpoint inside the “doesntmatter” method and you’ll see that “testrec” will contain the number “5”.  Also, you’ll notice that there is no id passed, but you’ll still need to specify an id (I called it “Ignore”) in the javascript.  This is to ensure a proper pattern match with the routing that has been defined in the WebApiConfig.cs file.  One last example, to demonstrate that you can have two controller methods with the same parameters but called from different ajax calls.  Create this code for your “TestController4” javascript:

$(“#TestController4“).click(function() {
    var temp = { Number: ‘9‘ };

    $.ajax({
type: “POST“,
url: “api/Demo/SaveTestType2/Ignore“,
contentType: “application/json”,
data: JSON.stringify(temp),
success: function() {

},
error: function(error) {
           alert(error.responseText);
}
    });
});

And finally for the controller:

[HttpPost]
[ActionName(“SaveTestType2“)]
public HttpResponseMessage doesntmatter2(TestType testrec)
{
    return Request.CreateResponse(HttpStatusCode.OK, testrec);

}

Now, if you put a breakpoint inside each C# controller method, you can click on each button (Test 1 through Test 4) and see your program stop at the correct controller.  You can also see that the “doesntmatter2” method contains a “9” instead of a “5”.  So we know that the correct parameter is being passed.

One other thing to notice (if you haven’t noticed already), is that the method names in the controller don’t mean anything.  You can give them descriptive names for your own identifying purposes.  The name in the “ActionName” attribute is what controls which method is called from the post.  Without this attribute, you will need to create post methods with different parameters so the controller knows which one to match.  Also, I’m betting it’s possible to manipulate the routing to set up a pattern where you don’t need the “Ignore” parameter in your ajax call.  I have yet to dig deeper into the routes.  When I get that nailed down, I’ll do another blog post and report what I’ve discovered.  There are also other types of controllers, like a DELETE and a PUT controller, which I did not include in this blog post.

Summary

The four sample API controllers that I have presented are a test project that I set up to reverse engineer what I needed in order to make my application run.  Sometimes you have to create a small test with just the bare essentials to see how things interact with each other.  Otherwise, you can waste a lot of time trying to get something simple to work because it is buried in a lot of other program clutter (which could be conflicting with your code).  Now that I’ve figured out the very basics, I’ll keep this little program handy for further testing.  I hope this helps you get rolling without going through all the pain I did when I attempted to make this work.









 

MVC 4 API controllers

If you’ve read my previous posts you’ll know that I’m in the research phase of deciding which framework to use with my company’s new project.  At this point I’m leaning toward MVC 4 with a few add ons: AngularJS, Bootstrap, Less, EF-6 and some others.  MVC is starting to grow on me and I wanted to show how to pass data back and forth between jquery (using AJAX) and an API controller (just to get warmed up).

Let’s Get Started
 
To get this started I created a blank MVC 4 application and a controller called “HomeController.cs” in the “Controllers” directory.  Once this file was created, I opened the file and it already contained this code (automagically):


I apologize for using images for the code in this post, I’ll include a link to the whole project at the end so you can download the source code.  Or you can just follow along with my descriptions and create this project on your own (giving you the chance to learn the tricks as you do it).

If you right click on the “View” method, you’ll see an option called “Add View…”.  Select that and a new dialog box will appear to create a view.  Leave the view name “Index” and just click the “Add” button.  A new cshtml file will be created in the “Views” directory.  This is where you’ll put some html code for the startup page.  Before modifying that file, let’s create a script directory and a javascript file.

Right-click on the project and click “Add -> Add New Folder”.  Name the folder “scripts”.  Then right-click on the scripts folder and select “Add -> New Item”.  Then navigate to create a js file:


You can name the file anything you like.  I named mine “javastuff.js”.

Next, you’ll need JQuery.  I would recommend going to the JQuery website and downloading the latest version available.  The reason I like to do it this way is because it only needs one file.  If you use the NuGet facility, you’ll probably get a bunch of stuff you don’t need.  

Go to “jquery.com” and click on the download button.  I chose version 2.0.3 for this example.  Once you have downloaded the js file that is needed for jquery, drag it into the scripts folder.

Now it’s time to include the javascript into the html index.cshtml file created earlier.  First double-click on the index.cshtml file to edit the contents.  Then drag each js file into the code just above the <h2> tags.  Like this:


Of course, you can also hand type the script tags in if you like.  Make sure the jquery reference is on top.  You should be able to run your application and it will do pretty much nothing at this time (except print the text “Index” at the top of the browser).

All right, back to the C# stuff.  Create another controller in the “Controllers” directory, but this time make sure it is an empty API Controller (Right-click on the “Controllers” directory and select “Add -> Controller…”).  Name it “PersonnelController”:


One more file to create.  Right-click on the “Models” directory and create a C# file.  Name it “PersonnelModel.cs”.  Your models should contain the code that queries your database, but I’m going to skip using a database in this sample to keep it as simple as possible.  What I’m going to do is create a class that will represent one database record.  Then I’ll use lists of this class to represent data queried from the database.  The “PersonnelModel.cs” file should look like this:


Now we can use a list of this class inside of the api controller file (open your “PersonnelController.cs” file and enter this code):


I had to add a using statement to bring in the model for this example.  This “Get()” API controller will communicate with the JQuery that we are about to create.  Edit the “javastuff.js” file and make an ajax call like this:


Now you can put a breakpoint on the line where the variable temp is assigned to data.  When you run your application you’ll break at that point and you can see that data contains a list of records that match what was added to result in the C# controller above:



Here’s the source code for the entire project:
MVC Blog Post Controller Demo Project (Zip File)

In my next post I’m going to show how to add AngularJS to the project and connect a grid control to the API Controller and automatically display rows of data in the index.cshtml file.

 

The Game (Part 4)

I have implemented the mask and view capabilities.  I’m calling this version 2.  Here’s a sample screenshot of how it looks in action:

The first thing you’ll notice about this map is that unexplored areas are colored in black.  These will uncover as allied units are moved around the map.  The darker areas are areas that are not visible but have been explored.  These areas could have enemy units hiding there.  Every time an allied unit is moved the view map is recomputed in JavaScript (and a duplicate array is maintained in C# in case the player refreshes their browser).  The unexplored areas are initialized at the beginning of the game and are cleared as units are moved.  Both the JavaScript and C# code have functions/methods to deal with this mask.  The difference is that the JavaScript doesn’t maintain an array of cells that are explored because they are just set to hide the mask whenever a unit passes by and they are never set back during the game.
The two masks are identical and use the same image to paint over top of the entire board.  I set the opacity to 0.3 for the view hex pictures so the player can see the terrain under it.  I also manually set the display value of each enemy unit to match the value of the view mask.
Here’s the code: Battlefield One Code V2
You can go directly to my website to play the game as is: (temporarily down).
I’ve played the game a few times and it is a bit more challenging than the first version without the masks.  I think my next enhancement will be adding a variety of different unit types.  I might have to enlarge the playing board to allow more playing pieces.
Stay tuned…
Note: I have recently upgraded my website to use MVC4 and .NET 4.5. I have refactored my code to make the game work on MVC4.  Click here to try it out.

 

The Game (Part 3)

So I’m working on the visibility and mask of the game I wrote in the last two blog posts.  Here’s a problem that I ran into right away and it involves not paying attention to detail.  What I’m referring to here is the hex board layout.  If you look at the documentation:

Battle Field One Specifications

You’ll see a page titled “Unit Movement” and at the bottom is the definition for finding the surrounding 6 cells.  What I didn’t verify is that my game has the cells shifted the exact same way.  You see, there are two different ways a hex-board can be drawn (actually there are rotated arrangements too, but I’m going to ignore that).  If the first column is started lower than the second column , then it follows my specification.  However, if you look at the actual game, you’ll see that I drew the map starting with the first column higher than the second column.

Old Documentation:

 
 
Game:



So that means that the game was designed wrong to begin with.  Now the choice is to change the documentation and fix the calculations inside the game or change the game board and leave everything else clean.

I’m choosing to change the specification for the game and I’m going to have to fix the even/odd test inside version 1 to make sure I am searching the right surrounding cells.  If you’re just downloading the specification, then you’ll noticed that it’s already been corrected.

These things happen and it’s fortunate that I was able to catch this before getting any deeper into the game code. 

 

Designing a Game

It’s been a while since I posted something new.  That’s due to the fact that I’ve been working on a small game.  My intent was to design and build a fully-functional game to demonstrate AJAX, C# and SVG.  The trick to completing something like this is to make sure the scope is small enough that it can be completed in a short time.  I chose a turn-based game to keep the code simple.  This game is a basic Axis-vs-Allies type board game using a hex board layout.  I chose the hex layout to make the a game a bit more challenging and the hex board has 6 directions instead of 4 primary and 4 diagonals. 

I named the game “Battlefield One.”  Not overly creative, just a temporary name.  Here’s the basic design document:

Battlefield One

Feel free to download and thumb through the details.  There’s mention of two types of units in the game, but I trimmed it down to just infantry.  No tanks at this time.  That’s easy to add though, since there is an object called “Unit” that I used to contain the defense, offense, movement, etc.  This object can easily be expanded to represent other units.

Follow this link to play the game:

Battlefield One Game

Here’s a screenshot of part of the game board:


The first task I performed was rendering the playing board.  There are a lot of decisions that can be made here, but I chose to render the beehive grid with lines on top of a background picture.  The trick was getting the picture to line up.  So I wrote some SVG code to paint one hexagon and repeated a grid of these shapes.  As I’ve mentioned in a previous post, this board is really no more than an offset checkerboard, where every other column is offset by 1/2 the height of the previous cell.  Once I had a grid printed on the screen I had to make sure my browser was set to 100% (yup, I forgot that step and had to redo this next step).  Next I took a snapshot of the entire screen and put it inside Photoshop.  You can use any paint program you like, I’m comfortable with Photoshop and this problem just screamed “layers!” to me.  After I put the screenshot on a layer in Photoshop, I filled in the green areas for all the cells except the four cities.  I made up an easy pattern of city building roofs and roads and then I just copied to all 4 city locations.  Then I put my background into the SVG code before rendering the beehive cells.

That pretty much completed the background picture.  In future versions of this game, I hope to add roads and make the movement factor double when a unit uses a road.  But for now, it’s just a green field.

Next I defined a unit and worked out the rendering portion.  For units, the center icon is just a PNG file that I created.  The unit type will define which PNG file will be rendered in the center of the unit box.  The four corners are numbers representing the defense, offense, movement and fire range.  The top center number is a number that I added for troubleshooting purposes.  I left it in for now.  It represents the unique unit number.  This was a snafu that I ran into when I was debugging a deleted unit problem.

The unit objects are grouped into a list:

private List<Unit> AllUnits = new List<Unit>();

The only issue with using a list is that deleting a unit causes the list to compress and the indexes to each item is now changed (at least for units after the deleted unit).  So I inserted a variable in the Unit class called “Number” which represents the unique unit number:

public class Unit
{
   public int Number { get; private set; }
   public int Defense { get; set; }
   public int Offense { get; private set; }
   public int Movement { get; private set; }
   public int Range { get; private set; }
   public int UnitType { get; private set; }
   public int X { get; set; }
   public int Y { get; set; }
   public NATIONALITY Nationality { get; private set; }
   public UNITCOMMAND Command { get; set; } // used by enemy units only
   public int DestX; // used by enemy units only
   public int DestY; // used by enemy units only
}

I created a couple enum’s for NATIONALITY and UNITCOMMAND.  There’s nothing fancy going on here, it’s just my way of keeping track of what is set.  It also helps in the “if” statements to see what is being compared.  The enums are as follows:

public enum NATIONALITY { Allied, German };
public enum UNITCOMMAND { None, Wait, Destination, Defend };

At the moment, I’m only using the “None” and “Destination” status of the UNITCOMMAND variable.  I initialize the Unit class to a Command of “None” and then I change the command to “Destination” once I have set a unit DestX and DestY for enemy units. 

The Game AI

I managed to crank out enough C# and JavaScript to allow the allied units to move around the map board.  The computer player was still dead (i.e. not moving or attacking).  I decided to work on the enemy move phase of the game.  I kept the game AI as simple as possible.  Basically, the enemy will count the total number of units, divide by 4 (which is the number of cities on this map), then set the destination for each group to a different city. 

That was all I setup initially.  I didn’t bother with attacking or detecting any end game results.  The movement of units included a method to force move restrictions on the desired movement (I called this the SnapTo method).  This method will make sure the unit only travels one unit from its current location, it can’t overlap another unit and they can’t go off the edges of the map. 

There was a problem that I ran into.  My algorithm computed which units would move and did the SnapTo operation inside the C# code, then sent it back through an AJAX return to the calling JavaScript that performed the actual move.  The problem is that the order that the units are moved can determine if there is another unit in the square that will be moved to.  So I decided to just send the data to the JavaScript in no particular order, then I looped through a queue of move orders.  If the unit was blocked, I swapped that unit to the back of the queue and then continued moving other units.  After a few attempts to move a unit and passing it over, eventually the space it was destined to move into will be empty (vacated by another unit just moved). 

Next, I did the enemy attack phase.  I decided that if the enemy bumped into an allied unit, it would just attack during the attack phase.  So I wrote a method to search for allied units that are one hex away from a German unit, then send both unit numbers and the battle result back to the JavaScript from the calling AJAX. 

Last, I completed the code for the allied attack phase.  The JavaScript that triggers this sends and AJAX command to the C# code which does the battle calculation, sending back the results.  The return JavaScript function deletes the unit object from the SVG code.

Game Goals

There are 2 possible goals that can be achieved to win or lose the game.  The first goal is to capture all 4 cities.  The German or Allied side needs to capture all 4 to win the game.  If either side has only 3 units or less, then that goal is not achievable.  The second goal is to destroy all the enemy units (or the enemy must destroy all the allied units).  When one team or the other destroys the other’s units, the game is won.

The game can become a draw due to the fact that the enemy AI splits groups of units for each city.  Once the group of units reaches the destination city, they just sit there waiting for something to happen.  Unfortunately, it doesn’t do the enemy much good to have 3 or 4 units sitting on one city while the allied player sits on another city with one remaining unit.  The enemy will not seek out and destroy the allied unit.  This is a weakness that I’ll be fixing next.

Game Code

I’m going to spend some time and refactor the code to clean up all the scraps I left on the floor of the sausage factory.  Once I do that, I’ll post the code for anybody to download and examine.  Though I haven’t completely tested this on an iPad, I have done some preliminary testing and it works pretty good.  The total amount of code for this game is about 860 lines of JavaScript and 730 lines of C# code.  Just a little something I do on a weekend.

Update 6/12/2013:

I performed a few bug fixes while refactoring the code.  Now that I have been able to play the game several times in a row without a hiccup, I feel confident that it’s pretty close to bug free.

Update 6/13/2013:

Here’s the entire project for download: BattleField One Project.