Coding and stuff

Just another site


setup an alias

dnvm alias default486 1.0.0-beta4 -arch x86

use the alias

dnvm use default486 -p

DbContext Error

To get detailed information about errors that the DbContext Save has raised: 

public static class DataExtensions
public static int SaveChangesWithErrors(this DbContext context)
return context.SaveChanges();
catch (DbEntityValidationException ex)
StringBuilder sb = new StringBuilder();

foreach (var failure in ex.EntityValidationErrors)
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);

throw new DbEntityValidationException(
"Entity Validation Failed - errors follow:\n" +
sb.ToString(), ex
); // Add the original exception as the innerException

Media Formatter – MVC 6

I saw a post that said that the MediaTypeFormatter has now moved to IInputFormatter and IOutputFormatter

There’s a link to an example of someone (rynowak) using an output formatter here:

Visual studio 2015, 5, MVC6, c# 6 … initial views and the 30 second tour! …

I’ve spent a little time with VS 2015 (RC) now. There is HUGE amount that has changed.

c# 6 … 

For me the biggest win here is (and this is a big win):

Null conditional operators…


A list of some of the changes can be found here:

You can have a quick play with (most of) the features at:

Visual studio 2015

For me the biggest win here is:

lambda debugging .. and using lambdas in the immediate window. (another huge win)

They (MS) look like they are trying to

(with MVC) bower, gulp, grunt NPM

These packages bring a lot of power, however they also bring a fair mount of learning, and hassle. This means that rather spending 5 minutes putting in a script library, you can now spend an hour doing it!!! That said, you can do cool stuff with it along the way. It just seems to me that this will result in additional technical debt for project initialization.

Publishing… oh dear. Is MS under the mistaken belief that developers actually use the publish feature. Do they not appreciate CI? I guess that I’ll work this out eventually, but at the moment its like wading through treacle.

Huge changes to the syntax, to html tag helpers to, to config files, DI etc.


Mvc now coexists with webapi – cool

No more “goto view” – how dissapointing. (but possibly because of coexisting with webapi?)

No more “Action”. This has been replaced by web components.

Note the comments about bower etc, and publishing from the section above.


I’ve not looked at the latest version of this yet, but I see that with the upcoming EF7, the intention is to drop EDMX files, with a shift towards code first. I’ve found code first fairly easy to use, however confusion can arise around the data annotations vs fluent api  – read up on the views of Julia Lerman. I don’t really like the “view” implementation. It’s also easy to make a really bad data schema using code first…. creating hundreds of properties with nvarchar(max). I also really don’t like the MS implementation of Many to Many relationships with Entity Framework.

Globbing patterns (things like **)

Globbing patterns

These are used in things like Gulp/Grunt

From the Grunt website:

It is often impractical to specify all source filepaths individually, so Grunt supports filename expansion (also know as globbing) via the built-in node-glob and minimatch libraries.

While this isn’t a comprehensive tutorial on globbing patterns, know that in a filepath:

  • * matches any number of characters, but not /
  • ? matches a single character, but not /
  • ** matches any number of characters, including /, as long as it’s the only thing in a path part
  • {} allows for a comma-separated list of “or” expressions
  • ! at the beginning of a pattern will negate the match

For more information about globs, see:

Finding foreign keys…

sp_fkeys ‘dataitems’

SQL Collation

Find the collation on a table (useful for excel imports)
SELECT, col.collation_name
sys.columns col
object_id = OBJECT_ID(‘ImportConcepts’)

Change the collation where necessary:
ALTER TABLE ImportConcepts



spreadsheets with opendocument format

Xlsx files are basically zip files.

You’ll need to add the following using statements:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

(additionally you’ll need to add references to WindowsBase (for the compression), and DocumentFormat.OpenXML which can be downloaded from the open xml sdk:

Basic spreadsheet parsing for the openDocument standard can use with DOM or SAX.

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(physicalPath, false))
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
foreach (WorksheetPart wsp in workbookPart.WorksheetParts)
SheetData sheetData = wsp.Worksheet.Elements().First();

foreach (Row row in sheetData.Elements())
Score s = new Score();
// workbook needs to be passed through as spreadsheet strings are not stored in the cell, but a separate lookup table.
s.ScoreName = row.getScoreName(workbookPart);
s.ScoreValue = row.getScoreValue();

The biggest thing to notice is that strings are stored in a different location, and you you’ll end up wondering why you always get back “0”.

public static double getScoreValue(this Row r)
double cellValue = -1;

Cell c = (Cell)r.ElementAt(1);
cellValue = double.Parse(c.CellValue.Text);
return cellValue;

