Type datetime2 is not a defined system type

EF generating wasted db calls

Odd one this! Caused by a fairly innocuous looking

 var result = MyRepository.Select(a => myIds.Contains(a.theirID)).ToList();

It was a two fold effect, datetime2 was being CAST(NULL AS datetime2) AS in the generated SQL therefore at the point where it was being mapped back to entity it was failing a unknown type. The root of the cause was in the blog post. Read it for a nice detailed run at the issue, thanks to the OP :)

Posted in C#, EF4 | Leave a comment

WCF compatible JSON

Object is null when it arrives at WCF method

Its a case issue isn’t it. Json not knowing that parameter “Hello” is the same as “hello” so get that casing right :)

Also constructing JSON in unit tests for simple parameters is erm simple enough to hand crank.

//putting on request stream

Its slightly more complex (well it always trips me up) to serialise an object to json as the name of the object seems to escape with the inbuilt jsonserializer. So add it manually and all your deserialization will pass off fine.

 var oSerializer = new JavaScriptSerializer();
 var jsonbytes = Encoding.UTF8.GetBytes("{ \"nameOfClass\":" + oSerializer.Serialize(myclass)+"}");
Posted in C# | Leave a comment

MVC action filters

Action filters

This is fun, cos apparently I had totally misunderstood where these bad boys come from and there are a few opinions on the interwebs just to add to the mess in my mind :) So they are attributes that are a way of declaratively adding reusable functionality to a controller or action. You get some OOTB and you can implement IFilter types to create your own. The neat thing is they are optional and you won’t muddy your controller with code – so called cross cutting concerns. Your implementing in one place, repetitive reusable code. Its like some kind of nirvana!

The ASP.NET MVC framework supports four different types of filters:

Authorization filters – Implements the IAuthorizationFilter attribute.
Action filters – Implements the IActionFilter attribute.
Result filters – Implements the IResultFilter attribute.
Exception filters – Implements the IExceptionFilter attribute.

So in order to hook into the execution pipeline of an action you override OnActionExecuted to add some custom code to the execution of the method. You override OnActionExecuting as a precondition to the execution of the target method. Finally, you override OnResultExecuting and OnResultExecuted to place your code around the internal step that governs the generation of the method response.

This is ok for controller level but say you wanted to do this for every controller… Well head to the the global.asax.cs file and specifically the RegisterGlobalFilters method. Suprisingly this does what it says on the tin. Really nice post here on an example of the use. I shall be stealing this method to secure a WCF service I wrote (note to self do this when you get in on Monday ;) ) I suppose you could add a HttpModule into your web.config to sneak in there but I’m rapidly heading off the point.

Back on the point … So lets have a quick squiz at what you get for your MSDN subs..

Authorize – checks to see whether the current user is logged in, and matches a provided username or role name (or names), and if not it returns a 401 status, which in turn invokes the configured authentication provider.
ChildActionOnly – used to indicate that the action method may only be called as part of a parent request, to render inline markup, rather then returning a full view template.
OutputCache – tells ASP.NET to cache the output of the requested action, and to serve the cached output based on the parameters provided.
HandleError – provides a mechanism for mapping exceptions to specific View templates, so that you can easily provide custom error pages to your users for specific exceptions (or simply have a generic error view template that handles all exceptions).
RequireHttps – forces a switch from http to https by redirecting GET requests to the https version of the requested URL, and rejects non-https POST requests.
ValidateAntiForgeryToken – checks to see whether the server request has been tampered with. Used in conjunction with the AntiForgeryToken HTML Helper, which injects a hidden input field and cookie for later verification.
ValidateInput – when set to false, tells ASP.NET MVC to set ValidateRequest to false, allowing input with potentially dangerous values (i.e. markup and script). You should properly encode any values received before storing or displaying them, when request validation is disabled. Note that in ASP.NET 4.0, request validation occurs earlier in the processing pipeline, so in order to use this attribute, you must set the following value in your web.config file:

Posted in C#, MVC | Leave a comment

MVC Controller class

Ok what’s behind every controller you write? This is my list of highlights

Lets look at what the class inherits.ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter. A nice wadge of functionality there. Im interested in the various filters. As well that seems to make up the bulk and also gives me a headache/insight into the intended use of the controller class. So much so in fact I’ve dedicated a post to them. Yay me. Its clear this is where the following “on” methods come from.

OnActionExecuted Called after the action method is invoked.
OnActionExecuting Called before the action method is invoked.
OnAuthorization Called when authorization occurs.
OnException Called when an unhandled exception occurs in the action.
OnResultExecuted Called after the action result that is returned by an action method is executed so this method runs after the response is written. Seems to me to be a popular place to put debug type info as you know whats been sent OTW.
OnResultExecuting Called before the action result that is returned by an action method is executed.



