Creating a SharePoint CSOM ClientContext with an authentication cookie

There are a few ways to use CSOM to authenticate to SharePoint. Some of those include:

- Using an AccessToken (OAuth2/SP2013 app model)
- With the SharePointOnlineCredential helper class where you supply a username and password

Now, I wanted to do neither of these things. In my case, I had already logged into SharePoint, and had a FedAuth and rtFa cookie available to me and wanted to construct a ClientContext from those. It took me a while to work out – skip to the end for the code :-)

Wictor Wilen did some work in this area a few years back with his MsOnlineClaimsHelper class. I tried to follow his methods to form my ClientContext by using a CookieContainer to add the FedAuth cookie to ClientContext WebRequest objects, and applying a UserAgent header, and so on…but was consistently met with a 403 response from SharePoint.

Then I came across a post comparing MsOnlineClaimsHelper with the SharePointOnlineCredentials class – which helpfully pointed out that the latter was a supported replacement and should be used. The SharePointOnlineCredential class makes CSOM really trivial to use with a username and password:

SecureString pw = new SecureString();
foreach (char c in "mypassword".ToCharArray())
context.Credentials = new SharePointOnlineCredentials("", pw);

The crucial point is that at some point along the line, the SharePointOnlineCredentials class converts a username and password into a FedAuth cookie, and it’s the process of supplying the FedAuth cookie in ClientContext web requests that I was having trouble implementing myself. So at this point I opened up the JetBrains dotPeek decompiler for the Microsoft.SharePoint.Client.Runtime.dll assembly, and found the SharePointOnlineAuthenticationModule which did exactly that, in the GetSpoAuthCookieAndUpdateRequest method:

private bool GetSpoAuthCookieAndUpdateRequest(WebRequest request, SharePointOnlineCredentials spoCredentials, bool preAuthentication)
string uriString = request.RequestUri.ToString();
int length1 = uriString.IndexOf('?');
if (length1 > 0)
uriString = uriString.Substring(0, length1);
int length2 = uriString.IndexOf('#');
if (length2 > 0)
uriString = uriString.Substring(0, length2);
int length3 = uriString.IndexOf("/_vti_bin", StringComparison.OrdinalIgnoreCase);
if (length3 > 0)
uriString = uriString.Substring(0, length3);
int length4 = uriString.IndexOf("/_api", StringComparison.OrdinalIgnoreCase);
if (length4 > 0)
uriString = uriString.Substring(0, length4);
Uri url = new Uri(uriString);
string authenticationCookie;
if (preAuthentication)
authenticationCookie = spoCredentials.GetAuthenticationCookie(url, false, true);
if (string.IsNullOrEmpty(authenticationCookie))
authenticationCookie = spoCredentials.GetAuthenticationCookie(url, true, true);
authenticationCookie = spoCredentials.GetAuthenticationCookie(url, true, true);
if (string.IsNullOrEmpty(authenticationCookie))
return false;
request.Headers[HttpRequestHeader.Cookie] = authenticationCookie;
return true;

The important bit here is just the single line:
request.Headers[HttpRequestHeader.Cookie] = authenticationCookie;

Previously I had tried to set the cookies via a CookieContainer object, which didn’t work (I got 403 errors). I don’t know why, but setting the cookie directly via the Cookie header works.

Now in our case we have both a FedAuth and an rtFa cookie so we can put it all together like this:

ClientContext cc = new ClientContext(spSiteUrl);
cc.ExecutingWebRequest += (object sender, WebRequestEventArgs e) =>
    e.WebRequestExecutor.WebRequest.Headers[HttpRequestHeader.Cookie] = "FedAuth=" + _fedAuth + ";rtFa=" + _rtFa;

By trial and error I found that naming the cookie FedAuth and not SPOIDCRL – as it’s named in the SharePointOnlineCredential code – was required. Also, without passing the rtFa cookie, I got 403 errors.

Scaffolding a modern web application with ASP.NET Core

This post is a walkthrough of putting together a new application in the latest web technologies. Perfect for starting a new project! It’s incredibly easy with the new ASP.NET Core SPA (single-page application) templates.

The stack in use is as follows:

  • Visual Studio 2017 or Visual Studio Code (optional, but nice for intellisense, debugging etc)
  • TypeScript (extends JavaScript with features like classes and types)
  • React (client library for rendering your UI) and Redux (for handling state, allowing debug features like time travel)
  • Webpack (for bundling/minifying your scripts, and hot module replacement)
  • ASP.NET Core – letting us write our server in lovely C#! (Notably, server pre-rendering is available due to the AspNetCore.SpaServices assembly which calls into Node to execute scripts on the server)

