Customizing the EF Entity Templates

The nice thing about Entity Framework is that anytime you are using one of the entity template generation capabilities, they are pretty easily customizable. This, of course, means that you are NOT using the pure code-first API most likely (however, to an existing database defines a T4 template). In this blog post, we’re going to quickly update the T4 template to change the default rendering:

using System;
using System.Collections.Generic;
    
public partial class State_LKP
{
    public int StateID { get; set; }
    public string StateCode { get; set; }
    public string StateName { get; set; }
}

To add additional information that the application can later use for metadata purposes, such as the following:

using System;
using System.Collections.Generic;
    
public partial class State_LKP
{
    public const string StateID_Name = "StateID";
    public int StateID { get; set; }
    
    public const int StateCode_MAX_LENGTH = 10;		
    public const string StateCode_Name = "StateCode";
    public string StateCode { get; set; }
    
    public const int StateName_MAX_LENGTH = 50;
    public const string StateName_Name = "StateName";
    public string StateName { get; set; }
}

Notice that each column has a constant defining the name, as well as a constant defining it’s max length defined in the database (if a string).

To do this, we need to open up the .tt file that generates each of the entities. In my version, around line 66, we have the following snippet.

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    foreach (var edmProperty in simpleProperties)
    {
#>
    <#=codeStringGenerator.Property(edmProperty)#>
<#
    }
}

Notice that this snippet loops through each of the simple properties (the properties defined one for each column) and renders out a definition (note codeStringGenerator is a class defined in the T4 template that defines all of the markup. I didn’t choose to modify that here). To add the name constants and the max length constants, the updated samples were changed to the following code sample. Comments below indicate the changes made.

var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
    //edmProperty of type EdmProperty
    foreach (var edmProperty in simpleProperties)
    {
        //Check max length - if any max length, then write out a constant
	 if(edmProperty.MaxLength.HasValue)
                {
                        #>
 
                        public const int <#= edmProperty.Name #>_MAX_LENGTH = 
                            <#= edmProperty.MaxLength.Value #>;
 
                        <#
                }	


         public const string <#= edmProperty.Name #>_Name = 
               "<#= edmProperty.Name #>";

    <#=codeStringGenerator.Property(edmProperty)#>
    <#
    }
}

Here we add constants to the output of the properties and everything generates great. You may say it would be better to use attributes; that is possible as well, but for that I’d recommend editing the CodeStringGenerator class (in the T4 template) and update the Property method directly instead.

The T4 template is available here: http://pastebin.com/42NiuwDE

Discussing ASP.NET MVC Model Binding With Hidden Data

If you have taken over an MVC application, you may have come across a dilemma like the following. Notice that in a view, within a form, you’ll see a group of hidden fields mixed in with a form like the following.

Html.HiddenFor(i => i.ContactID)
Html.HiddenFor(i => i.ContactTypeID)
Html.HiddenFor(i => i.ContactDescription)
Html.HiddenFor(i => i.ContactTypeDescription)
Html.HiddenFor(i => i.OrganizationID)

Html.LabelFor(i => i.OrganizationName, new { @class = "control-label" }) Html.TextBoxFor(i => i.OrganizationName, new { @class = "form-control" })
@* and so on *@

My example had five hidden fields, but I’ve seen a lot more. These fields are not useful to the form per se; the user doesn’t enter them. However, the information is important to the records about to be updated in the database, and thus are included in the form as hidden fields for that reason. However, another reason is it acts as a quasi-ViewState mechanism that makes it very easy to replenish the following model:

public class ContactInfoModel
{
    public int? ContactID { get; set; }

    public int? ContactTypeID { get; set; }

    public string ContactDescription { get; set; }

    public string ContactTypeDescription { get; set; }

    public int? OrganizationID { get; set; }

    public string OrganizationName { get; set; }

    /* and so on */
}

[HttpPost]
public ActionResult Contact(ContactInfoModel model)
{
 ...
}

While OrganizationName and the other unlisted properties came from the form, the first five properties (and potentially more) are stored in the hidden field. The hidden field makes it nice and easy to replenish this model, and than allow the developer to use the parameters in the post action. MVC does a very nice job posting the values back to the server and populating these properties.

However, notice I said before, that this was a ViewState-like solution? It’s not quite within the model of ViewState because all of the parameters are embedded in the form in clear text. In most systems, the user is required to login before they can ever get to a page that contains this type of information. Either way, the users have the tools (IE developer tools, Firebug) to inspect and change the values in the hidden fields if they so desired. That is where the danger can lie.

