TEF Open Source Project Released

I’ve always liked the idea of MEF. The ability to mark a class as exportable, then very easily consume it in your application is a very nice feature. However, MEF has always been instance-based, meaning you had to have an instance of a class to register. This works OK in some instances, but not in others. For example, in some instances, an instance of a class in ASP.NET can be problematic, especially if it’s tied to a specific HTTP context.

Because I needed type-specific support, without having to instantiate a specific instance, TEF was born, a simplistic implementation for registering your types. Registering your types is as simple as adding an [ExportType] to your class, or adding an assembly attribute [ExportDependency].

[ExportType(typeof(ISomeService))]
public class MySomeService : ISomeService
{
}

OR:

[assembly:ExportDependency(typeof(ISomeService), typeof(MySomeService))]

To extract the types out of the assembly, you can target a specific app domain, assembly or collection of types. For instance, the code below targets a specific app domain.

var importer = new TEFMetadataImporter();
//Pull any assembly dependencies marked with [ExportDependency]
var types = importer.GetAssemblyTypes(AppDomain.CurrentDomain).ToList();
var assemblyTypeCount = types.Count;

//Pull any type dependencies marked with [ExportType]
types.AddRange(importer.GetClassTypes(AppDomain.CurrentDomain));

The project was built for .NET projects, MonoTouch, and MonoDroid. You can grab the source code and a sample project for TEF on BitBucket. Note: for MonoTouch and MonoDroid, the project was built with Xamarin Studio, so the System DLL’s may not match the Visual Studio System DLL’s.

Telerik Q1 2014 Released

The latest release for Q1 2014 was includes some features that really caught my eye, and so I’m posting this to share them to you. The first was the new words processing feature for the WPF Telerik framework, a framework that can generate a word document without the use of Word. In my opinion, that is huge, as it is a very useful framework that can even challenge other word processing software products available on the market, now available with DevCraft complete.

The second interesting product was a responsive UI framework available with the Kendo UI framework. A lot of applications make use of some responsive UI framework like Twitter Bootstrap or Foundation by Zurb. Now that Kendo has an offering for this, it’s one step closer to making Kendo a complete product.

Dependency Inection in .NET Book Review

One of the first tasks in any application I build is to setup a Dependency Injection container, provide a simple wrapper around the container itself, and make it available throughout the entire application. The reasoning is simple; all of the references are easy to contain, the application remains loosely coupled, and the dependencies are managed for you. The DI container composes the object and populates all of the dependencies automatically. To me, DI has always been a pattern undervalued in the .NET world, and so a book like this is great to make such an excellent design pattern known to the .NET world.

A really good book on Dependency Injection was published and is a good read for going from knowing nothing about Dependency Injection to becoming an expert in it. The book walks through the basics of DI: how to inject a reference and how to design your component to allow for dependency injection, object composition, and lifetime management. The book continues on to look at what’s good for DI, and what is an anti-pattern for DI as well.

The book follows up with how to setup DI using some of the most widely used Dependency Injection containers on the open source market. Each chapter illustrates how a user would setup the container, provide the references, and make use of the container within an application. It looks at the various configuration options each container has, and explains the nuances (each container does behave a little bit differently, even though conceptually they are very similar).

If you never looked into dependency injection, I would highly recommend that you do, and this book is a great way to start.

Adding ASP.NET MVC Anti-Forgery Tokens To All Post Requests Easily

One of the newer attacks against web applications is the cross-site request forgery attack. It’s an attack against modern applications that store a cookie to represent the currently logged in user. The problem has been explained in other web sites. I’d highly recommend checking out Phil Haack’s blog post on the subject.

One of the techniques to prevent this attack is to add an anti-forgery token using the @Html.AntiForgeryToken extension method. On the controller side, the action method defines the [ValidateAntiForgeryToken] attribute. Behind the scenes, the hidden input field for the anti-forgery token is validated by the MVC framework to ensure it’s correct. This has also been explained well; see Steve Sanderson’s post on the subject. While there is discussion as to whether this approach is needed just for the logging in an anonymous posts, or all posts in general, as been up for debate. But the point of CSRF is to attack authenticated users.