Firstly you need to install the .NET Core SDK. The current version is 1.1. You can either install Visual Studio (if you are licensed for that) or just the command line tools. You can later install Visual Studio Code, the free cross-platform Visual Studio, if you like.

Next you need to install Node. If you’ve already got it, update it to the latest version. I found that I had an old version and I was getting bizarre errors until I realised I had to uninstall and reinstall. Node seems like an odd requirement since it’s a web server in itself, and aren’t we using IIS? The reason it’s needed is because we can take advantage of its extensive library of packages, and additionally, ASP.NET Core can use Node silently in the background to execute JavaScript, on the server, for pre-rendering the page. This can be done when you’re using React or Angular 2.

Now comes the fun part. We will use the ASP.NET SPA Services (Single-page application) generator to produce a ready-to-go, pre-configured application based on the client library we want. So, install both SPA Services and the Yeoman generator:

npm install -g yo generator-aspnetcore-spa

Now create a folder for your application, cd into it, and run the generator:

cd c:\appdirectory
yo aspnetcore-spa

You’ll be given a choice about which framework to use in your project:

In my case I picked React with Redux. It then asks if you want the ‘project.json’ or ‘csproj’ project format. csproj is the one to go with if you’re using Visual Studio 2017. Type a project name and you’re done.

Once the process completes you’ll have a project setup and ready to go:

Before running, you will want to switch to development mode. This allows dev features like hot module reloading to work:


To run the project, you have two options. Either open the csproj in Visual Studio 2017 and hit F5 to start debugging, or back in your console, run:

dotnet run

Either way the server will start on port 5000, so have a browse of it. There’s a little basic application for you to muck about with:

Click ‘Counter’ and there’s a button that increments a variable:

Now open ClientApp/components/Counter.tsx. This is the TypeScript React component for the counter.  We’ll test out the hot module reloading by editing that component to add another element to the page:

Webpack at this point detects the file change, the client downloads it, and Redux is able to maintain the state and update the page:

Another major win when using a state manager like Redux is Time Travel. Time Travel is when the state of your app is recorded throughout the lifetime of the app, and you can use a timeline to move the state of the app backwards and forwards in time.

To get Time Travel working, you can use the Redux Dev Tools. The dev tools come in two formats: a JavaScript library that you can add to your app, or a Chrome browser extension. Check out this blog post for an explanation of it. Either way, the dev tools look like this:

To try it out, click the ‘Increment’ button a few times. The tools are already recording the state changes and you’ll see the ‘INCREMENT_COUNT’ action appearing along within a timestamp.

Make sure the slider is show by clicking the slider button:

And then just move the slider around to travel through time. You can also click on an individual action in the list on the left to jump to the state at that time.

Replacing an expired S2S (high-trust) certificate in SharePoint 2013

In SharePoint 2013, configuring your environment for high-trust apps involves a few manual steps. Part of this process is configuring a trusted token issuer in the form of a certificate, which is then used to create app tokens.

Then comes the day when your certificate expires. But don’t panic; it is fairly simple to replace your certificate. Of course, the ideal scenario is to complete this *before* the certificate expires, so, set a reminder for next time!

Firstly, create a new certificate. You may need to request this from your organisation, but a self-signed certificate is fine for development environments (which requires that you turn off HTTPS with AllowOAuthOverHttp = true). Either way, you need both the CER and PFX files for your certificate. Copy the .CER to your SharePoint system. At this point, let’s check for details of your existing Root Authorities by opening the SharePoint command prompt and running Get-SPTrustedRootAuthority. All of your trusted root authories will be listed. Scroll down the list until you find your expired certificate:


The expired certificate above is called ‘s2s’. You can delete that one with the following command:

Remove-SPTrustedRootAuthority -Identity s2s


You’ll receive a confirmation message; press Y and enter. If you run Get-SPTrustedRootAuthority again you’ll see it’s gone. The next step is to remove your old token issuer. Run the following command to get a list of your existing token issuers:



Note the name of your expired token issuer, and delete it by its name, pressing Y to confirm:

Remove-SPTrustedSecurityTokenIssuer -Identity "Custodian App"


Finally, it’s time to add your new certificate as both a trusted root authority and a token issuer. First, register the new trusted root authority:

$path = "C:\certs\s2s-certificate.cer"
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($path)
New-SPTrustedRootAuthority -Name "S2S Certificate" -Certificate $certificate


And register the token issuer. Note that the the Issuer ID, the guid below, is specific to your app. Your Issuer ID is the same as your Client ID, if you have one token issuer per app.