public static string getScoreName(this Row r, WorkbookPart workbookPart)
string cellText = string.Empty;
Cell c = (Cell)r.ElementAt(0);
if (c != null && c.DataType != null && c.DataType == CellValues.SharedString)
int id = -1;
Int32.TryParse(c.InnerText, out id);
var item = GetSharedStringItemById(workbookPart, id);
if (item.Text != null)
cellText = item.Text.Text;
else if (item.InnerText != null)
cellText = item.InnerText;
else if (item.InnerXml != null)
cellText = item.InnerXml;
return cellText;

public static SharedStringItem GetSharedStringItemById(WorkbookPart workbookPart, int id)
return workbookPart.SharedStringTablePart.SharedStringTable.Elements().ElementAt(id);

Accessing via SAX, would be:

using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(product.SystemFileName, false))
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
var sheetCount = workbookPart.Workbook.Sheets.Count();
foreach (WorksheetPart wsp in workbookPart.WorksheetParts)
var columnCount = wsp.Worksheet.Descendants().Count();
var rowCount = wsp.Worksheet.Descendants().Count();
var cellCount = wsp.Worksheet.Descendants().Count();

OpenXmlReader reader = OpenXmlReader.Create(wsp);
string text;
while (reader.Read())
text = reader.GetText();
System.Diagnostics.Debug.WriteLine(text + "");

For more information about these methods, see the example at MSDN:

Alternatively there are several thirdparty libraries (like: or there is the ever present OLEDB or SSIS.

Parsing via OLEDB would be something like:
private static DataTable ParseOldDb(string physicalPath)
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;data source='" + physicalPath + "';Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\" ";
string cmd = "select * from [sheet1$]";
var dt = new DataTable();

using (OleDbConnection cn = new OleDbConnection(conStr))
DataTable schema = cn.GetSchema();

using (OleDbDataAdapter ad = new OleDbDataAdapter(cmd, cn))
return dt;

JsonCamelCaseFormatter (hows that for an ironically cased title)

In the test web api projects I’ve been adjusting the formatting sligtly in the Startup file (configuration method):

var config = GlobalConfiguration.Configuration;
var xmlFormatter = config.Formatters.XmlFormatter;

var jsonFormatter = config.Formatters.JsonFormatter;
var JsonmediaTypeformatter = System.Net.Http.Formatting.MediaTypeFormatter.GetDefaultValueForType(typeof(JsonMediaTypeFormatter));

JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

jsonFormatter.SerializerSettings = jsonSettings;

Its even appearing in umbraco now!
I was pleased to see the inclusion of the [JsonCamelCaseFormatter] attribute in umbraco (add to the class of a webAPI0.

umbraco 7.2 Custom Sections (part of developer section)

a bit of a custom section in angular (it doesn’t do much), but it does show how to create a custom section in v7 with angularjs.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting;
using System.Text;
using System.Web;
//using umbraco.businesslogic;
using umbraco.BusinessLogic.Actions;
using umbraco.interfaces;
using Umbraco.Core.Services;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.Trees;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web.WebApi.Filters;
using umbraco;
using umbraco.BusinessLogic.Actions;

// note that this relates to:
–+-umbAltFileEditor (got from the plugincontroller attribute area name)
——-+ umbAltController (got from the tree attribute string alias)

[Tree("developer", "umbAltController", "umb alt controller")]
public class umbAltController : Umbraco.Web.Trees.TreeController

protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
// check if we're rendering the root node's children
if (id == Constants.System.Root.ToInvariantString())
// empty tree
var tree = new TreeNodeCollection();

var path = HttpContext.Current.Server.MapPath("~/AngularJSViews");
var folder = new DirectoryInfo(path);

foreach (FileInfo fi in folder.GetFiles())
var fileitem = this.CreateTreeNode(fi.FullName, "-1", queryStrings, fi.Name, "icon-truck", false);

return tree;
throw new NotSupportedException();

protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
// create my menu item "Import"
var menu = new MenuItemCollection();
// duplicate this section for more than one icon
menu.DefaultMenuAlias = ActionNew.Instance.Alias;
return menu;


package.manifest (/app_plugins/umbaltfileeditor/package.manifest):
javascript: [

angular controller (/app_plugins/umbaltfileeditor/BackOffice/umbAltController/umbAltFileEditorController.js):

'use strict';
(function () {
//create the controller
function umbAltFileEditorListController($scope, $routeParams, $http) {
//set a property on the scope equal to the current route id
$ = $;
$scope.message = "fred1";

//register the controller
angular.module("umbraco").controller('umbAltFileEditorListController', umbAltFileEditorListController);


Thanks in part to the work of:
…. and I want to have a read of this one too:

Blog at | The Baskerville Theme.

Up ↑


Get every new post delivered to your Inbox.