I’m not real fond of repetitive coding, especially when the framework is flexible enough to avoid it. Below is my solution to to create a flexible solution to validate all post operations. The first task is to create an attribute for validating the token. After using .NET Reflector by Red Gate to examine the existing ValidateAntiForgeryTokenAttribute class, the token is simply an authorization attribute that validates the request using a helper utility to validate it. See the example below.

public class GlobalAntiForgeryTokenAttribute
  : FilterAttribute, IAuthorizationFilter
{
  public sub OnAuthorization(filterContext As AuthorizationContext)
  {
	if (filterContext.HttpContext.Request.HttpMethod.ToUpper() == "POST")
	{
	  AntiForgery.Validate();
    }	
  }
}

On authorization of the request, if the operation is a POST request, we call the Validate() method on the AntiForgery helper to actually perform the validation. All of our post operations are now checked for forgery; however, this will fail because we haven’t added our token globally. To do that, we have to create a custom form extension method like the following:

public static void FormExtensions
{
   public static MvcForm BeginDataForm(this HtmlHelper html, string action, string controller, ...)
   {
     var form = html.BeginForm(action, controller, ...);
	 //At this point, the form markup is rendered in BeginForm
	 // we can render the token
	
	 //With every form, we render a token, since this
	 //assumes all forms are posts
	 html.ViewContext.Writer.Write(html.AntiForgeryToken().ToHtmlString());
	
	return form;
   }
}

If we use our custom helper for all of our forms, then all of our custom forms will have rendered an anti-forgery token. Therefore we don’t have to worry about creating it ourselves, saving time and reducing code.

Launching the Browser in Android with Xamarin

If you like the Android interface and have used an app like Facebook or Twitter, you’re no doubt used to the ability to click a link and get a list of browser-based applications to choose from. This ability to choose your browser to open a link is a feature in Android called an “intent”. An intent is an asynchronous message to request some action on behalf of another application. Intents serve many purposes, such as sending data to Facebook, or a browser. Intents also navigate between activities in an application.

For sharing to a browser, it requires using a special intent with is the Intent.ACTION_VIEW in Android, or Intent.ActionView in Xamarin Android. This intent, along with the URL, signals to Android to open the requested resource in a browser. For instance, let’s take a look at the following method:

private void ShareToBrowser(string url)
{
	if (!url.StartsWith ("http")) {
		url = "http://" + url;
	}

	Android.Net.Uri uri = Android.Net.Uri.Parse(url);
	Intent intent = new Intent (Intent.ActionView);
	intent.SetData (uri);

	Intent chooser = Intent.CreateChooser (intent, "Open with");

	this.StartActivity(chooser);
}

In our utility method, from an URL string, we ensure there is an “http” prefix on the URL; otherwise, the intent doesn’t quite work right. From the URL, we create an Android URI, and pass it as the data of the intent. The constructor of the intent takes the name of an action, which in our case, is the view action. In most other common situations, we’d use the Send action. The View action is used for browsing, whereas Send is used for app sharing (to Facebook, etc.)

If we were to start the activity without the chooser, Android would pick the first browser installed and launch it. By adding a “chooser” intent, we get that nice “Open with” dialog, listing all of our installed browsers. And it’s that simple to launch the browser in our application.

If you are looking for a nice overview of intents, Lars Vogel has a nice overview available at Vogella.

VB.NET Inline Functions in ASP.NET MVC and Razor

I’ve seen various debate about whether inline markup expressions work in VB, and I want to tell you that they do. Here is how I did it. Define a method like the following, which will be an HTML helper extension. Please see my introductory post on how to do that:


<Extension>
Public Sub Inline(Of TModel)(html As HtmlHelper(Of TModel), template As Action(OF TModel))

In a view, you can define an implementation of that method like the following:


@Code