$realm = Get-SPAuthenticationRealm
$issuerId = "4d25b859-5092-4306-8e7e-82fac0633413"
$fullIssuerId = $issuerId + '@' + $realm
New-SPTrustedSecurityTokenIssuer -Name "Custodian Cert" -Certificate $certificate -RegisteredIssuerName $fullIssuerId -IsTrustBroker


Now, configure your provider-hosted app with the new certificate. In Repstor custodian you need to modify the web.config to either include the path and password of your certificate PFX file, or preferably, the serial number. Your changes will be picked up within 24 hours, or immediately if you do an iisreset. Also, you may need to clear any existing user access tokens (based on the expired certificate) from your app cache if you have one.

And set a reminder for next year :-)

Experiences From My First 2 Months Of Chicken Keeping

So I built my chicken coop/house and bought a feeder and waterer. I built a big 10m x 4m fenced area which had trees, shrubs, shelter, and the house in it. Finally I couldn’t find any more excuses for delaying it so we ventured out to buy our hens!!

Day 1 – buying the hens

We went to a poultry sale in a local village. It was a strange experience – we looked totally out of place, not being dressed as farmers. It was quickly apparent that we had no idea what we were doing despite having read everything there is to read about chickens for the previous 6 months. It was ‘point of lay’ hens we were after – around the 18-week old mark – which most of the hens for sale were. The sellers were very helpful and everyone had plenty of time to chat. No-one gave us the hard sell.

Every seller told us the hens had had their vaccinations (not that’d we know the difference anyway). In the end, we bought 4 hens from one guy and two from another. We bought them based on their colours which is obviously very scientific. We ended up with 2 hybrids, a White Sussex, a Barred Rock, a White Leghorn, and a Daisybelle which has beautiful iridescent black and green feathers. The White Leghorn lays white eggs and the rest lay various shades of brown.

Getting the hens home

We came prepared with a cardboard box in the boot of the car which the hens were very happy to sit in. At least, there were no complaints since they were probably scared out of their minds. One of the sellers started piling the hens into a plastic bag (!) before we told him we had a box.

We brought the hens into their fenced enclosure and opened the box…they weren’t keen to come out at first but slowly emerged and began to eat the grass and weeds and everything. Note that after a couple of weeks, your chicken area is going to be bare and brown!!

Finding bedding and food

We didn’t have bedding or food on the day we bought them, figuring we’d buy some of that at the poultry sale. There wasn’t any for sale, so we had to go elsewhere for that. It turns out that there are animal feed mills everywhere, at least within a few miles of any large town.

We were able to buy layers pellets which include everything a chicken needs nutritionally. We were also able to buy chopped straw, which is just little bits of straw about a centimeter or two in length. A big bale of it was £5 and a 25kg sack of feed was £8. Both last about a month. I also tried wood shavings and they work just as well – my preference at the minute is the straw since it composts more readily.

First Day

It didn’t take long for a hen to figure out how to escape. They can’t fly higher than a few feet, and the fence at nearly 2m high should have been high enough, however what I didn’t realise is that they jump on to things (like their house) then on to other things (like a branch) then over the fence. I have had to cut a number of low branches off a tree.

Chickens settling in!

First Night

The first night went smoothly as we manually put all the chickens in the house and locked it. This is the recommended practice as it takes them a little while to get used to it. I opened it again the next morning and they waddled out happily!

Second Night

The second night wasn’t as smooth. Two hens disappeared up a tree! I mean, right up the tree. I managed to get up on a step ladder and tap their bums with a broom and they flew out. I put them in the house. So, lesson learned: they’ll always go to the highest point possible! Another night, a hen managed to escape. I didn’t notice until she wandered up the garden path to say hello the next morning. I’ve no idea where she slept.

Egg Laying

We bought all the hens at 18 weeks of age, and they were a little too young to lay. We checked the egg box every day and happily, the first egg arrived after about two weeks. It was perfectly formed. Each hen started laying one by one over the course of a few weeks until we we got six on one day and knew for sure they were all laying :-)

We occasionally get a rubbery egg, or ‘softie’. They’re sometimes a sign that the hen is stressed (the egg ‘pops out’ too early, before the shell is completely formed) or possibly the hen isn’t getting enough calcium. In our case, I think the hens are just young and haven’t quite got the hang of things! We don’t eat them, although I understand they’re perfectly edible. If they’re broken, I clean it up pretty quickly.