Here’s the other side of the conundrum: if we don’t reload the parameters, what do we do? If we didn’t include the hidden fields, the first five parameters are not loaded from the client and thus the model is partially replenished. In most cases, these pieces of information might not be needed anyway (with the exception of OrganizationID in our scenario).

The application can certainly requery the information it needs, but then the information gets reloaded on every postback, which can get more expensive. The application could also use Session to store the information fields too.

I’m not saying “NEVER use hidden fields”, but I’m debating the value of a large number of hidden fields for replenishing the model. I probably fit within the category of storing any relative information in Session or requerying the information from the database, depending on how much information we are talking about. What is your thoughts or preference? Using hidden fields, session, database?

Using Interfaces for ASP.NET MVC Model Binding

Sometimes you may want to support view reuse, where a partial view displays a portion of the application in a reusable fashion. Suppose you had the following entity which has a bunch of properties.

public class Customer
{
   public int CustomerID { get; set; }

   public string FirstName { get; set; }

   public string LastName { get; set; }

   public string AccountNumber { get; set; }

   .
   .
}

Suppose you wanted to use a PartialView because it was an AJAX widget with a JavaScript initialization script, and defining a reusable control made it really easy to support this. MVC defines a strongly typed model reference, so does that mean we have to bind the model directly to Customer, or define a custom type for an editor template?

We actually can use interfaces by adding the following:

public interface IAccountEntity
{
   string AccountNumber { get; set; }
}

We can define this in a partial view:

@model IAccountEntity

@Html.TextBoxFor(i => i.AccountNumber)

   $(function() {
      /* Registration Script */
   });

And then use it in our EditCustomer view, as a partial with the existing model:

@Html.Partial("EditAccountNumber", Model)

Since Model (of type Customer) is also IAccountEntity, this translates just fine with MVC. It works just as well when you use hierarchies too. For instance, Customer implements IAccountEntity, but what if we had a CustomerModel class above Customer like:

CustomerModel
     Customer : IAccountEntity
        AccountNumber

If EditCustomer view looks like the following:

@model CustomerModel
.
.

<div class="form-group">
   <label class="col-md-2 control-label">First Name</label>
   <div class="col-md-10">
       @Html.TextBoxFor(Function(i) i.Customer.FirstName)
   </div>
</div>
<div class="form-group">
   <label class="col-md-2 control-label">Last Name</label>
   <div class="col-md-10">
       @Html.TextBoxFor(Function(i) i.Customer.LastName)
   </div>
</div>
<div class="form-group">
   <label class="col-md-2 control-label">AccountNumber</label>
   <div class="col-md-10">
       @Html.Partial("EditAccountNumber", Model)
   </div>
</div>

Notice how the model is passed in directly; this won’t work for our scenario, because the EditAccountNumber expects an IAccountEntity, and requires that the partial be passed in this way:

@Html.Partial("EditAccountNumber", Model.Customer)

However, that doesn’t work for our needs, if our controller has a post operation of the following:

[HttpPost]
ActionResult Edit(CustomerModel model)
{
    if (string.IsNullOrEmpty(model.AccountNumber))
    {
      //This will always be the case, why?  See below
    }
}

Welcome to one of the challenges of MVC model binding. In the previous form, the first/last name and account number would post back to the server something like:

Customer__FirstName: BOB
Customer__LastName: SMITH
AccountNumber: ABC123

What needs to happen is the “AccountNumber” key also needs to be Customer__AccountNumber for it to successfully bind back to the server. You can add AccountNumber as a parameter to the post method, or we can add another interface that supports our hierarchy, and add this interface to the CustomerModel:

//Interface definition
public interface IAccountNumberModel
{
    IAccountNumberEntity Customer { get; set; }
}

//Update to the model class
public class CustomerModel : IAccountNumberModel
{

   public Customer Customer { get; set; }

   IAccountNumberEntity IAccountNumberModel.Customer { get; set; }

}

Here IAccountNumberModel has the same property name as CustomerModel; that’s important to make sure the model binding name structure matches. Now we can pass in the CustomerModel to the EditAccountNumber view with these modifications:

//EditAccountNumber
@model IAccountNumberModel

@Html.TextBoxFor(i => i.Customer.AccountNumber)
.
.

//EditCustomer:
.
.
@Html.Partial("EditAccountNumber", Model)

