Generic interfaces and methods in the data access layer
Generics have been in C# since v2.0 but it's only been recently that I've started to make use of them and appreciate their elegance and application.
I've been working on a conceptual CMS and to speed things along I'm using in-memory storage in the form of List<Type>. This is a concrete implementation of my different ITypeManager interfaces. I quickly realised that for any given type in my object model I would need various but common CRUD operations and so all these common operations needed to be in each of the interfaces for my various and numerous object types.
Generics to the rescue
Generics provided a much need solution to my repeating the methods in the interfaces with the same signature but just returning differing types. I created a general IManger interface
public interface IManager {
T GetSingleById(Guid id);
IEnumerable GetManyByParentId(Guid parentId);
T Save(ref T t);
}
which each of the ITypeManager interfaces would implement
public interface ITypeManager: IManager<Type> {
// Additional methods required by the type specific manager
}
So far I've managed to vastly reduce the amount of code that I have to write but (genuinely to my surprise) Visual Studio 2010 gave me even less work to do when creating the concrete implementations of the ITypeManager interfaces by generating the stub methods with the correct types!
public class TypeManager: ITypeManager {
public Type GetSingleById(Guid id) {
// type specific implementation
}
public IEnumerable<Type> GetManyByParentId(Guid parentId) {
// type specific implementation
}
public Type Save(Type t) {
// type specific implementation
}
}I was impressed both with the small amount of code that I had to write and the code generation tools within Visual Studio 2010, so I looked for more places where generics could help me to write less code (and, as it turned out, make my code more maintainable).
Generic methods
I can honestly say that until this past week I hadn't written a single generic method. In fact I had to enlist the help of the very helpful guys over at Stackoverflow.com to get this right.
I quickly identified that each and every one of my concrete implementations of ITypeManager included very similar code and LINQ queries which had to be prime targets for generic methods.
...
public Type GetSingleById(Guid id) {
return (from i in this.listOfItems where i.Id == id select i).SingleOrDefault();
}
...
The example above was quickly moved into a new static method of a static class (pass in the list and the id and get the item or null if it doesn't exist).
public static class Manager {
public static T GetSingleById(List items, Guid id) {
return (from i in items where i.Id == id select i).SingleOrDefault();
}
}Initially I had some issues with the where clause; specifically it wouldn't compile since object doesn't have an Id property for the where clause to operate on. Since all my object types have an Id property, I moved this into a base class HasId with this property and added a base type condition to the method.
public static class Manager {
public static T GetSingleById(List items, Guid id) Where T: HasId {
return (from i in items where i.Id == id select i).SingleOrDefault();
}
}Now all I had to do was to call this static method from within my concrete class passing in the in-memory list that it was using for storage.
Next I created a second base class HasIdAndParentId subclassing HasId by adding a new ParentId property which all but my root object types subclass. This enabled me to add generic methods to my static class like
public static class Manager {
public static T GetSingleById(List items, Guid id) Where T: HasId {
return (from i in items where i.Id == id select i).SingleOrDefault();
}
public static IEnumerable GetManyByParentId(List items, Guid parentId) Where T: HasIdAndParentId {
return from i in items where i.ParentId == parentId;
}
}and in turn call these from my concrete classes.
So why go to all this bother? Well firstly, I have written less code; for a single example it looks like I written far more code but, I also managed to add a method to my static class to save an object (does it already exist?, if so update it, if not create it, re-query the data store using the primary key and return the object) and replaced 20 or so lines of code in each of my concrete classes with a single call to my static class. And, secondly my code as become more maintainable since all the LINQ is in one file. If, say, I add a new property to HasId called IsRetired so that I can skip records that have been retired; I can implement this in all my concrete classes in one place.
public static class Manager {
public static T GetSingleById(List items, Guid id) Where T: HasId {
return (from i in items where i.Id == id && i.IsRetired == false select i).SingleOrDefault();
}
public static IEnumerable GetManyByParentId(List items, Guid parentId) Where T: HasIdAndParentId {
return from i in items where i.ParentId == parentId && i.IsRetired == false;
}
}That's what I call maintainable.


Fuel consumption. Part II
In Part I of this series we decided what our application should do and what data we needed to collect for our application to work, now, we need to turn our attention to how we actually collect the information.
We initially embarked on this project to use ASP.net MVC v2 so clearly we'll be building a web interface but is an application that records drivers fuel really useful on the web? Well, it is if you consider using a mobile phone to browse the web, drivers can record the data directly from the forecourt (or from the adjacent supermarket carpark).


Fuel consumption. Part I
We've decided to embark on a sample web application using ASP.net MVC 2 and .net framework v4, written in C# v4 as a way to develop a template solution for future reference.
We realise that some of the technologies used will be superceded but this is about the application structure and development approach that we use, which (until the next development revolution) should remain valid.
So, where to begin? Well, we've decided that a simple web site to record fuel use and calculate fuel consumption should require all of the UI, business logic, data logic and, data storage functionality to enable us to have a understandable end-to-end sample project.
Firstly we need to outline what our application will actually do and record the rules and formulae that the application wil adhere to.
The primary goal of our application is to provide drivers with a fuel consumption figure for their vehicle. It is quite common during development projects to actually forget what the application is supposed to be doing; it's unlikely in this simple scenario but, when projects run into months and years of development it's suprisingly easy to lose sight of the actual target of the project.
Given that we now know what we are trying to achieve we need to work out how to actually achieve our goal, not in terms of code or application structure but in terms of what information do we need to achieve our goal or, more specifically, how do we calculate the fuel consumption of a vehicle?
Well, as sample applications generally go, our calculations are fairly simple; fuel consumption figures are stated in distance per volume so to calculate the fuel consumption of a vehicle we need to know how far it has travelled (d) and how much fuel it used to travel that distance (f) giving it's fuel consumption as d / f.
Now we need to work out how we measure the distance that the vehicle has travelled and how much fuel it used to travel that distance. Since we are only providing the application to make the calculations surely we don't need to worry about these details? Well, yes and no; for our application to work we just need the raw data but, for our application to be useful we need to provide a way for the user to only have to provide easily obtainable information.
The mechanism that this sample application will use is to record the total distance that the vehicle has travelled and the amount of fuel required to put the vehicles fuel level to a known state; in simple terms, we record the odometer reading and the amount of fuel required to fill the tank. This allow us to calculate the two pieces of raw data that we require for our calculation.
Sample recorded data| Odometer | Distance | Fuel Added |
|---|
| 0 | 0 | 30 |
| 300 | 300 | 30 |
| 400 | 100 | 10 |
| 650 | 250 | 30 |
| 950 | 300 | 25 |
As we can see from the sample data above, if the driver records the odometer reading and how much fuel was required to fill the fuel tank we know the distance that the vehicle has travelled (the difference between the previously record odometer reading and the current odometer reading) and the volume of fuel used to travel this distance (the amount of fuel that had to be added to refil the fuel tank). Obviously calculations can only be made when we have a record of the previous odometer reading (when the fuel tank was full), the current odometer reading and the amount of fuel added to refil the tank but, this does not stop the driver adding fuel without filling the fuel tank as long as the addition of this fuel is recorded.
Sample recorded data| Odometer | Distance | Fuel Added | Tank Filled |
|---|
| 0 | 0 | 30 | yes |
| 300 | 300 | 30 | yes |
| 400 | 100 | 10 | yes |
| 650 | 250 | 30 | yes |
| 950 | 300 | 25 | yes |
| 1150 | 200 | 10 | no |
| 1200 | 50 | 15 | yes |
We can see from the table above that at 1150 miles the driver added 10 litres of fuel but this didn't fill the tank but at 1200 miles the driver added 15 litres of fuel and this did fill the tank. We can still calculate the fuel consumption between 950 miles and 1200 miles; 250 miles travelled and a total of 25 litres of fuel added.
Summary
We decided to write an application that will calculate a vehicles fuel consumption. We discovered the formula for calculating a vehicles fuel consumption but discovered that it is not practical for the driver to access this raw data so we discovered how to calculate this raw data from data that the driver can access and noted how this will impact the availability of the fuel consumption results.


Useful extension methods
This method is useful for hiding plain text; note that it is not a secure encryption method, to the casual passer-by the output will be meaningless, to the seasoned hacker it will be decrypted in seconds.
Note that by using 129 as the key all the output characters from using [a-zA-Z0-9] as input characters will be valid XML.
If you run this method on string A to get string B then run the method on string B you will be returned string A; it is fully reversible.
public static string Xor(this string text)
{
int key = 129;
StringBuilder inSb = new StringBuilder(text);
StringBuilder outSb = new StringBuilder(text.Length);
char c;
for (int i = 0; i < text.Length; i++)
{
c = inSb[i];
c = (char)(c ^ key);
outSb.Append(c);
}
return outSb.ToString();
}


Decoupling data access in C#
This is nothing new; it's just a reminder for me and anyone else who want to bookmark this page.
The concept is to decouple the UI from the BLL and the BLL from the DAL to enable the UI to be updated and deployed independently of the BLL or to allow a new implementation of the UI (Winforms, Webforms, MVC, etc.) and to allow new implementations of the DAL without the BLL noticing.
So, easy things first; the UI. Simply ensure that ALL the business logic is contained within the BLL with a completely and descriptively documented API so the UI ONLY deals with presentation. This isn't so much decoupling (the UI will still have a reference to the concrete implementation in the BLL) but more encapsulating; still it make for good practice.
Now, the DAL. In the DAL we need to seperate the logical methods i.e. GetProduct, from the implementation i.e. SELECT * FROM Product. This is achieved using interface programming and a bit of reflection in the BLL and interface implementation in the DAL.
The process is:
- UI calls static methods within BLL
- BLL uses configuration settings to initialize a concrete implementation of an interface
- BLL calls methods against the concrete implemention in the DAL
- The DAL returns data to the BLL
- The BLL processes the data from the DAL and returns the processed data to the UI
Some code then; first in the DAL.
namespace Demo.DAL;
{
using System;
using ...;
public interface IProductManager
{
Product GetProduct(int id);
}
}
namespace Demo.DAL.Sql
{
using System;
using ...;
public class SqlProductManager : IProductManager
{
public Product GetProduct(int id)
{
Product product = new Product();
// do SQL stuff with the product
return product;
}
}
}
namespace Demo.DAL.Memory
{
using System;
using ...;
public class MemoryProductManager : IProductManager
{
pubic Product GetProduct(int id)
{
Product product = new Product();
// do MEMORY stuff with the product
return product;
}
}
}
The above code defines an interface IProductManager and two concrete implementations of the interface; SqlProductManager and MemoryProductManager. Since both classes implement the same interface we can write code in the BLL against the interface without any care of how it's implemented in the DAL.
namespace Demo.BLL
{
using System;
using Demo.DAL;
using ...;
private static IProductManager dalManager;
static ProductManager()
{
// initialize dalManager
}
public static class ProductManager
{
public static Product GetProduct(int id)
{
return dalManager.GetProduct(id);
}
}
}
So far, so good; we have a nice static method to call from our UI in the BLL that hides all implementation from the UI and we're programming against an interface so the BLL doesn't care about the implementation in the DAL. The BLL does however care about which implementation in the DAL is used; it's up to the BLL to tell the DAL to use either the Sql implementation or the Memory implementation.
It's time for configuration to step in, and yet another set of classes. We can instruct the BLL to use a particular implementation of the DAL interfaces in our application or web configuration file. In the BLL we use a bit of reflection to initialize an instance of the particular type we require. Since the type implements the interface we know all the calls to dalManager.methodName will be honored.
We could (but I don't recommend it) put a bunch of appSettings into the config file; but it's much cleaner to use a custom configuration section and a static manager to access it.
namespace Demo.Configuration
{
using System;
using System.Configuration;
using ...;
public class ProductManagerConfiguration : ConfigurationSection
{
[ConfigurationProperty("type", IsRequired = true)]
public string Type
{
get { return (string)this["type"]; }
}
}
}
namespace Demo.Configuration
{
using System;
using System.Configuration;
using ...;
public static class ConfigurationManager
{
public static ProductManagerConfiguration ProductManagerConfiguration
{
get
{
return (ProductManagerConfiguration)ConfigurationManager.GetSection("demo/productManager");
}
}
}
}
Next we add our configuration section to our application or web config file.
Finally we need to update the BLL.ProductManager class so that dalManager is initialized correctly.
namespace Demo.BLL
{
using System;
using Demo.DAL;
using ...;
private static IProductManager dalManager;
static ProductManager()
{
// initialize dalManager
if (dalManager == null)
{
try
{
ProductManagerConfiguration productManagerConfiguration = ConfigurationManager.ProductManagerConfiguration;
Type type = Type.GetType(productManagerConfiguration.Type);
dalManager = (IProductManager)Activator.CreateInstance(type);
}
catch
{
// initialization failed
}
}
}
public static class ProductManager
{
public static Product GetProduct(int id)
{
return dalManager.GetProduct(id);
}
}
}


Living with the HTC HD2. Part II
Communication is what a phone should be about but when it comes to smart phones communication is really what a phone should be about. I want my phone to communicate with my GSM network for voice, with (preferably) my 3G or my GPRS network for mobile data and with my WiFi network (when available) for 'local' data. I'd also like it to be able to communicate with my VPN over WiFi or 3G and finally I'd like it to be able to communicate with my PC over USB.
Is all this reasonable? Well, I think so and that's why I have a smart phone. Now, down to the nitty gritty; how do I achieve all this?
The GSM and 3G / GPRS connections are no brainers; turn on the phone and we're done. Configuring a WiFi connection is straight forward too; it's just like any Windows based PC. But, if I've got WiFi coverage (and I want a data connection) how do I configure the phone to use this connection in preference to 3G / GPRS? Seriously, this is a question ... how? Next, when I want a VPN connection I can configure this in the connection settings and over 3G / GPRS it works; but when I then connect to my PC using USB I cannot use Active Sync, I have to actually delete the VPN connection on the phone to get Active Sync working!
Answers please!


ASP.net MVC ActionFilter and Redirect
Apply this filter to Methods that require authorisation
[AttributeUsage(AttributeTargets.Method)]
public class AuthAttribute : ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!Authorised) /* whatever Authorised does */
{
filterContext.Result = ((BaseController)filterContext.Controller).Redirect303(
"Login", "Home", new {
returnAction = filterContext.RouteData.GetRequiredString("action"),
returnController = filterContext.RouteData.GetRequiredString("controller"),
returnData = filterContext.RouteData.Values.ContainsKey("id") ? filterContext.RouteData.Values["id"] : string.Empty });
}
}
}
Then in
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Login(string returnAction, string returnController, string returnData)
{
/* blah */
string returnUrl = Url.Action(returnAction, returnController, new { id = returnData });
/* blah */
}
Put returnUrl into a hidden form input in Login.aspx and then in
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(FormCollection form)
{
string returnUrl = Url.RouteUrl(new { controller = "Home", action = "Index" });
if (!string.IsNullOrEmpty(form["returnUrl"]))
{
returnUrl = form["returnUrl"];
}
/* blah */
// redirect to the original page
return Redirect303Url(returnUrl);
}