Our Barred Rock hen seemed to be getting bullied in the first few weeks. It was running away from the other hens and “sulking” by sitting in the house. I thought it was sick at first but then realised it was the only hen who hadn’t yet developed a comb so it was the youngest and at the bottom of the pecking order! So, since she was eating and drinking, there was nothing to worry about. Apparently separating her from the rest of the hens is the worst thing you could do in this situation.

Free Ranging outside of their enclosure

Although the enclosure we have is quite large (about 40sq m) I like to open it up and give the hens free reign of the garden occasionally. They enjoy pecking about in the compost heap, climbing on stuff, eating in our veg beds (which we try to keep them away from), pooing on paths, eating slugs and other insects (which is great), getting in your way, and digging dust baths!

Hens and Kids

We have a two year old, and he loves running about after them. They aren’t scared of him, but when he chases them, I think they get a bit nervous. I think this can contribute to some ‘softies’ – the occasional rubbery egg. So he only plays with them under supervision. He loves it when they eat food out of his hand – I guess it’s quite exhilarating for him since they’re pretty large animals relative to him!


The hens put themselves to bed every night when the light starts to fade. I just go out and close their door. I have a homemade automatic door opener that lets them out at sunrise when they wake up (which is totally necessary since there’s no water in their coop, and sunrise is about 4:30).

I top up their food and give them fresh water every 2 or 3 days. I actually change their water whenever it starts to look dirty – they tend to get it a bit mucky somehow.

I clean their coop out once a week. Sometimes I do a “full clean” – shovelling out all the bedding, and scrubbing any poop that’s stuck anywhere. Sometimes I skip the full clean and just shovel out the chicken poo and put it on the compost heap. It depends what sort of state it’s in.

Diet – Scraps From the Kitchen

We give the hens quite a few scraps from the kitchen, bits of peelings and chopped veg and bread. Apparently giving them too many scraps isn’t good for them since they get a balanced diet from their pellets. So, we try to limit it to a treat. We also have crushed eggshell in a plastic box available to them which they can eat if they want more calcium. Apparently they know and they’ll just take what they need. I rarely see a hen go near it.


I have applied a powder to their coop once, which is apparently supposed to kill any ticks/mites that live in there. I don’t know much about this but I think at some stage I’m going to need to apply it to the hens themselves.

Building a cheap homemade chicken house, in pictures

Here’s my coop building process in pictures. Enjoy!


I firstly cut four pieces of heavyweight stuff for the roof. It’s at a 30-degree incline. I used some brackets I had lying about and bent them to 30-degrees. I don’t think I really needed them. I also cut four legs; I think they’re about 1.2m tall.


I fixed the legs to the roof frame. Then I made a frame for the nesting box. It’s about 45cm high at the tallest, sloping down. I don’t think mine is enough of a slope, it should be steeper.

Then I started screwing together a frame of thinner wood that holds the legs together. At this point it starts looking like a house! The purpose of the frame is to support the windows and door and just hold everything together. Also there are beams across the bottom to support the floor.

The windows frames are 25.5cm square, because I bought some 25cm perspex from ebay. It was pretty cheap, about £5 I think.


I continued screwing everything together. The diagonal X shaped bits at the bottom are simply to hold the whole thing square during assembly. I took them off when I was nearly done.

You can see in the second and third picture above that I have two roosting beams. One is higher than the other; apparently that’s good to allow the hens to nest in their pecking order.


I made the floor so that it can slide in and out to aid cleaning. I never slide it out though, I just brush it out. It’s too heavy. I’ve made a door that flaps open if the weather’s hot. I haven’t used it yet, though since the house is out of the sun and it isn’t warm at night here anyway.

You can see the end of the house is one big door. That’s good for cleaning it out, easy access.


So this is the nesting box getting attached. It’s not enough of an incline; water doesn’t run off it quick enough and it gets saturated. It works well enough for now, though.

I made window frames and a door frame that are screwed on top of the door and window openings. This is so that they stick out. The purpose of the window frame is to hold the windows in (duh) and with the door frame, it protects claws of predators getting into the edges of the door when it’s closed.


After the frame was complete, I cut cladding to fit in around the door and windows. That was the most boring job. Then I nailed wood across the roof and attached slates to it. I was originally planning to do a thatched roof, but I had slates available.

Most of the wood I got from an old shed that I dismantled. The slates were found around the garden, they had been carefully placed by the previous owner to block holes in the hedge. So now we’ve got a problem with cats coming in all the time!

The paint was normal indoor emulsion, but I painted a layer of PVC glue over it to waterproof it.