Html.Inline(Sub(m)
@<span>This is my template</span>
End Sub)

End Code

This approach has worked for me, as long as any helper using the template is inside an @Code block, and the Sub(m) declaration is a multi-line sub, not an inline statement.

Custom ASP.NET MVC Helper Extensions

As you probably are aware of, ASP.NET MVC was a divergence from the approach developers took to developing ASP.NET web forms applications. For web forms developers, any level of customizations occurred by creating custom ASP.NET server controls, inheriting from a particular base class and adding some functionality, something like:

public class SuperLabel : Label
{
   // Enhanced functionality
}

There are many benefits to doing this; you can initialize the control’s properties for your web application, or encapsulate repeatable code into a common class that’s reused throughout the application. For instance, if we know that we will always render our form labels in a specific manner, I could create a custom control to do this following:

public class FormLabel : WebControl
{

   protected override void Render(HtmlTextWriter writer)
    {
         writer.Write("<div>" + this.Text + "</div>");
    }

}

And that way, every label is wrapped in a div with a FormLabel class. This is a simple example of standarizing your control’s output and thus your client’s markup, but you get the idea. This is also possible in ASP.NET MVC, with the help of your own helper methods.

Note that there are two kinds of helper methods in MVC: ones who return an MvcHtmlString object and render the text inline, and ones that render inside the method and are defined as @Html.DoSomething(); (with a semi-colon at the end; in VB this method can be called in a @Code block). I’m going to talk about helpers that return an MvcHtmlString in this blog post. As a simple example of a helper we may want to standardize on, we can, for instance, wrap a DIV with a special class around the Html.EditorFor helper as in the following example:

public static class HtmlHelperExtensions
{

  public static MvcHtmlString CustomEditorFor(this HtmlHelper html, Expression<Func> expr)
  {
     return new MvcHtmlString("<div>" + html.EditorFor(expr) + "</div>");
  }

}

As you can see, we have a custom editor with a wrapper DIV around it now, which we can put in our UI by doing:

@Html.CustomEditorFor(i => i.ModelProperty)

The TModel and TProp generic references above are inferred from the current view’s model, and the property expressed in the lambda expression. If you look in other MVC helpers, they are all defined with these two generic references. The HtmlHelper class has a lot of useful features; first it has access to all the extension methods as you would use them in the UI (most defined in the System.Web.Mvc.Html namespace, but there are additional namespaces too). It also has a reference to the ViewContext and to the current model for the given view, via the HtmlHelper.ViewData.Model property (remember HtmlHelper is specific to the model, therefore it maintains an explicit, strongly-typed reference to said model).

I’ve only scratched the surface, but you can see a lot of options are available to you. For instance, if you use Twitter bootstrap, maybe you want your editor helper to look like:

 public static MvcHtmlString CustomEditorFor(this HtmlHelper html, Expression<Func> expr)
  {

     return new MvcHtmlString(
  @"<div class=\"control-group\">" + 
    html.LabelFor(
        expr, 
        new { @class = "col-md-2 control-label" }
     ).ToHtmlString() +
   @"</div>
     <div class=\"col-md-10\">" + 
    html.EditorFor(expr) + 
    "</div>");

  }

And thus, this saves you from writing a lot of HTML. In the future, I may write on some of the extensions I’ve used for twitter bootstrap to save time. I hope this is a good overview of how you can customize HTML helpers in ASP.NET MVC, which I am using this technique in a current ASP.NET MVC 5 application.

UITableViews Part 3: Showing a View Over a UITableViewCell in Xamarin iOS

An iOS UI is comprised of a view, which is what the user sees, and a controller, which is the functional logic. A view can have one or many subviews, but this is not required. Within iOS, there are specialized controlles that work with a particular type of view. For instance, the UITableViewController works with a UITableView as it’s user interface.

Step 1: Initial Setup

Setup a UITableViewController, and a view and/or controller to overlay. There is nothing complex here, and I’m not going to go into any more specificity.

Step 2: Setup Globals