Since CustomerModel implements IAccountNumberModel, and this matches the type of model on our partial view, everything binds correctly.

Some Considerations For MVC 6 Client Attributes

One of the new features coming is the addition of Tag Helpers, which are server-side attributes that get interpreted and translated into a client-side attributes. This transforms the previous approach we used to use of the following:

@Html.ActionLink("Text", "Action", "Controller")
@* OR *@
<a href="@Url.Action("Action", "Controller")">Text</a>

Both of the above examples translate to the same result; Html.ActionLink builds a link with a single HREF attribute. One of the changes available with tag helpers is to instead use new “asp” prefixed attributes to perform the rendering:

<a asp-controller="Controller" asp-action="Action">Text</a>

These attributes get translated to a href client-side attribute with the appropriately generated URL. There are a variety of tags available that support server-side attributes, outside of the hyperlink. For instance, the form and label tags also support attributes, as well as others that you can find more at the following resources:

There is lots of good content out there on the subject already. I wanted to discuss in this post the merits of tag helpers, and discuss some of the pros and cons. Whatever is discussed with tag helpers, it’s important to remember that you can always utilize the old way of developing the user interface. To my knowledge, that isn’t going away.

It is important to remember that tag helpers are server-side; they still run server-side code, and so you cannot use asp attributes at client time. The client-side interpreters do not know of these attributes, but the server does as in this post. So if you like to use jQuery or Kendo UI templating, tag helpers won’t really give you much, as you have to render the link anyway. Now, there are server-side tricks to rendering client content that can be utilized, which I have written about in the past on this blog, and so there are ways to leverage that depending on what you are doing.

You also have to be careful which attributes you use where, as certain attributes are supported for certain tags. I haven’t found a comprehensive list yet, other than the Mikesdotnetting post. So be careful as you use new attributes to account for that. Also, some properties define expressions to the field in the model that may contain additional information. For instance, the label may support a field to grab the display information. In this case, the attribute defines the name of the field to display information for, which corresponds to the property in the model. It will be interesting to see how Tag Helpers support deep nested models, and whether we need to render names like Customers[0].FirstName when working with lists. This is one area where the old tags make it a little more clear.

These are some preliminary ideas to think about; I’m sure I’ll be amending this post as I think of other considerations after publishing this post :-)

Entity Framework 6 Update Taking REALLY Long Time

I had a strange issue updating the Entity Framework model against a newly built SQL Server 2014 database.  For some reason, it was talking a REALLY long time, even hours to connect.  Using SQL Server Profiler, we saw some activity which never completed.  I couldn’t figure it out until someone helped me by sending me this link: https://entityframework.codeplex.com/workitem/2445

Other users had indicated that Cumulative Update 5 needed to be installed and so this contained the resolution to the issue.  If you don’t want to install Cumulative Updates, changing the compatibility level to SQL Server 2012 worked just fine as well.  Changing the compatibility level immediately takes effect without server level restarts.

Understanding Game Design: Introductory Help

A lot of the game on the mobile market share characteristics with other games of the same type, and can thus be grouped together in a similar category.  Regardless of the type of game we are talking about building, one of the more useful features of the game is to provide some instruction at the beginning of the game.  There is usually an interactive explanation of the game’s mechanics that forces you to perform certain actions to make sure you understand how the game is played.

For instance, for a running game, the game guides the user to use the various mechanisms:  swipe up to jump, swipe down to slide, swipe left and right to move left and right, and whatever other controls may be involved.  The introductory help may also cover what the various menus do, and typically show you how you can upgrade your character.

For a civilization building game, the game illustrates how towns and cities can be built to improve your commerce capabilities, how to speed up the development by spending a secondary currency (like gems), how to upgrade characters in the game, how the menu system works, and detail any other game characteristic.

It’s good to have introductory help; even though the game may be self explanatory and a lot of the games have similar mechanics, it’s good to explain the mechanics so the user can unleash the full potential of the game.

Xamarin Forms Threading Fun

I’ve been trying out the async/await model in Xamarin Forms, and have had trouble getting it to work. It turns out there is great challenge in ensuring everything runs on the same thread. In this I learned a few lessons:

1) Make sure that once you start an operation asynchronously, make sure everything is also called in an async fashion. For instance, I had the following call hierarchy:

async LoginButton_Click
async HandleSignInCompleted(..);
async loginService.Login(..);
async HttpClient.PostAsync(..);