What I’d do differently next time:

  • I’d make it bigger, with an area I can put food and water in. Basically I’d make it big enough for the chickens to live for a day or two without human intervention (closing them in at night). At the moment, I have to be there every night to lock them in because there isn’t room enough for their food/water which sit outside.
  • I’d make a door that slides up/down. This would make it easier to add an automatic door opener and closer. At the minute I have a homemade automatic door opener fitted but I have no idea how I could get it to close automatically.
  • It’s tall so it’s airy, with plenty of room for our 6 hens. However, one of the roosting bars is a little close to the big end door so there’s always poop on it and that doesn’t help with cleaning. In mark 2 I’d like to have a single, long roosting bar with a poop tray under it to make cleaning easier.

Automatic chicken coop door opener

Don’t want to get up at sunrise to let your chickens out, and don’t want to pay £80 for one of those battery-powered coop door opening timer contraptions? Well, here’s how to make one for about £10 depending on what you have lying about the house.

Shopping list:

  • 1x Door lock actuator motor (~£3), from Amazon or any car parts place.
    Actually, buy two because if you’re anything like me you’ll accidentally burn one out.
  • A 12v power supply. I used an old phone charger. Check your drawer of electrical tat or buy one like this for £5.
  • A timer plug, I have a digital one with a 1 minute minimum interval. I got one for £2.
  • A pair of crocodile clips - £1.50
  • A plastic tupperware box/empty chinese food box/any container that you can make waterproof by sealing shut
  • Duck tape
  • Enough cable to stretch from your power supply (which must absolutely remain indoors!!) to the coop door. I used 0.75mm cable, it cost about 45p per metre. You might get away with cheaper stuff, I’m not sure.
So you could wire this up in a very basic fashion – with the timer plug coming on at dawn, powering the actuator, which will open the door. However, without actually breaking the circuit as the door opens, the actuator will burn out (as it’s going to be powered for the minimum interval on your timer). Hence, the crocodile clips attach to the catch on the door and the little metal ‘pole’ (which is metal), and the circuit breaks when the door opens.
When you switch the positive and negative terminals, you can choose whether the actuator goes ‘in’ or ‘out’ when it’s powered. You want it to go ‘in’.
See diagram:

Chicken coop opener….drawn in Paint!

The metal catch and pole both come included with the actuator pack.

Now, here’s the real thing! You can see I’ve encased the actuator and most of the wiring inside a little plastic box, with a hole cut for the metal pole to stick out of it. I know this looks a bit of a mess, I’ve kind of gone a bit mad with the duck tape:

I’m sure your cables will be tidier.

Here’s an up-close of the catch mechanism:

The long flat brass thing and the metal ‘pole’ are included with the actuator. At the top you can see that the pole sticks into a little metal staple nail. Click here to see exactly what this is if you can’t see it. Of course, if you have any other ‘hook’ type of thing you could use then go for it. I just used what I had.

The final piece of the puzzle for me was making sure the door actually flung open when it was unlocked. To make sure it did that, I put a screw behind the door – between it and the door frame – so that you have to apply a little bit of pressure to actually get the door to close. It works like a charm.

There are a few downsides to this arrangement:

  • The timer plug can only be set to a fixed time of day. So you’ve to change it every now and again to keep up with the sunrise. Maybe a light sensor plug would do the job.
  • It only opens! There isn’t really any scope to add a ‘closing’ mechanism. It has to be manually closed each night.

ASP.Net WebApi Error: “The controller for path … was not found or does not implement IController.”

I have an ASP.NET MVC 4 project and I’ve added a Web API controller to it. Nothing fancy, no custom configuration, nothing. It doesn’t work out of the box. I get a 404 HTTP error and this error stack in my IIS logs:

[HttpException]: The controller for path '/api/controllername/5' was not found or does not implement IController.
   at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
   at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
   at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Turns out to be a pretty non-obvious fix. The error mentions that it’s checking that the controller implements IController. Normal MVC controllers implement IController, but WebAPI controllers do not. So it’s trying to match our URL with a standard MVC controller.

Take a look in the RouteConfig file and you’ll see something like this:

	name: "Default",
	url: "{controller}/{action}/{id}",
	defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Does that match your URL? Yeah, it probably does. Your URL (if you’re following the normal WebApi pattern) starts with ‘/api/’, so the router is trying to find a standard controller called ‘api’

Open up the file Global.asax.cs. It’ll look something like this:

protected void Application_Start()

You will now notice that the RouteConfig (for normal controllers) is registered in the pipeline before the WebApiConfig routes. This means that the standard controllers take precedent. And because your Web Api URL matches the pattern defined in RouteConfig, the framework is attempting to use it.