ASP.net MVC reminders
To get the 'usual' HttpRequest object (rather than an HttpRequestBase object). This is usually required when calling methods (or services) provided by non-MVC ASP libraries.
System.Web.HttpContext.Current.Request


Living with the HTC HD2. Part I
The HTC HD2 is an amazing Windows Mobile 6.5 Smartphone. There are plenty of resources around the 'net to tell you all about its specifications and functions but I have one and there's nothing better than first-hand experience to find out how it really works in the real world.
Firstly it's big, really BIG!. I'd go so far as to say that it isn't pocket sized; not trouser pockets in any case. It'll live quite comfortably in your jacket or shirt pocket though but since you'll want to be playing with it almost constantly it doesn't really matter.
Secondly it's slick. The HTC interface is beautiful to look at and a pleasure to use. Everything just works how you might expect it to work, everything is where you might expect it to be, it's quite a feat of engineering. If you want to find out just how good the HTC interface is you can change it to the Default Windows Mobile interface; that's awkward, clunky and certainly not intuitive and if you really want to punish yourself there always the Windows Smartphone interface.
So have I discovered anything that I don't like about the HTC HD2? Well, yes. Firstly there's the fact that it's a touch screen, but I just said that the interface is really nice didn't I? Yes, it is, but that isn't what I mean; finger friendly isn't always ear friendly. I managed to switch on the speaker phone mid-conversation today; only embarrassing as it happened since I was walking the street having a personal conversation but, potentially damaging. There is supposed to be a method of detecting when you raise the phone to your ear which disables the touch screen until you lower the phone from your ear and, to be truthful, it generally works but one event in the first week? Even that seems a little too frequent for me but only time will tell.
The second thing that I've noticed is that the Digital Compass just doesn't seem to work; I've tried it in several places and it always complains about there being too much interference, and what is the move in a figure of 8 action supposed to do? I've stood there looking quite the pratt on several occasions and the phone just seems to ignore that action completely. Am I doing something wrong?