It’s important to make sure everything uses the async model, rather than calling the method directly. For instance, an async method can be called directly, or the results invoked directly with the .Result property on the Task. But don’t do it! Be consistent with the async/await setup.

2) Use ConfigureAwait(false)

The Task object has a ConfigureAwait method. I had success using it by applying it EVERYWHERE, on every async operation. In my above stack trace, this looked like:

async void LoginButton_Click //Since a button callback, can't define here
    async HandleSignInCompleted(..).ConfigureAwait(false);
       async loginService.Login(..).ConfigureAwait(false);
          async HttpClient.PostAsync(..).ConfigureAwait(false);

3) UI Synchronization

In my call stack, in the HandleSignInCompleted, there was a call to:

var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);

This failed with an Android error (tested on an Android device) stating that the view was modified on a different thread that the original, which makes sense since we are in the async thread. The solution to that was to wrap the call in a Device.BeginInvokeOnMainThread method call. This built up the UI for the Dashboard page in the main UI thread instead.

Device.BeginInvokeOnMainThread(() => {
var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);
});

Read more about BeginInvokeOnMainThread to understand the specifics, and why it may work in some situations and not others. So far that has been the tale of my adventures in asynchronous operations in Xamarin Forms. Hopefully this might help you as you use Xamarin Forms.

Understanding Game Design: Currencies

Within any specific game, there are various forms of currency, but it usually works out that there are two to three types of currency. The first type of currency, which I’ll call the primary currency, is the most easy to accrue. It usually exists within the game and is collected during the game play. For instance, for an endless runner game, the currency is in the path of the player waiting to be collected. For a city or civilization building game, currency is produced by a factory, mine, etc. and slowly builds up over time. These “factories” can be improved to yield a better economic output.

A secondary form of currency is rarer to collect. It doesn’t normally appear in the game, but can be collected in various ways: the most common way is through purchasing online. Other ways are usually as a form of daily reward, or lifetime achievements (for instance, as a form of reward for doing X action a lot of times). Sometimes, there is a third rare currency available to enable certain special actions, which can only usually be purchased.

Some examples of game currencies are the following:

  • Clash of Clans – Primary currency exists as gold/elixir, and secondary currency exists as gems. Primary currency is earned over time as produced by gold mines and elixir stations. Gems can be used to speed up the progress.
  • Boom Beach – Primary currency exists as gold for purchases, wood/stone/iron for producing buildings. Diamonds are available as a secondary currency and can be used to speed through the game.
  • Spiderman Unlimited – The primary currency are vials, with a secondary currency of ISO-8. Vials are collected during the course of running in the game, while ISO-8 is earned for completing levels.

During the game, the “economies of scale” usually favor a quicker accumulation of the primary currency, a slower accumulation of a secondary currency, and a purchase only accumulation of a tertiary currency. If you are unfamiliar with the term “Economies of Scale”, is defined as the following in Wikipedia:

In microeconomics, economies of scale are the cost advantages that enterprises obtain due to size, output, or scale of operation, with cost per unit of output generally decreasing with increasing scale as fixed costs are spread out over more units of output.

… For example, a large manufacturing facility would be expected to have a lower cost per unit of output than a smaller facility, all other factors being equal, while a company with many facilities should have a cost advantage over a competitor with fewer.

While we aren’t dealing with businesses or manufacturing, from a game design perspective, economies of scale can refer to paid vs. free users. There will be users that buy the game or pay for in-game currency to get ahead faster in the game, while other users will take a slower track and earn all currency. A good economy of scale with these two types of users should obviously slant to players willing to pay money in order to take the fast track, while making sure to offer an incentive to play the game for free users.

Incentives appear in many forms; some are the following examples:

  • They may be daily rewards for coming back to play the game day in and day out.
  • Special game modes can be made available that offer a higher level of currency than usual, but which is only available for a short period of time. These add some variances to the game

A Surprising Fact About Extension Methods

Extension methods are awesome. They allow extending the API of an object by creating a static method that “attaches” to an instance of an object, provided the extension method targets that type, which can be a generic or non-generic class, or an interface. Did you know that Extension methods extend an instance of an object, and can be called even if the object is null? For instance, suppose we had an extension method:

public static class ObjectExtensions
{
   public bool IsNull(this object obj)
   {
      return obj == null;
   }
}

And can be called on an object:

object obj;
var isNull = obj.IsNull();

Behind the scenes, the .NET framework passes the reference to obj to the static IsNull method, which will be null.

