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.

Xamarin Forms Async Loading of Data

Xamarin supports the async/await model of the .NET framework, which is an awesome capability. Because async/await is supported, it’s possible to use this to load the data in your application on demand. For instance, suppose we had a page with two listviews, such as the following sample page:



	
		
			
				
					
						
							
							
							
						
					
				
			
		
	

	
		
			
				
					
						
							
							
							
						
					
				
			
		
	


Let’s take a second to look at the ListView markup. The ListView renders a custom ViewCell for each item in the list. We can use ViewCell to create a custom UI for each list item, which is provided by the inner StackLayout. The ListView is bound in code (though could be easily bound in the markup) as shown below, each delaying a specific period of time (for the purposes of simulating a network request).

public class Game
{
	public string Name { get; set; }
	public int Score { get; set; }
	public string PlayerImageUrl { get; set; }
}
public class HighScore
{
	public string Name { get; set; }
	public string Level { get; set; }
	public int Score { get; set; }
}

private async void LoadGames()
{
	await Task.Delay (3000);

	//All zeros is used for demoing purposes.
	this.GamesList.ItemsSource = new List {
		new Game { Name = "Paul J.", Score = 5350, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Peter K.", Score = 3410, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Bill C.", Score = 960, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Bobby B.", Score = 3190, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Amy S.", Score = 5950, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" }
	};
}

private async void LoadHighScores()
{
	await Task.Delay (5000);

	this.HighScoresList.ItemsSource = new List {
		new HighScore { Name = "Robby10210.", Score = 907409, Level = "Lv. 42" },
		new HighScore { Name = "Peter K.", Score = 891399, Level = "Lv. 41" },
		new HighScore { Name = "Bill C.", Score = 801222, Level = "Lv. 39" },
		new HighScore { Name = "Bobby B.", Score = 681202, Level = "Lv. 34" },
		new HighScore { Name = "Amy S.", Score = 660198, Level = "Lv. 33" }
	};
}

This loads data into the lists after a delay without interruption to the user. A quick demo of the app is illustrated below for your viewing pleasure on Youtube at the URL, taken with Camtasia – a great screen recording tool: http://www.youtube.com/watch?v=3l2B9v2b0gw.

Dependencies in Xamarin Forms

Dependency Injection and Service Location, in the .NET world, is becoming widely accepted as a flexible way to link resources between classes dynamically. One of the many frameworks out on the market provide a very flexible way to locate dependencies or build up an object via constructor/property injection. Some of these containers also contain a bootstrapper component that make registration in the application easier.

There are two components to this: the type registration, and the type location. Let’s take a look at both of these separately.

Type Registration

There are a variety of ways to do this. Outside of defining the registrations manually, there are other frameworks out there that make defining dependencies easier. For instance, I’ve recently created a product called TEF (typed extensibility framework), which is similar to MEF, but for types. By marking a type as a dependency using assembly attributes, or by marking the type with an exportable attribute, the system extracts these types from the assembly and makes them available for registration in the container. Below is an example of how you can mark a type as exportable:

public interface ISomeType { .. }

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

OR


The system can then parse the assemblies in the application, extracting out all of the individual types. I go through this example because the DependencyService registers components in the assembly in a very similar way. It follows a similar design to TEF for registration; however, it only supports assembly attributes as in the following example:


Marking all of your dependencies will automatically import them into the dependency service.

Type Retrieval

The Xamarin Forms Dependency Service has a similarity to ASP.NET MVC’s IDependencyResolver, which has the same purpose of supplying types to the various components.

This is not the same as a dependency injection container; it is a service locator designed to locate references. For instance, if you have this page:

public partial class DependencyPage : ContentPage
	{
	private ICacheService _cache = null;
	private IDependentService _dependent = null;

	public DependencyPage (ICacheService cache, IDependentService dependent)
	{
		InitializeComponent ();

		_cache = cache;
		_dependent = dependent;
	}

}

Notice it has two constructor dependencies. The following will produce an error with the dependency service.

var page = DependencyService.Get (DependencyFetchTarget.NewInstance);

With a Dependency Injection container, the above code would actually work because the container can handle cascading dependencies. Instead, to use DependencyService, it would have to be created this way:

var page = new DependencyPage(
    DependencyService.Get (DependencyFetchTarget.NewInstance), 
    DependencyService.Get (DependencyFetchTarget.NewInstance)
);

for the page to work. If anyone has any tips, or if there are inconsistencies, please post a comment and I’ll update the post.

Understanding Game Design: Challenges

Previously we looked at offering a reward as an incentive to bring people back to your game day after day. In this post, we are going to look at an additional incentive: challenges. Challenges occur in several forms:

Daily Challenges – Challenges only available for that day; as long as the challenges are met, then the streak continues. Usually there are three challenges that need completed to finish the challenges for the day.
Mission Challenges – Challenges related to the game or mission at hand, that try to shape the way the user plays the game. For instance, while a player may try to get through point A to B as quickly as possible, Mission Challenges try to convince the player to achieve certain objectives within the game that extend the game even further, with some incentive (such as in-game currency).
Coincidental Challenges – For the lack of a better word, some challenges encourage the user to perform certain actions in the game (jump over something 5 times, slide under this or that, etc.) that may not directly relate to the actions of the game.

Challenges give the user the opportunity to achieve some perk for completing certain tasks. The challenge should be enticing enough to encourage users to continually come back to the game. However, these perks do not amount to the same amount of incentives offered for purchasing in-game currency; daily challenges usually progress the game a little faster, but overall progress continues forward a bit more slowly than users who pay money to buy currency. Challenges reward users for completing the challenge, and may offer a continual streak for completing the challenge day after day.

As the user gets more skilled, challenges should increase in difficulty. For instance, maybe the player has to run 250 feet to achieve the challenge. That distance should increase slowly over time. It should always be within grasp though; if the challenge is increased too much, it may dissuade the player from trying to put in the effort. Additionally, increases shouldn’t occur after every time they complete it, but after so many completions of the perk.

Let’s take a look at some examples of challenges:

– Subway Surfer – the player gets rewards for performing in-game activities. Jumping over train cars, rolling X times, collecting X coins, stumbling into train cars, are all challenges that can be completed to increase the overall score multiplier. Increasing the score multiplier leads to higher scores.
– Mini Golf MatchUp -This game provides 3 daily challenges that have to be earned within the game. While these challenges don’t streak, completing the challenge offers a coin reward. The rewards are provided for certain actions: making a hole in one, activating certain features, etc.

Understanding Game Design: Daily Rewards

Almost every mobile game I see offers a daily reward of some sort. ¬†Whether it be a form of currency or an in-game product for temporary or permanent use, a daily reward seems to be a common occurrence for most games. ¬†There have been a few variances between the forms of daily rewards offered, so let’s look at the various kinds of setups:

When to Offer

Once a day – this is the most common setup; a user can get a daily reward just by logging into the game, but only once per day. The perk screen would appear the next day the user logged in. Sometimes, these types of perks had to be collected everyday, or the streak was lost. We’ll discuss that later.
Exactly 24 Hours – This is a setup that’s also been used; at exactly the 24 hour mark, the perk will become available. A countdown timer is usually displayed to let the user know how long to wait.

An important decision point here is whether missing a day breaks the streak. That may make sense for the once a day perk, but may not make sense for the exactly 24 hours perk.

How to Offer

Randomization – A random reward is chosen and given to the user. A common method of displaying the chosen perk is by a spinning wheel (similar to Wheel of Fortune or the Price is Right).
5 Day Reward System – A common setup is a 5 day reward system. Rewards can either progress up to include better prizes. They may also offer the same prize; on completion of the fifth day, a bigger reward is usually granted. Missing one day often causes this reward system to reset back to zero.
5 Day Sliding Reward System – I only saw this in one game, but thought it was interesting. The game offered a 5 day reward system. At specific intervals (which for larger inventory items may occur at day 50, or smaller inventory items at day 20/25), would offer a powerful item the user typically wanted.
Continual Day Reward System – This reward system contains a reward system with a large number of days, building up to something epic if the user is committed to the game. Missing a day may or may not break the streak (which breaking the streak would cause the system to reset).

What to Offer

The most common offering is in-game currency. Usually, it’s the primary currency offered by the game; the daily reward helps the user obtain currency quicker by being committed to the game. As the game progresses, additional forms of currency may become available (we’ll be talking about currency in another post). At the end of a 5 day reward system, the game may offer an item used within the game.

Some Examples

Let’s look at some game examples:

Subway Surfer – Upon spelling a word by collecting letters in the game, the user gets a certain amount of coins in the game. Every day the reward is collected, more money is achieved. Upon completing the 5 day challenge, the last prize is a Mystery Box.
Despicable Me: Minion Rush (older version) – Before they changed it to the current reward system, the previous version offered a 5 day reward system that could be collected once certain in-game achievements were completed. For the first 4 days, random achievements were earned. On day 5, a puzzle piece could be claimed. Puzzle pieces were used to unlock characters. If one day was missed, the process would start over again.
Temple Run 2 – Upon completing in game achievements, rewards are earned. There are 5 days, and the reward increases every day.
Candy Crush Saga – A daily challenge wheel appears and offers a daily prize.
Spy Wars – In game currency is earned by logging in every day. Additionally, a secondary currency is earned if the user logs in with Facebook. The reward system continues up in the amount of money earned, and eventually resets. Breaks in days do not reset the reward.
Punch Hero – A continual reward system that is offered at exactly 24 hours. Nothing in the game needs to be completed to receive it. A break in the day does not break the streak; however, the maximum prize offered is only available if collected within the month.

TEF Available As A Nuget Package

I’ve added TEF as a Nuget package available for download in two flavors now:

Install-Package TEF

TEF is a PCL library which allows you to define types for exporting into a dependency injection container. Since it’s PCL, it can work in Silverlight, Xamarin.iOS, Xamarin.Android, and more.

Install-Package TEF.NET

This is a .NET 4.5 version that provides .NET framework specific add-ons, such as parsing the assemblies in the app domain.

Biztalk 2013 R2 Database Selection Error on Deployment

I’ve been involved in setting up a Biztalk 2013 R2 instance, and it’s been a good learning opportunity for me. We ran into an interesting issue today, having to do with SQL Server permissions. The environment I work in is pretty locked down as far as permissions are concerned, and in trying to deploy a Biztalk application to the development environment and on entering the database server name in the Server field, the database could not be selected. If the defaults were supplied by default, everything was OK. But on entering the server name, the selector for the Biztalk Configuration database said that it couldn’t connect to the server to retrieve the database list. It failed to pull the names of the databases available on the server for my AD account.

While some sites said adding sysadmin in SQL Server would help, what actually worked was granting the “View All Databases” permission in SQL Server. So by adding this database permission, that resolved the issue. I was glad it was that because I wasn’t about to get sysadmin privileges :-D.

ASP.NET MVC Seamless Routing Encryption

There are certain pages in the application where the data passed in must be encrypted in a GET request. This could be a link redirection from an email or another site, or just an internal redirect where the parameters can’t get exposed. A link like this may actually look like:

/Some/Action?enc=345SFIPOWHG:LNNJE:LKJWET46-DSFSF:KJ

The data is nonsensical to the user, but contains identifying information about the user. For instance, the encrypted data may have the following information:

– User ID
– Response Identifier
– Response (Yes/No, Agree/Disagree, text description, whatever else)

The system can then check that the user logged in matches the user in the URL request. It can lookup the associated response database record, and record the response provided. This feature is not native to ASP.NET MVC, but is relative easy to build in. This post will illustrate how to do so, using the following steps:

1) The first step is to create an action method to define a URL. We’ll want to create two forms: one method as a redirection, and one method as an URL generation. Both of these will be extension methods on different objects:

private static string GetEncryptedData(object args)
{
    var encryption = new EncryptionService();
    var list = new RouteValueDictionary(args);
    var items = new List();

    foreach (var entry in list)
    {
         items.Add(entry.Key + "=" + (!string.IsNullOrEmpty(entry.Value) ? entry.Value : ""));
    }

    return encryption.Encrypt(String.Join("&", items));
}

public static ActionResult RedirectToActionSecure(this ControllerBase controller,
                                                  string action, 
                                                  string controller, 
                                                  object args)
{
    var encText = GetEncryptedData(args);
    return controller.RedirectToAction(action, controller, new { enc = encText });
}

public static IHtmlString ActionSecure(this UrlHelper url, 
                                       string action, 
                                       string controller, 
                                       object args)
{
    var encText = GetEncryptedData(args);
    return url.Action(action, controller, new { enc = encText });
}

Certainly, you can create overloads without the action and/or controller too, which is easy to do. Additionally, this code should do more null checking; it assumes that the data exists. The first step is get a reference to the encryption service you are using for your application. I’m leaving that out of this post. Using this service, a querystring is generated and then encrypted together. The value is stored in the “enc” querystring value when routed. This looks like in the code:

public ActionResult X()
{
   return RedirectToActionSecure("Action", "ctlr", new { a = 1, b = 2 });
}