We’ll need a reference to our controller to overlay (within our custom UITableViewController class), so that we only have one static reference to use as the popup. I created the controller in the ViewDidLoad method.

private LinkItemActionController _actionController = null;
public override void ViewDidLoad ()
{
base.ViewDidLoad ();

_actionController = new LinkItemActionController ();
_actionController.View.Hidden = true;
//My own custom method
this.AddViewControllerToView (_actionController, this.View);

Step 3: Responding to the Selection

Now that we have a controller in place, anytime an item is selected, we need to change the current frame that the controller’s view draws in. On click of a cell, the UITableViewSource triggers the RowSelected delegate method. From here, we can notify the controller to draw the LinkItemActionController view within the bounds of the cell. Below is a snippet of how I do that.

//Data source for tableviewcontroller
protected class LinksSource : Nucleo.UI.BaseTableViewSource
{
public event EventHandler ItemSelected;

public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
	var cell = this.GetCell (tableView, indexPath);

	var dataItem = this.GetDataItem (indexPath);
	if (dataItem == null)
		return;

	if (ItemSelected != null)
		ItemSelected (this, new SelectEventArgs { Cell = cell, DataItem = dataItem, IndexPath = indexPath });

	tableView.DeselectRow (indexPath, true);
}

}

//controller, responds to ItemSelected event
public partial class LinksController : Nucleo.Controllers.BaseUITableViewController 
{

void HandleItemSelected (object sender, SelectEventArgs e)
{
	var rect = this.TableView.RectForRowAtIndexPath (e.IndexPath);
	_actionController.View.Hidden = false;
	_actionController.View.Frame = rect;
	_actionController.RefreshUI(rect.Width - 40, rect.Height);

	_selectedItem = e.DataItem;
}

In this snippet, the UITableViewSource (from the snippet given in a previous post) notifies the controller that the row was selected. An ItemSelected event bubbles up to the controller, and the HandleItemSelected method handles loading the UI. First, it uses RectForRowAtIndexPath to get the underlying frame to use for the drawing. Next, the view is shown and given the cell rectangle. Lastly, a RefreshUI method does the actual drawing of the buttons, and we store the current selected item for safekeeping.

Step 4: Loading the Buttons

When I first learned how to frame a house, I learned about how to place the studs that support a wall every 16 inches, except for the second stud, which is 15 1/4 inches away from the first stud. The reason for this is simple: to make sure the plywall overlaps a stud evenly on both sides (essentially centering each end evenly over the stud). We’re doing something similar here; we’re going to try to render each button evenly over the cell row, but we have to offset the first button by half of the width to ensure each image appears correctly within its quarter segment (as there are 4 buttons, I broke each out evenly). To do this, I used the following code and a little bit of math to do it (this is our LinkItemActionController):

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

	this.View.BackgroundColor = UIColor.FromRGBA (255, 154, 35, 50);

	//TODO: display evenly-spaced buttons
	_cancelButton = this.CreateButton ("icon_back.png");
	_cancelButton.TouchUpInside += HandleCancel;
	this.View.AddSubview (_cancelButton);

	_shareButton = this.CreateButton ("icon_share.png");
	_shareButton.TouchUpInside += HandleShare;
	this.View.AddSubview (_shareButton);

	_deleteButton = this.CreateButton ("icon_delete.png");
	_deleteButton.TouchUpInside += HandleDelete;
	this.View.AddSubview (_deleteButton);

	_viewButton = this.CreateButton ("icon_view.png");
	_viewButton.TouchUpInside += HandleView;
	this.View.AddSubview (_viewButton);
}