This works great for chaining references to objects which may or may not exist. For instance, I like to write extensions for LINQ to XML, to chain drilling through a series of objects which may or may not exist. The following is the extension method:

public static class XmlExtensions
{
   public static XElement GetElement(XElement el, string childName)
   {
      if (el == null)
       return null;

      return el.Element(childName);
   }

   public static string GetElementValue(XElement el, string childName)
   {
      if (el == null)
        return null;

      return el.Value("childName");
   }
}

Using these extensions, you can drill through a large hierarchy. Whether the elements exist or not, the drill through code works because we handle null, and continue the null chain. If all the elements exist in the document, the value is returned. A sample of using this is below:

var doc = XDocument.Load("test.xml");
doc.Root.GetElement("Customer")
        .GetElement("LastOrder")
        .GetElement("Details")
        .GetElementValue("Cost");

If Customer, LastOrder, Details, or Cost elements are not in the XML, then a null is returned from GetElementValue. However, if all are provided, the cost is returned as a string. A simple extension can make working with hierarchical data much easier.

Using TEF in Xamarin Forms

TEF (Typed Extensibility Framework) is similar to MEF, but was designed to be flexible, customizable, and easy to implement. In this guide, we’re going to look at how to use TEF in a Xamarin Forms project. TEF is pretty easy to get started, but certain features are not available in a portable environment, which are in a Xamarin Android or Xamarin iOS project (for instance, the AppDomain is not portable, but is available in these projects). Therefore, we need to do some customization. To start, let’s go through the following steps:

Create a Project

In Visual Studio or Xamarin Studio, create a new portable or shared Xamarin.Forms project. TEF will work with either option.

Import TEF

Using Nuget, download the TEF package using Import-Package TEF via command line, or search for TEF in the Nuget Window Search Bar.

Add an AppDomain Assembly Loader

Or whatever other strategy you like to use. The following snippet uses the AppDomain to look for the loaded assemblies and find any ExportType or ExportDependency attributes. To do this, we need to create a class that implements TEF.Consumption.IAssemblyLoader. It will return a list of assemblies, and must exist in both the iOS and Android project.

Find your iOS and Android projects and create a new folder called “Library” or “Services”, or whatever you like to call it, and include the following code snippet below in each project. Note: if you are using a shared project, this may work by placing the reference there. I haven’t tried using a shared project.

[assembly:Dependency(typeof(AppDomainAssemblyLoader))]

public class AppDomainAssemblyLoader : TEF.Consumption.IAssemblyLoader
{
	public IEnumerable LoadAssemblies ()
	{
		return System.AppDomain.CurrentDomain.GetAssemblies ();
	}
}

I chose to use Xamarin’s DependencyService, which is a service locator, as the means to register and fetch this type (you’ll see the fetch later on). To register types, see my previous blog post, which explains how the assembly attributes are used.

Add a Consumer

A consumer is the component that takes the types and produces a dependency injection container. In this example, I’m using SimpleInjector PCL. Any container can be used, and you can find more about supporting containers via the Container Integration documentation. Note: it’s not complicated to create your own IConsumer class though; see the documentation for how.

Import Types

We need to add the TypeFactory code that ties all of these components together. In the App class that the Xamarin.Forms project creates, this code can exist in OnStart, or it can also be utilized with the Lazy class. I chose a different route: define it in the property of the App class:

public class App : Application
{
	private SimpleInjector.Container _container;

	public SimpleInjector.Container Container {
		get 
		{
			if (_container == null) {
				_container = TypeFactory.Configure ((c) => {
					c.AssemblyLoader (
						DependencyService.Get (DependencyFetchTarget.GlobalInstance)
					).Consumer (
						new SimpleInjectorConsumer()
					);
				}).Initialize () as SimpleInjector.Container;
			}

			return _container;
		}
	}

Here we use the TypeFactory to tie everything together. The configure method takes the assembly loader and consumer references, while the Initialize() uses this to construct the container. The container is returned and can be used in your app (weakly typed). In my example, to use the container in your application, use ((App)Application.Current).Container. And that’s all it takes to incorporate TEF into an assembly. The benefit is we can mark a type like:

[ExportType(typeof(ISomeType))]
public class SomeType : ISomeType
{

or as:

[ExportAssembly(typeof(ISomeType), typeof(SomeType))]

public interface ISomeType { }

public class SomeType : ISomeType { }

And these will be automatically consumed for us and put in our dependency injection container.