Or in the view:

@Url.ActionSecure("Action", "ctlr", new { a = 1, b = 2 });

When a request is made to that controller and action, MVC checks for the “enc” querystring parameter. It does this in an Action filter attribute, on ActionExecuting.

public class EncryptionActionAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext context)
   {
        var encryption = new EncryptionService();

       // Step 1: parse the URL
       var url = context.HttpContext.Request.Url.ToString();
       var index = url.IndexOf("enc=");

       if (index > 0) {
         //Get the encrypted value and decrypt it.
         var encText = context.HttpContext.Server.Decode(url.Substring(index + 4));
         var groups = encryption.Decrypt(encText).Split('&');
         var actionParams = filterContext.ActionDescriptor.GetParameters();

         //Parse all of the "KEY=VALUE" groups
         foreach (var group in groups)
         {
            var pair = group.Split('=');

               if (pair.Value == null)
                 continue;

               //Make sure the action has the parameter of the given name
               var actionParam = actionParams.FirstOrDefault(i => i.Name == pair.Key);
               if (actionParam != null) {
                  var nullType = Nullable.GetUnderlyingType(actionParam.ParameterType);

                  //If a nullable type, make sure to use changetype for that type instead; 
                  //nullable types are not supported
                  if (nullType != null)
                     context.ActionParameters[pair.Key] = 
                          Convert.ChangeType(pair.Value, nullType);
                  //Otherwise, assign and cast the value accordingly
                  else
                     context.ActionParameters[pair.Key] = 
                          Convert.ChangeType(pair.Value, actionParam.ParameterType);

               }

         }
       }
   }
}