The fix is just to move the WebApiConfig registration further up the pipeline, before RouteConfig:

protected void Application_Start()

Calf Fasciculation, or Benign Fasciculation Syndrome (BFS)

If you don’t read anything else, read this: if you have fasciculations, stop worrying. Anxiety makes it worse. And it’s almost certainly not dangerous or indicative of another issue. Go to the doctor who will confirm that. Now read on.

In January 2014, one evening, I suddenly began having twitches in my calves. Not just little twitches, either. It was the entire muscle – right from my ankle to the base of the back of my knee. In both legs. And it was all of the time, 24 hours a day. I read someone else describe it as like having “insects crawling around under the skin.”

I googled for videos of calf fasciculations but although these do give an idea of what it’s like, the results I found weren’t quite as extreme:

Now, if this has happened to you, there’s good news and not so good news.

Good news:
It’s not going to do you any harm or shorten your lifespan or anything like that.

Bad news:
There’s not much you can do about it.

It wasn’t particularly noticeable during the day, when exercising, but when sitting still it became too annoying. Not painful at all, but uncomfortable. I found there are two ways to reduce the annoying-ness:

  • Have the calf muscle in a stretched position
  • Have the calf muscle pressed against a surface.

Having the muscle stretched meant standing up. When sitting on the sofa, I’d have my legs pressed against the base of the sofa, and then I could sit without it annoying me too much.

The first couple of days were the worst, because I wasn’t used to it. I felt like it was making me feel fatigued, but later realised this was psychosomatic. I desperately ran through the possible causes:

  • Poor quality shoes I had bought a few days prior
  • Exercise (running) on the day it started, immediately following a blood donation session
  • Deficiency in Magnesium, Calcium, or Potassium
  • Deficiency in something else, maybe related to being vegetarian
  • Stress (a common cause)
  • Tiredness
  • Medication side effects (I wasn’t taking any)
  • Alcohol intake (I hadn’t been drinking, and rarely drink much)
  • Infection, eg. Lyme’s disease (I didn’t have anything I knew of!)

Having run through the possible causes, I narrowed it down to having ran back to the office immediately following a blood donation session. You’re really not supposed to do that. I remember my calves having been really sore, and this was understandable since a pint of blood was missing from my body via which to transport oxygen to exercised muscles. I had quickly caused some kind of muscle damage to myself through careless behaviour.

After around 4 days of desperately hoping this stupid twitching would stop (and initially believing it would), I realised I’d need to try and find a solution. The worst part was that I was finding it hard to sleep. The internet wasn’t much help but I compiled a list of potential short-term remedies:

  • Take calcium, magnesium and potassium supplements and get tested for deficiency
  • Lower my stress levels (I thought about it carefully and decided I wasn’t stressed)
  • Get plenty of rest
  • Stretching
  • Wear decent shoes
  • Take Quinine (tonic water). Apparently it’s good for cramps. It tasted awful and didn’t do anything. Apparently quinine tablets would be needed to get a high enough dose to have a chance of doing anything.
  • Reduce caffeine intake. I stopped consuming any caffeine for more than a week. It didn’t work.

None of these did anything. I had no deficiencies (other than in common sense). As time went on I got used to the fasciculations. Sleeping became easy again as I learned to either sleep on my back (calves pressed against the mattress) or on my side (weirdly configured so that one calf was pressed against the other). My initial feelings of fatigue evaporated after just a few days and I started to feel fine and energetic again, having realised that the fatigue was brought on by the mental irritation and depressing google results I was finding.

Note to self – googling a medical issue is a BAD IDEA! Only a doctor can tell you what your ailment is!

I thought carefully about alternative, long-term remedies:

  • Fitness. I resumed running (and quickly injured my foot which has temporarily put a stop to that)
  • Strength training/weight gain. I started Stronglifts 5×5 and the GOMAD diet (google it) and gained 10lbs (mostly of fat, in fairness) in three weeks. I became stronger, including my calves. Which was nice. I’m continuing with the strength training.
  • Copper ointment. Apparently this “complimentary” medicine helps with cramps and damaged muscle. I maintained putting it on my calves for a few days and then lost interest. I don’t think it was going to do anything.
  • Acupuncture – I’ll resort to this if I get desperate and have some cash to throw about.
  • Homeopathy – I’ll need to be very desperate to try this, but who knows. That day may come.

I should mention that I visited the doctor twice. The first time, I was told it was nothing to worry about and to come back in a few weeks if it continued. The second time, I gave a blood sample for calcium, magnesium, and potassium testing – these were negative. I haven’t bothered going back because I know there’s no proven treatment.