public void RefreshUI(float availableWidth, float availableHeight)
{
	var quarterWidth = availableWidth / 4f;
	var centerWidth = quarterWidth / 2f;
	var currentY = (availableHeight - IMAGE_SIZE) / 2f;
	var currentX = centerWidth - (IMAGE_SIZE / 2f);


	_cancelButton.Frame = new RectangleF (currentX, currentY, IMAGE_SIZE, IMAGE_SIZE);
	currentX += quarterWidth;

	_shareButton.Frame = new RectangleF (currentX, currentY, IMAGE_SIZE, IMAGE_SIZE);
	currentX += quarterWidth;

	_deleteButton.Frame = new RectangleF (currentX, currentY, IMAGE_SIZE, IMAGE_SIZE);
	currentX += quarterWidth;

	_viewButton.Frame = new RectangleF (currentX, currentY, IMAGE_SIZE, IMAGE_SIZE);

}

The IMAGE_SIZE constant is 44 pixels. As a rough example, assume that the total width is 400 pixels. Each quadrant is 100 pixels wide. We want the button to be in the center of the quadrant, so we subtract half of the 100 pixels to arrive at 50. We also need to ensure that we factor in the button image width, which is 44 pixels wide; not factoring this in would throw off the centering, and therefore the algorithm also subtracts another 22 pixels, arriving at a first coordinate value of 28,0 (the cell happens to have a height of 44, so no offset there). Every image afterward has a value of 100 added to it, leaving the next coordinates as 128,0; 228,0; 328,0, with the end of each image finishing at coordinates 72,0; 172,0; 272,0; 372;0.

Finish

Below is a snapshot of the finished product. While not the final color scheme and icon colors, it gives you an idea of what our final product has the potential to become.

iosviewoverscreenshot

Dependency Injection for iOS and Android Using Xamarin

Dependency injection is one of my key design patterns that I commonly implement in any architecture. Dependency injection is one of the loosest couplings one can achieve in a design pattern, since the construction and specification of any relationships are managed by the dependency injection container. The common way to supply a relationship is through a property or a constructor. For instance, an iOS controller may look like the following:


public class TestController : UIViewController
{
private IService1 _s1;
private IService2 _s2;

public TestController(IService1 s1, IService2, s2) : base(..) {
_s1 = s1;
_s2 = s2;
}
}

Where IService1 and IService2 are interfaces defined in the dependency injection container. The DI container creates the TestController class instance, and populates the services. Since the typical way to create a controller is to add it to the navigation controller, constructor injection is a great technique for iOS:


var container = DIContainer.Instance;
//At this point, new controller created and services defined
var newController = container.GetInstance();

//this refers to the current UIViewController;
//code below adds the controller to the stack
this.NavigationController.PushViewController(newController, true);

However, constructor injection does not work in Android’s architecture. This is because Android doesn’t expose the activity creation process to the developer. Android does expose the initialization of a controller though, which makes it a more ideal candidate for property injection. Each android activity has a specific lifecycle that it follows, the create method is usually a good place to put code like this. However, because services are often utilized within the create method of the activity, we need something that’s a step sooner than that. I ended up resorting to doing this during the constructor, as in the sample activity below:


public abstract class BaseActivity : Activity
{

protected void CheckForDependencies()
{
var props = this.GetType ().GetProperties ();
foreach (var prop in props) {
if (prop.GetCustomAttributes(typeof(ServiceDependencyAttribute), false).Length > 0) {
//Inject dependency
try
{

object instance = App.Current.Resolver.GetInstance (prop.PropertyType);
if (instance != null)
prop.SetValue (this, instance, null);

}
catch(Exception ex) {
Toast.MakeText (this, "An error occurred: " + ex.Message, ToastLength.Long);
}
}
}
}

public BaseActivity()
{
this.CheckForDependencies ();
}

}

And a sample activity like:


public class AchievementsActivity : BaseActivity
{

[ServiceDependency]
public IErrorHandlerService ErrorHandler { get; set; }

[ServiceDependency]
public IAchievementsLoader Achievements { get; set; }

[ServiceDependency]
public IMessageDialogService Messages { get; set; }

}

The common problem with using inheritance is that you have to implement a custom base class for every different type of activity: list activities, fragments, and every other activity type. Otherwise, you’d have to duplicate the property injection logic. However, inheritance is the best way to address the problem and essentially “wrap” the base functionality.