There’s a lot to it, so let’s break it down:

– Again, missing null checks and conversion error recovery, so you’ll want to ensure that’s there.
– The first step is to grab the encrypted value from the URL and decode it; once we have this value, the encrypted value is decrypted to get the key/value pairs.
– The filter context has two parameter types: ActionDescription, which GetParameters() returns the metadata of the action method, and ActionParameters, which is a collection of values about to be injected into the action. The ActionParameters collection can be added or modified as you like.
– Each key/value pair is evaluated, and injected into the ActionParameters collection; the values that were encrypted were injected in.
– We first have to check that a nullable type is converted correctly; otherwise, the cast to a nullable type through ChangeType raises an exception.

Some/Action?enc=23442q5wetew

It’s decrypted to:

UserID: 1
ResponseID: 3
Response: YES

The values are inserted into an action method like this:

Authenticating over AD with the ADMembershipProvider

Want to authenticate against AD but don’t want to use LDAP directly? Would you like to use the AD membership provider, but don’t want tied into the membership API? No problem! That’s because you can programmably create the membership provider, provide some configuration options, and then made an API call to check the login status. The code is very simply the following:

var membershipProviderName = "Provider"; // Does not need to be in web.config
var connectionStringName = "SomeConnectionString";
var config = new NameValueCollection();

config.Add("connectionStringName", connectionStringName);

var provider = new ActiveDirectoryMembershipProvider();
provider.Initialize(providerName, config);

var isValidUser = provider.ValidateUser(user, password);

And that’s all it takes. The provider name is the name you would normally see in the configuration file; we’re defining it during initialization. Next, we need to create configuration options. Our implementation only supplies the connection string name defined in the connection strings setting. Define a connection string, with the name supplied above, that points to the LDAP store. Note that no membership API needs to exist in the