New in MVC 3 its a wrapper around ViewData’s KVP for retrieval of data from the store. Both are there to facilitate the controller making data available to the view. Syntax wise I prefer ViewBag’s dynamic approach. So where you would of had ViewData["SomeData"] = List{“hi”,”whats”,”up”}, you now get ViewBag.SomeData = List{“hi”,”whats”,”up”}. In the view it makes for a clean ViewBag.SomeData access. Dynamics deserve a post so how about this one


I nicked this quote from this StackOverflow post (don’t hate me Google) “TempData is a session-backed temporary storage dictionary that is available for one single request. So you get a mechanism to pass data from current request to the next and that’s it. Its worth noting that ViewData won’t persist the data hence the distinction of the two methods.

Posted in C#, MVC | Leave a comment

Adventures in LINQ

What is it, why and just who is she?

The standard query operators allow queries to be applied to any IEnumerable based information source.

Return is based on the type so LINQ to Objects, LINQ to XML, LINQ to DataSets, and all that works on in-memory CLR objects return IEnumerable. For LINQ to SQL, LINQ to Entities which work on Expression Trees to generate SQL commands, the return type is IQueryable.

So be careful here because querying on an IEnumerable will do the equivalent of “select *” and filter the result.

IEnumerable<Product> products = dataprovider.GetProducts();
var defunct = products.Where(prd=>prd.EndOfLine);

However if you have a IQueryable return then because of the Expression Tree the compiler can form a much more economic query. In this case including “WHERE EndOfLine is True”.

IQueryable<Product> products = dataprovider.GetProducts();
var defunct = products.Where(prd=>prd.EndOfLine);

Good quote from this really nice article
As you can see, IQueryable contains a property of type Expression, this is the base type from which most variants of Expression are derived. It is designed to hold the expression tree associated with an instance of IQueryable. It is a data structure equivalent to the executable code found in a query expression.

Posted in Uncategorized | Leave a comment

Android parcelable

Seriously, really, that much effort wow ok then welcome to parcelable

It was all going so well until I wanted to pass some complex data from one activity to another. The mechanism to do this requires an object (your parcel) to add to the intent you create to transition to the next activity.

goToNextActivity.putExtra ("name",parcel);

The pain in the arse bit is creating your parcel. Now this is my first hack at getting this and I really want to not re-create the object that im putting in the parcel then again the other side. But for now…

import android.os.Parcel;
import android.os.Parcelable;
public final class SettingsAndCategoriesParcel implements Parcelable {
    public int UserId;
    public int RoleId;
    public int QuestionId;
    public static final Parcelable.Creator<SettingsAndCategoriesParcel> CREATOR = new
Parcelable.Creator<SettingsAndCategoriesParcel>() {
        public SettingsAndCategoriesParcel createFromParcel(Parcel in) {
            return new SettingsAndCategoriesParcel(in);
        public SettingsAndCategoriesParcel[] newArray(int size) {
            return new SettingsAndCategoriesParcel[size];
    public SettingsAndCategoriesParcel() {
    private SettingsAndCategoriesParcel(Parcel in) {
    public void readFromParcel(Parcel in) {
        UserId = in.readInt();
        RoleId= in.readInt();
        QuestionId = in.readInt();
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub

So whats all this about. Well when you implement Parcelable you get the task of coding the read and write methods to compliment your object. The joy. DescribeContent I havent implemented nor seen an error nor seen anyone else do it… so its not especially complex its just getting the basics of the constructor and the parcels in and out. Have fun..

Posted in Android | Leave a comment

Android context

How do I get the context

Its blindingly simple although for the life of me I found tracking down getApplicationContext() hard. /ho hum

Posted in Android | Leave a comment

Using the android secure area

Secure area sounds like something destined to fail to me, but that’s just me being doubting :) Hopefully it does exactly what it says on the tin and provides an area like the i(jesus)phone to store sensitive data.

The read/write is pretty simple, keep an eye for your Context.MODE_PRIVATE and job done.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class secure {
	public static void save(String filename, String data, Context ctx) {
		FileOutputStream fos;
		try {
			fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
	public static String readText(String filename, Context ctx) {
		FileInputStream fis;
		StringBuffer fileContent = new StringBuffer("");
		try {
			fis = ctx.openFileInput(filename);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = fis.read(buffer)) != -1) {
				for (int i = 0; i < length; i++) {
					fileContent.append((char) buffer[i]);
			return fileContent.toString();
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		return "";
Posted in Android | Leave a comment

Android app activity stops launching in eclipse emulator

Don’t you hate it when things that were working fine yesterday stop working today? Do a team of gremlins appear overnight to bash your code stripping activity ids as they go? Well if your activities stop launching as you move round your app the answer is no.

The very simple answer is you need to do a clean. Eclipse->Project->Clean and your app will once again know its activity ids.

Posted in Android | Tagged | Leave a comment

Which javascript files for MVC 3 client validation

Simple question with the answer hidden deep in many posts that I spend time so much time googling im bloomin gonna put it here. Insert your favourite CDN :)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"           type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"      type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.7/jQuery.Validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
Posted in JQuery, JavaScript, MVC | Leave a comment