How am I doing now? Well, it’s been three months, and the fasciculations are still there. I feel like it’s less intense, though. I can sleep without pressure on my calves – this has only happened in the past two weeks. Sometimes it feels like they’ve stopped, but when I roll up my jeans, they’re still going. Oh well; as long as it feels better, that’s the important thing. My best guess for the cause of the improvement is my weight and strength gains. It may be coincidence, but the calf improvements did seem to begin about a week after I began strength training and weight gain. I’d recommend strength training anyway, since it’s a good health improvement to take on.

Apparently, in a large proportion of cases, this condition subsides within several years – maybe not completely, but often noticeably. The main thing is that it’s not worrying me anymore, and I’m fully confident that it’s going to disappear before the end of the year. In three months it feels noticeably better. After exercise it becomes much more intense, but that’s to be expected and is not a problem.

I have written this post because of the lack of information I found on the internet when trying to self-diagnose. All I found was loads of people deciding that they probably had a disease called ALS. Which they don’t. If recommend you attempt all of the remedies I’ve suggested, starting with the most common ones: stress, over-exercise, alcohol/caffeine consumption, and mineral deficiency.

Leave a comment if you have something similar or know of a potential treatment I haven’t suggested. Good luck!

Futher reading:

Update 31-Oct 2014: It’s been 10 months. It’s as annoying as it was at the beginning. I sleep with pressure on my calves: lying on my side, with one on top of the other, or on my back. Oh well…otherwise healthy :-)

Update 25-Mar-2015: Now 15 months. Nothing new, except it’s totally normal for me now. I don’t run any more because my calves are usually pretty sore afterwords. I walk a lot which I don’t think makes it worse. My son woke me up from a deep sleep one night, and it felt like the fasciculations had gone. I felt my calves and couldn’t feel them moving. I went back to sleep. I don’t know if I was imagining it but that’s the only time it seems like they stopped. I love reading the comments. Makes it all seem normal!

Update 18-Aug-2015: They’ve stopped. Not all at once, but gradually, over the course of the past 6 weeks or so. Actually I think they’re still going but very, very faintly. I don’t think there was anything I have done differently in my life – I have no idea why they stopped. It was about 17 months in total. Weird!! As someone posted in the comments, here is a site with more information, and a discussion forum.

Super strong homemade weights bench

Inspired by this description of a wooden DIY weights bench, I decided to make my own. Mine was way simpler, though; I used less wood but it’s much thicker so it’s still strong. This post includes photos of each step, but I won’t go into loads of detail – hopefully the images will speak for themselves.

Home made wooden weights bench

Excuse the mess….

But firstly, with regard to motivation for making this, let me quote from the link I mentioned:

Shopping for a weight bench can be difficult. And by difficult I mean expensive. And just to be clear, whenever I use the phrase “weight bench” I mean a strong one that can be used to Bench Press. The problem you’ll run into when buying these is that the reasonably priced ones are not rated to hold much weight. You’ll see figures like “300 lbs.” But when you consider that the bench has to hold your body as well, 300 lbs. is not much. If you weigh a measly 150 lbs. when you start, and bench press 150 lbs. That’s your 300 lbs. right there. This is novice level lifting. Once you turn into a real lifter after a few years of training, you’ll probably weigh closer to 200 lbs. yourself and be benching near 300 lbs. Now that’s 500 lbs. and all those affordable weight benches are now too weak for your purposes. But when you start pricing quality benches that are rated for this type of serious lifting, you are going to have to pay hundreds of dollars for them. This is unacceptable by Homemade Strength standards.

Before I get into how I made my bench, let me say I’ve tested it with a total mass of 250kg. That’s me (75kg – yes, I’m skinny) plus a friend (100kg) plus weights (75kg) all on top of it, in the middle. So it’s strong! However, you should always do what I’ve done and test your bench thoroughly before lifting weights on it. You don’t want it breaking when you’re holding your own body weight in cast iron above you. With that in mind, here are the details:


Standard sizes are 45cm high and 30cm wide. You can adjust these to suit yourself – you may want to make it shorter (if you’re short). Some people prefer it a little narrower. The length is 110cm – it needs to comfortably fit both your head and bum. 110cm is long enough for me and I’m 6’1″.


- Screws of various sizes, electric screwdriver
- Saw – probably a circular saw…I wouldn’t fancy cutting it all the old fashioned way
- Staplegun & staples for the upholstery (tacks are an alternative)


I used about 3 metres of timber measuring 50mm X 150mm. It’s really thick, heavy stuff: not like 2×4 at all. I had it lying around the garage. You can use whatever you have lying around as long as you’re sure it can hold the weight. When it comes to using it, go gently, and make sure you’re safe. If you’re not sure, then stop.