Next, we create and initialize the provider, and use the provider to validate the credentials. Is there an expense to building this up every time? I haven’t tested it out, but logically it seems that would be the case. Just plan it’s use accordingly.

Entity Framework Table Tricks

I’ve seen out on the web quite a few questions about how to do this or that with Entity Framework, so I’d thought I’d write up a solution to various ways to work with tables and to customize entities.

Sets

Suppose we have a context with a Customers table; by default, the Entity Framework code generator generates code that allows the consumer to do the following.

var ctx = new EFContext();
ctx.Customers.Where(i => ..);

The Customers property is a DBSet object that is responsible for “table management”, which is not quite right but a good quick way to understand it. The DBSet is the primary mechanism for generating queries against the table and adding new objects to the table. Entity Framework code generators create wrappers around this object, but also expose the following methods in two forms:

public System.Data.Entity.DbSet Set(Type type);
public System.Data.Entity.DbSet Set();

Referring to a table generically using the set method comes in handy when you want to simplify your data access code. To explain what I mean, let’s look at a small sample. We may want to use the repository pattern like this:

public interface IRepository
 where T: class
{

    IEnumerable GetAll();

}

public class CustomerRepository : IRepository
{
   public IEnumerable GetAll()
   {
      var ctx = new EFContext();
      return ctx.Customers.ToList();
   }
}

Note how we write the code in each and every repository; we have 1 now, but as the system grows, each repository has to write this same code over and over again. Sure, we can generate it automatically, but we can also do this:

public abstract class BaseRepository : IRepository
{
   public IEnumerable GetAll()
   {
      var ctx = new EFContext();
      return ctx.Set().ToList();
   }
}

public class CustomerRepository : BaseRepository
{

}

Notice the set method usage and how this one common method prevents us from having to write common code. Now we have one method shared across all repositories. We could also use the other override like so:

ctx.Set(typeof(Customer));

Although, it’s far less flexible than the generic form. A lot of the common options are not available out-of-the-box. One important use you can use it to add objects to the database, however.

var customer = new Customer { .. };
ctx.Set(typeof(Customer)).Add(customer);
ctx.Set().Add(customer);

ctx.SaveChanges();

SaveChanges then commits any changed made, raising errors for any validations or update exceptions.

Using Interfaces

Using interfaces can add in some nice flexibility. Suppose we have an interface like this:

public interface IAuditEntity
{
   public DateTime Entered { get; set; }

   public DateTime? Updated { get; set; }
}

Supposing that all of your entities implement this interface, you can simplify your repositories by creating common code:

public abstract class BaseRepository
{

   public IEnumerable GetUpdatedSince(DateTime check)
      where T: IAuditEntity
   {
      var ctx = new EFContext();
      return ctx.Set().Where(i => i.Updated != null && i.Updated.Value > check);
   }

}

While the example above is not the most useful, it illustrates what can be done to create common routines in entity framework. Since Updated matches the name of a field in the table being queried, Entity Framework resolves this correctly; if the name doesn’t match, an exception will be raised saying the property defined in the expression doesn’t exist in the table.

Functions

What floored me though is through a method, Entity Framework can bridge the gap and provide common code. For instance, suppose we had entities like this:

public class Customer
{
   public string Country { get; set; }
}

public class Employee
{
  public string PrimaryCountry { get; set; }
}

We couldn’t create an interface with the name Country, because Employee doesn’t have a matching property. We could change the name, but for the sake of the example, let’s keep them different. Since property name mismatches cause errors, we can surprisingly use functions. An architect had shown me this and I was floored, simply because properties don’t work. But by doing:

public interface ICountry
{
   public string CountryExpression();
}

public class Customer : ICountry
{
   public string Country { get; set; }

   public string CountryExpression()
   {
      return this.Country;
   }
}

public class Employee
{
  public string PrimaryCountry { get; set; }


   public string CountryExpression()
   {
      return this.PrimaryCountry;
   }
}

And then doing the following in the query will work:

public IEnumerable GetByCountry(string country)
 where T: ICountry
{
  var ctx = new EFContext();
  return ctx.Set().Where(i => i.CountryExpression() == country);
}

An architect showed me this trick, and I was floored that it worked since properties don’t. Hopefully this post illustrated some tricks to using entity framework and reduce the overall coding needed.