PRG & Nokia Series 40 Browser
In ASP.net MVC (or any other MVC framework) using the PRG pattern is quite common; the browser sends a POST to the controller, the controller returns a redirect and the browser GETs the redirect URI - simple, effective and widely used.
However, the Nokia Series 40 browser doesn't quite behave properly when using the standard redirects in ASP.net MVC; the ASP.net MVC RedirectToAction method sends a HTTP status code 302 to the browser and expects the browser to GET the URI, the Nokia Series 40 browser rePOSTs the data from the original POST to the new URI. In ASP.net MVC controller actions have to be told to accept a HTTP POST (by default they only accept a HTTP GET) and since the browser has been asked to GET from the URI in the redirect there's every chance that the controller won't accept the POST. So the controller sends another redirect and around the loop we go again!
The solution is to send a HTTP status code 303 to the browser, the Nokia Series 40 browser correctly GETs the URI in this case.
So now the problem moves to ASP.net MVC but thankfully the solution is straight forward; create a new class that inherits ActionResult and set the HTTP status code of the response to 303 and the response redirect location property to the desired GET URI.
public class Redirect303 : ActionResult
{
private string url = string.Empty;
public Redirect303(string url)
{
this.url = url;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 303;
context.HttpContext.Response.RedirectLocation = url;
}
}
It is clear from the code that the browser will be sent a HTTP status code of 303; just what the Nokia Series 40 browser needs but this class doesn't support the nice URI builder parameters that the MVC RedirectToAction method does. To make this class 'nice to use' just add public properties to your base controller class (you do have a base controller class that all your controllers inherit from don't you) that take the desired parameters and use the Url.Action method to get the MVC framework work out the URI for you.
public Redirect303 Redirect303(string actionName)
{
return new Redirect303(Url.Action(actionName));
}
public Redirect303 Redirect303(string actionName, object routeValues)
{
return new Redirect303(Url.Action(actionName, routeValues));
}
public Redirect303 Redirect303(string actionName, string controllerName)
{
return new Redirect303(Url.Action(actionName, controllerName));
}
public Redirect303 Redirect303(string actionName, string controllerName, object routeValues)
{
return new Redirect303(Url.Action(actionName, controllerName, routeValues));
}
There are actually 8 overloads for Url.Action so it wouldn't take long to build wrappers for all of them; once done you can forget RedirectToAction and use Redirect303 instead.