UITableView Part 2 – DataSources and Sources

In every programming language and operating system, there is always a grid control, which needs data. How the grid gets it data varies slightly; however, conceptually the grid gets the data through a data source. Sometimes the data source is the raw data itself, and sometimes it’s a wrapper around the data, which the wrapper offers some additional functionality. In iOS, there are two ways to bind the UITableView, through a UITableViewDataSource object and a UITableViewSource object. Both forementioned classes, similar in nature, are delegate classes that act as an intermediary between the underlying data and the tableview. In iOS, a delegate is a construct much different from the class that drives the behavior of the tableview. In Xamarin iOS, the UITableViewSource is a class with a bunch of optional methods. Overriding particular methods allow a developer to tap into certain functionality of and receive feedback from the tableview.

This post is going to discuss how to bind to a UITableView, and assumes you are familiar with the basic features of iOS and the UITableView. To begin, in order to use a UITableViewSource for a TableView in Xamarin iOS, follow these steps.

First, create a new class that inherits from UITableViewSource:

public class MySource : UITableViewSource

Next, override the following method:

UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)

The GetCell method is responsible for creating and populating a UITableViewCell that the UI will return to the current user, and may look like the following implementation:

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
	var cell = tableView.DequeueReusableCell ("StringIdentifier");
	if (cell == null)
		cell = new UITableViewCell(UITableViewCellStyle.Default, "StringIdentifier");

	//Load data into cell from data source

	return cell;
}

First we see if a cell has already been created for this identifier. The iOS framework will try to reuse an existing cell if it’s already created. If it isn’t created, then the cell is instantiated and returned. Additionally, the RowsInSection method is used to determine the number of rows in the current section. RowsInSection is useful for grouping of tables (which is supplied in the constructor of the UITableViewController, but that’s for another discussion). When the table is grouped, the RowsInSection method needs to return the number of rows (in integer form) for the given groups at the specified index path (since the NSIndexPath contains the current section and the current data item pointers).

The GetCell and RowsInSection methods are the most critical methods because it controls how the data is loaded in the UI.

There are plenty of other useful methods to know about to. For instance, if you want to handle the click of a row, handle the RowSelected event:

public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
    //DO something

    tableView.DeselectRow (indexPath, true); // iOS convention is to remove the highlight
}

The UITableViewSource has methods for overriding the height of the row, and header/footer (if using grouping), as well as change the current view used for the header and footer. For instance, the view could be changed to use an image as the header and footer, as I wrote about before.

Note that the UITableViewSource class doesn’t retain your data source; you need to store the data in a variable so it can be retrieved through the index path later. Also, note that the source needs to be created for every controller you may want to use it in, leading to a lot of repetition.

Now I’m not one for repetition; I really don’t like the idea of writing boilerplate code just for the sake of writing boilerplate code. Therefore, I decided to create a reusable base class that abstracts most of the functionality away. It takes away a lot of the repetitiveness, while also offering the full functionality. To use it, all you need to do is inherit from Nucleo.UI.BaseUITableViewSource, and override the GetCellIdentifier and PopulateCell methods, and set the Data or GroupedData properties (depending on whether the table is grouped or not). This means you really could define a UITableViewSource like:

public class MySource : Nucleo.UI.BaseUITableViewSource
{
    public override string GetCellIdentifier() { return "My"; }

    public override MyClass PopulateCell(UITableViewCell cell, T dataItem, NSIndexPath path)
    {
        //Cell is already dequeued or created, only populate the cell here
    }
}

The process of creating the cell is abstracted away for you; however, if you are using a custom cell (more on this later), then you can override the CreateNewCell class and return your custom cell, and cast the cell reference in the PopulateCell method. Additionally, all of the grouping functionality is handled for you automatically by setting GroupedData property; RowsInSection and SectionFor methods, all used for grouping, are already wired up.

If you want to view the full code sample, you can do so from here. You can also find my project where I have this code at my Nucleo Mobile bitbucket.org repository.