I had some left over MDF from my kitchen which was fitted last year, and I cut out two pieces of 30cm x 110cm x 12mm. The reason I need two will become clear later!

For the legs you’ll need another two pieces of 30cm x 30cm MDF. Read all the way through to see why these are needed.

Finally, I bought 4m of cheap wadding (polyester padding material). This probably wasn’t enough, it’s very thin. So my bench isn’t particularly comfortable. That doesn’t bother me. I also bought a metre of pleather (fake plastic leather) for about £8. It’s only a metre but it’s 140cm wide so that’s plenty.

The great thing about wooden construction is that you can change it later, or add more strength to it. I have the option of adding more legs to the middle of my bench for extra support if I ever go above the 250kg. When it’s complete you need to do some serious testing on this bench to make sure it’s up to the job before use. As I mentioned already, you really don’t want 100kg (or any amount) of weights crashing down on you during bench press when your bench breaks.

I’m a lightweight and I’m lifting light weights. You probably aren’t so your bench may need to be stronger.


Start by cutting the legs. They’re about 40cm long (total height will be more when the MDF top is added). Also cut the centre beam, it should be about 100cm long. Adjust these sizes to your preferences, the design is flexible. Feel free to double up on that centre beam.

Now I use my pieces of 30cm x 30cm MDF and screw them to the legs. This holds the legs together but also, the centre beam will rest on it. In this picture there’s only 4 screws in each; I actually ended up putting 10 in each.

These need to be 50mm from the top of the legs – this is because the centre beam will rest on them. It’ll become clear in a moment.

This is how it fits together so far. Screw it together. You need some pretty long screws.

Here’s my two pieces of 30cm x 110cm MDF.

Then put the first piece of MDF on top, and screw it into the legs and beam. It’ll help hold the whole thing together. It’s way sturdier than it looks here. It’s really heavyweight and there’s no movement or wobble in the legs whatsoever.

Now, at this point, you may wish to do your testing and add additional legs to the middle if needs be! If you want to avoid doing testing and be conservative about, then just add more legs.

Here’s our bits so far: partially completed bench, leather, wadding, and the top piece of MDF.

Next up we’re doing the padding. Lay down your leather (upside down!) followed by the wadding, followed by the other piece of MDF:

Try and keep it as neat as possible, it’s awkward because it’ll try to move about. Allow the wadding to stick out of the edges so that it’ll wrap round the edges nicely. Staple one side first, then wrap the other size around carefully but tightly. Don’t rip it!

You should end up with something like this. I’ve trimmed off the excess because as you can see from the picture above, my piece of leather was way too big.

OK, now dump your bench on top, upside down:

And put a few small screws through the first layer of MDF to hold the second on. Don’t make the screws too long, you don’t want them coming through into your back!


As a final note, I need to reiterate, test it first. Test it by piling all of your weights on top of it, and then stand on it, and have a friend stand on it too, and if you hear any creaks (or it breaks…) then go back to square one!! I’m a lightweight and I’m lifting light weights so you may well need to add more legs to the middle your bench.

Good luck!!

“Unknown User” error when creating SharePoint 2013 MVC Apps

Do you get this error?

Unknown User

Unable to determine your identity. Please try again by launching the app installed on your site.

Well, it’s quite possibly nothing to do with users, identities, or anything else related to security. This is the default text in the Views/Shared/error.cshtml file in the web project that’s generated for you when you create a new SharePoint MVC project.

So, this error is shown whenever there’s any unhandled exception in your app….and that could be anything, really. So you’ve got to start debugging it. That’s easy if you’re debugging locally: simply turn on break on exceptions by going to Debug -> Exception and checking the Common Language Runtime Exceptions in the Thrown column:

Now, if you’re developing an Autohosted app for SharePoint 2013, then it’ll be running in Azure. And if you’re unfortunate enough that you’re seeing the “Unknown Error” page in Azure but not locally, then you need to disable that error page and make sure you’re able to see the full exception detail.

To do that, browse to your Views/Shared/Error.cshtml file and remove it from your project. If you’re not using source control, then you’ll probably want to back it up somewhere else to restore it later – this is only for debugging.

Once you’ve got rid of it, you need to switch on exceptions from remote machines. Open your project’s main Web.config (in your web project root) and find the <system.web> tag. Add in the tag <customErrors mode=”Off”/>. It should look something like this:

Now when you run your project and reproduce the error, you’ll see a stack trace which should put you on the right track.