<?xml version="1.0" encoding="utf-16"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <atom:link rel="self" type="application/rss+xml" href="https://eliot-jones.com/" />
    <title>Eliot Jones</title>
    <link>https://eliot-jones.com/</link>
    <description>Simple Blog</description>
    <language>en</language>
    <item>
      <title>Show me the information</title>
      <link>https://eliot-jones.com/2026/3/stop-doing-this</link>
      <description>

&lt;p&gt;Since I'm in an unhinged rant frame of mind I wanted to also rant about this tendency for 'minimalist' thinking in UX/UI. I'm going to blame Google and their Material UI for this, they should be blamed for most things, but the trend has become something of an accepted wisdom amongst UI designers.&lt;/p&gt;

&lt;p&gt;The idea is you keep the UI nice and 'clean' and only show the user the fields you believe are relevant to them. For example you truncate a message because it would wrap and break the UI scaling. Or you show just the date part of a timestamp, or even worse show "a few hours ago" instead of the actual date. Maybe you show the full time on a mouse-over event, but how do I copy that?&lt;/p&gt;

&lt;p&gt;Hiding information to make your site visually appealing breaks real-world tasks. You can't predict what the user is going to do, you are not an oracle, so just show them the information. Even if they decide to put the entire text of the Iliad in a description field. It'll look garbage but at least they can complete their task.&lt;/p&gt;

&lt;p&gt;There is a lack of empathy for the user in these choices. What is your user trying to achieve? How can you make that task as easy as possible? What about users who fall outside the flows you predicted they would need?&lt;/p&gt;

&lt;p&gt;First up there's this screenshot from the fundamentally cursed Gmail UI:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/stopthis/who-was-it-to.png" alt="Gmail sent email showing only the first name of the recipient" /&gt;&lt;/p&gt;

&lt;p&gt;I've redacted my personal information from the screenshot but the &lt;code&gt;To&lt;/code&gt; field only tells you the first name of the recipient. What if you have multiple recipients with that name? Why not show me the email address next to the name? I needed to double check the address because I was sending an email from a different device outside of the Gmail ecosystem. You can get to the email address by clicking the expanding chevron next to the name but this is another speedbump on a common task. You tell me my own email address just above, why not the recipient's? Well it would scale badly for multiple recipients, but that's your job as a designer. Don't just hide the damned information. Systems should be designed to &lt;em&gt;do&lt;/em&gt; things.&lt;/p&gt;

&lt;p&gt;Then the worst offender. My bank. I was sending money abroad for some purpose using a wire transfer. The bank listed 2 options for the recipient bank that differed only in the last 3 letters of the SWIFT code. The recipient name, address, account number, etc., was identical. Because the first small test transfer I sent opted for the wrong SWIFT code leading my money to disappear I had to try again with the second SWIFT code. The second transfer worked so then I needed to send the remaining payment amount. But because of the idiotic decision to hide the full payee details I couldn't actually tell which of the 2 existing payees was the right one, so I then had to add the details a 3rd time. That left me with this problem:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/stopthis/payment-ui-fail.png" alt="3 payees with identical details" /&gt;&lt;/p&gt;

&lt;p&gt;Again I've redacted information here, these aren't real account numbers or names but I kept the redaction consistent. As you can see there's 3 payees with completely identical listings. If I send money to one of these my money disappears forever, lost somewhere in the international wire system. Well, you think, they've probably just done an inconvenient information hiding thing again. Maybe just click click the 3 dots next to the payee and you'll see the full details?&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/stopthis/payment-ui-fail-2.png" alt="Creating a payment to one of the payees" /&gt;&lt;/p&gt;

&lt;p&gt;Nope, the only options there are to delete the payee or send a payment. If you try sending a payment there's no further information about who you are actually paying.&lt;/p&gt;

&lt;p&gt;Granted this is a bank UI so their systems are probably ancient and they don't have the time or software development resources to go in and add a way to retrieve the information like Google has. But this happens because the designer and their poor taste wins out over the needs of people who actually &lt;em&gt;use&lt;/em&gt; the systems they build. I'm sorry that the information density or length or shape is inconvenient to your artistic vision. You're wasting my time and potentially losing me money. Just add the damned fields to the UI. You have them, they're in your database somewhere. So &lt;strong&gt;show them to me&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;Modern UI design is cursed. People with good aesthetic taste but terrible taste in actual usage win out over the developers and users of systems all the time. There is a lack of empathy. I feel like the only reasonable person in a world gone mad.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2026/3/stop-doing-this</guid>
      <pubDate>Sat, 21 Mar 2026 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Cheese sandwich</title>
      <link>https://eliot-jones.com/2026/3/cheese-sandwich</link>
      <description>

&lt;p&gt;If you are the type of person with &lt;em&gt;Very Strong Opinions&lt;/em&gt; about the (negative) health and moral implications of plant-based 'meat' you are signalling that you are fundamentally intellectually incurious. You have an opinion you haven't taken the time to inspect and have adopted certainty without rigor.&lt;/p&gt;

&lt;p&gt;This is a picture of a cheese sandwich, I made it at home, it was &lt;em&gt;ok&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/cheesesandwich/sandwich.jpg" alt="cheese sandwich" /&gt;&lt;/p&gt;

&lt;p&gt;And this is the ingredients list of that cheese sandwich:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Lettuce

&lt;ul&gt;
&lt;li&gt;it's a lettuce&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Tomato

&lt;ul&gt;
&lt;li&gt;it's a tomato&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Balsamic vinegar (a small drizzle rescues supermarket tomatoes from their cardboard nature)

&lt;ul&gt;
&lt;li&gt;wine vinegar&lt;/li&gt;
&lt;li&gt;concentrated grape must&lt;/li&gt;
&lt;li&gt;cooked grape must&lt;/li&gt;
&lt;li&gt;coloring E150(d)&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Mayonnaise

&lt;ul&gt;
&lt;li&gt;rapeseed oil&lt;/li&gt;
&lt;li&gt;egg&lt;/li&gt;
&lt;li&gt;spirit vinegar&lt;/li&gt;
&lt;li&gt;pasteurised egg yolk&lt;/li&gt;
&lt;li&gt;lemon juice from concentrate&lt;/li&gt;
&lt;li&gt;sugar&lt;/li&gt;
&lt;li&gt;salt&lt;/li&gt;
&lt;li&gt;mustard extract&lt;/li&gt;
&lt;li&gt;paprika extract&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Cheddar cheese

&lt;ul&gt;
&lt;li&gt;pasteurised full fat milk&lt;/li&gt;
&lt;li&gt;vegetarian rennet&lt;/li&gt;
&lt;li&gt;salt&lt;/li&gt;
&lt;li&gt;starter culture&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Bread

&lt;ul&gt;
&lt;li&gt;wheat&lt;/li&gt;
&lt;li&gt;rye&lt;/li&gt;
&lt;li&gt;barley&lt;/li&gt;
&lt;li&gt;oats&lt;/li&gt;
&lt;li&gt;millet&lt;/li&gt;
&lt;li&gt;corn&lt;/li&gt;
&lt;li&gt;sesame seeds&lt;/li&gt;
&lt;li&gt;sunflower seeds&lt;/li&gt;
&lt;li&gt;linseed&lt;/li&gt;
&lt;li&gt;soy&lt;/li&gt;
&lt;li&gt;100% vegetable shortening&lt;/li&gt;
&lt;li&gt;sugar&lt;/li&gt;
&lt;li&gt;molasses&lt;/li&gt;
&lt;li&gt;salt&lt;/li&gt;
&lt;li&gt;yeast&lt;/li&gt;
&lt;li&gt;calcium propionate&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Pickle

&lt;ul&gt;
&lt;li&gt;carrot&lt;/li&gt;
&lt;li&gt;rutabaga&lt;/li&gt;
&lt;li&gt;onion&lt;/li&gt;
&lt;li&gt;cauliflower&lt;/li&gt;
&lt;li&gt;sugar&lt;/li&gt;
&lt;li&gt;barley malt vinegar&lt;/li&gt;
&lt;li&gt;spirit vinegar&lt;/li&gt;
&lt;li&gt;salt&lt;/li&gt;
&lt;li&gt;tomato puree&lt;/li&gt;
&lt;li&gt;dates&lt;/li&gt;
&lt;li&gt;rice flour&lt;/li&gt;
&lt;li&gt;apple pulp&lt;/li&gt;
&lt;li&gt;modified maize starch&lt;/li&gt;
&lt;li&gt;sulphite ammonia caramel (color)&lt;/li&gt;
&lt;li&gt;onion powder&lt;/li&gt;
&lt;li&gt;lemon juice&lt;/li&gt;
&lt;li&gt;spices&lt;/li&gt;
&lt;li&gt;colouring food (barley malt extract)&lt;/li&gt;
&lt;li&gt;herb and spice extracts&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Add ham to taste.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, is this sandwich the healthiest food in the world? No, not really. But I hope you'd agree it's not complete poison either. Most of the ingredients list are recognizable things. Except rutabaga, I have no idea what rutabaga is, but Wikipedia tells me it is turnip. Importantly, many of them are things that have been through multiple processing steps. That's just what we do with food, we make ingredients into other things. We've been doing this for millennia.&lt;/p&gt;

&lt;p&gt;What is spirit vinegar? &lt;a href="https://versatilevinegar.org/faqs/"&gt;Per&lt;/a&gt; "The Vinegar Institute" (which sounds fun) all vinegars start out as agricultural sugars that are first fermented into alcohols, followed by the alcohol being fermented into acetic acid by other bacteria. What about modified maize starch? Modified how? Sounds pretty suspect. Well, &lt;a href="https://starchinfood.eu/question/what-is-modified-starch-and-why-is-it-modified/"&gt;the website&lt;/a&gt; "Starch in Food" (I'd bet a 'The Vinegar Institute' and 'Starch in Food' get-together is a real party) says it is a starch extracted from some kind of grain or vegetable treated to improve its uses in food in one of three possible ways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Cooking/roasting&lt;/li&gt;
&lt;li&gt;Enzymes&lt;/li&gt;
&lt;li&gt;Chemicals&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The packaging doesn't specify which of these 3 methods was used and it doesn't really matter. I'm fine eating this stuff. A cheese sandwich is full of chemicals. I'm full of chemicals, you are full of chemicals. Toilet bleach is chemicals, so is a lettuce. Food containing chemicals tells you nothing more than whether or not the food is a vacuum. Which brings me onto the topic of my rant.&lt;/p&gt;

&lt;p&gt;If you have strong opinions that plant-based meat substitutes are unnatural or unhealthy solely on the basis of their ingredients list you are being incurious and I'm sick of hearing about it. These days you can't move for people who have &lt;strong&gt;Opinions&lt;/strong&gt; that they can't wait to tell you if you order one of these things. And I don't think these people have come to their Capital-O &lt;strong&gt;Opinions&lt;/strong&gt; organically; and I don't think they've inspected why they think what they think. And that's intellectually lazy.&lt;/p&gt;

&lt;p&gt;In general there are different reasons someone might choose to adopt a vegan diet, vegetarian diet or simply choose to eat less meat. Each person will have their own reasons.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Health reasons.&lt;/li&gt;
&lt;li&gt;Moral reasons, a piggy is much like a cute little doggy but we only raise one of the two in horrendous conditions before murdering it and chopping it into pieces. (The dairy and egg industry are, if anything, crueler, but in life you generally have to decide at what point you're making the perfect the enemy of the good, and that decision is up to you)&lt;/li&gt;
&lt;li&gt;Environmental reasons, the environmental footprint of meat (and dairy) is generally larger than vegetarian foods.&lt;/li&gt;
&lt;li&gt;Taste, some people don't like the taste of meat.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Strong Opinions on plant-based meats are usually one of either:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;These taste bad and aren't really like meat. Which, sure, y'know, I think olives taste bad, but I'm not annoyed by the olive section of the supermarket. Just don't eat them.&lt;/li&gt;
&lt;li&gt;These are frankenfoods. They are fundamentally unnatural. They are extremely unhealthy, made in a lab, and you, as someone who eats them, have sinned. These foods will kill you and my real meat burger or sausage makes me not only a moral paragon, but someone who will outlive you because I have the true science.&lt;/li&gt;
&lt;li&gt;There is a 3rd, weaker, claim, often from other vegans or vegetarians. This is that you shouldn't &lt;em&gt;need&lt;/em&gt; them and as a vegetarian you should be happy with only chickpeas, lentils, black beans or tofu for every single meal for the rest of your life. This usually ties into the health concerns around them. If you don't like them and you're happy with pulses forever that's great for you. But try to be a bit less prescriptivist about this please.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The health claim is the main one, and the one that has done the greatest damage to both the industry and the consumer demand for these products. We've already seen how a fairly mundane sandwich starts to sound like it was produced in an RV in New Mexico if you start to deep dive into how we process and transform ingredients.&lt;/p&gt;

&lt;p&gt;But my response would be two-fold. If we concede the point, let's assume these ingredients &lt;em&gt;are&lt;/em&gt; unhealthy, well... so what? It's irrelevant. I'm not eating a burger, hot-dogs, chicken nuggets or sausages to be healthy, whether meat-based or plant-based. I'm having them slathered in sauces and cheese, with fries and onion rings. Because that's nice food, not for every day, but it's a cultural mainstay of my food culture. Some days you can have pasta and sauce, some days, too many days, you can have various lentil stews or curries, but some days you just want a damned burger. Some days you just want some junk food. But these options give you junk food without the bit where an animal spends its short life in abject misery before being slaughtered in terror.&lt;/p&gt;

&lt;p&gt;But I'm not conceding the point because I don't think you have standing to make it. I have very little confidence in strong claims made about dietary science by lay-people.&lt;/p&gt;

&lt;p&gt;It used to be that fat was the enemy, and then it was hydrogenated versus non-hydrogenated fats. Eggs were going to kill you but now they're maybe ok. But actually probably sugar will kill you. Now maybe seed oils will, or won't, or will only do it if you heat them beyond their smoke point. Maybe sweeteners protect you from the ill-effects of sugar or maybe they kill you in an even worse way. Are nitrites in your bacon going to kill you, is red meat? Are plant-based meats? Does a glass of red wine help my heart? Does dark chocolate? Is frying everything in beef tallow the answer? How are you going to live forever?&lt;/p&gt;

&lt;p&gt;Dietary science seems to me to be the weakest field of science, how do you pull out effects from the noise of everything people eat and interact with in their entire life? How do you get good enough source data from self-reported food diaries? How do you run big enough studies? This isn't an anti-science rant, we just need to do better science.&lt;/p&gt;

&lt;p&gt;But pop-science beliefs from dietary science always follow the same pattern. Some pre-print or university press release, or crank self-published article, gets picked up by the media and through word-of-mouth, or funded amplification by lobbyists, becomes the villain of the moment. It's easy to understand why this happens, sickness is scary, mortality is scary. The idea that there's some key to avoid it, some guidance that can become a moral framework is extremely alluring. Just take a shot of apple cider vinegar each day, just avoid sugar, just avoid sucralose, just avoid anything with chemicals, avoid margarine, avoid butter, avoid anything with more than 20 ingredients. These beliefs provide frameworks to manage the terror, a way to assume superiority and believe that you won't be struck down, that that only happens to those who err and don't follow the true path.&lt;/p&gt;

&lt;p&gt;Eat what you want to eat, I'll eat what I want to eat. Dietary science points us in a general direction. You probably want as much fresh fruit and veg as you can reasonably stomach or afford. You probably don't want too many carbs and only sugary things on occasion. But you also exist under a food system that prioritizes high satiety sugar-packed junk, so some days you're going to eat an entire sharing pack of sweets lying on the sofa, as the darkness gradually falls and you can't be bothered to get up to draw the curtains or switch on the light, because this is all so tiring sometimes.&lt;/p&gt;

&lt;p&gt;All I ask is that you're not running around spouting off when you don't have a solid foundation for doing so. We can all go and find our own pet study that tells us what we want to believe. We can use that for reassurance.&lt;/p&gt;

&lt;p&gt;But we don't have certainty on any of this stuff yet. So let's stop pretending otherwise.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2026/3/cheese-sandwich</guid>
      <pubDate>Fri, 20 Mar 2026 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>So you want to parse a PDF?</title>
      <link>https://eliot-jones.com/2025/8/pdf-parsing-xref</link>
      <description>

&lt;p&gt;Suppose you have an appetite for tilting at windmills. Let's say you love pain. Well then why not write a PDF parser today?&lt;/p&gt;

&lt;h2&gt;The ideal world: how the specification should work&lt;/h2&gt;

&lt;p&gt;Conceptually parsing a PDF is fairly simple:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First, locate the version header comment at the start of the file&lt;/li&gt;
&lt;li&gt;Next you need to locate the pointer to the cross-reference&lt;/li&gt;
&lt;li&gt;Then you can find all object offsets&lt;/li&gt;
&lt;li&gt;Finally you locate and build the trailer dictionary which points to the catalog dicitionary&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Introduction to PDF objects&lt;/h3&gt;

&lt;p&gt;A PDF object wraps some valid PDF content, numbers, strings, dictionaries, etc., in an object and generation number. The content is surrounded by the &lt;code&gt;obj/endobj&lt;/code&gt; markers, for example a simple number may have its own PDF object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;16 0 obj
620
endobj
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This declares that object 16 with generation 0 contains the number 620.&lt;/p&gt;

&lt;p&gt;A PDF file is effectively a graph of objects that may reference each other. Objects reference other objects by use of indirect references. These have the format "16 0 R" which indicates that the content
should be found in object 16 (generation number 0). In this case that would point to the object 16 containing the number 620. It is up to producer applications to split file content into objects as they wish, though the specification requires that certain object types be indirect.&lt;/p&gt;

&lt;h3&gt;Finding the cross-reference offset&lt;/h3&gt;

&lt;p&gt;To avoid the need to scan the entire file, PDFs declare a cross-reference table (xref). This is an index pointing to where each object in the file lives.&lt;/p&gt;

&lt;p&gt;Each file ends with a pointer to the cross-reference file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;&amp;lt; %trailer &amp;gt;&amp;gt;
startxref
116
%%EOF
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This tells the parser to jump to byte offset 116 to find the xref table (or stream). In theory this pointer is right at the end of the file, according to the specification:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Applications should read a PDF file from its end. The last line of the file contains only the end-of-file marker, &lt;code&gt;%%EOF&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Though the specification says the &lt;code&gt;%%EOF&lt;/code&gt; marker should be on the last line, in practice, things are much messier. For example, Adobe Acrobat only requires it to be within the last 1024 bytes. In real files it can appear anywhere.&lt;/p&gt;

&lt;p&gt;In addition files encountered in the wild lacked a linebreak before the offset declaration, or had a typo, e.g. &lt;code&gt;startref&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's assume you're able to find the declared cross-reference offset for now.&lt;/p&gt;

&lt;h3&gt;Finding all object offsets&lt;/h3&gt;

&lt;p&gt;At the specified offset you should find a well-formatted xref table:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;xref
7 4
0000000000 65535 f 
0000109882 00000 n 
0000109933 00000 n 
0000140066 00000 n 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After the &lt;code&gt;xref&lt;/code&gt; indicator appears, followed by a line break, the first object number and count of objects in the subsection are given. This means: start at object 7 and list 4 objects. Each line gives the byte offset, generation number, and status (n for in-use, f for free). From this, we know where to find objects 8-10 in the file.&lt;/p&gt;

&lt;p&gt;So in the example above -- skipping the free entry for object 7 -- this xref table tells where to find the following objects:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Object 8 (generation 0) at offset 109882&lt;/li&gt;
&lt;li&gt;Object 9 (generation 0) at offset 109933&lt;/li&gt;
&lt;li&gt;Object 10 (generation 0) at offset 140066&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note: files can have multiple xref tables or streams, linked by &lt;code&gt;/Prev&lt;/code&gt; entries in their trailers.&lt;/p&gt;

&lt;h3&gt;Locating the trailer dictionary&lt;/h3&gt;

&lt;p&gt;Finally, above the startxref marker, you'll find the trailer dictionary. This provides key metadata, most importantly, where to find the root object. Once you have that, you can follow references and begin interpreting the content.&lt;/p&gt;

&lt;h2&gt;The real world: where your pain begins&lt;/h2&gt;

&lt;p&gt;Assuming everything is well behaved and you have a reasonable parser for PDF objects this is fairly simple. But you cannot assume everything is well behaved. That would be very foolish, foolish indeed. You're in PDF hell
now. PDF isn't a specification, it's a social construct, it's a vibe. The more you struggle the deeper you sink. You live in the bog now, with the rest of us, far from the sight of God. If your parser expects files to obey the specification it will fail and people will think it is broken and pitiable. They will think that you are very silly.&lt;/p&gt;

&lt;h3&gt;The challenges of locating the xref pointer&lt;/h3&gt;

&lt;p&gt;We've already mentioned a few unexpected ways locating the pointer to the first cross-reference can fail:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It is not at the end of the file, nor within the last 1024 bytes of the file.&lt;/li&gt;
&lt;li&gt;It is misspelled.&lt;/li&gt;
&lt;li&gt;It is not in the format you'd expect.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But assuming you find a pointer, that's where the real fun begins. Because the pointer is not your friend, it is the first lie, you don't appreciate how deep the rabbit hole goes.
In screening 3977 files taken from the &lt;a href="https://digitalcorpora.s3.amazonaws.com/s3_browser.html#corpora/files/CC-MAIN-2021-31-PDF-UNTRUNCATED/"&gt;common crawl corpus&lt;/a&gt; at random we detected 23 files with a bad xref declaration. This works out to a roughly 0.5% failure rate in the sample set.&lt;/p&gt;

&lt;h3&gt;PDF content starting at a non-zero offset&lt;/h3&gt;

&lt;p&gt;In these files the &lt;code&gt;startxref&lt;/code&gt; pointer is incorrect due to a non-zero PDF content start.&lt;/p&gt;

&lt;p&gt;This happens when there's junk data before the &lt;code&gt;%PDF-&lt;/code&gt; version header. This shifts every single byte offset in the file.
For example, the declared startxref pointer might be 960, but the actual location is at 970 because of the 10 bytes of junk data at the beginning:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ten bytes!%PDF-1.4
%âãÏÓ
4 0 obj
(content follows)
endobj
% more content
xref
0 5
% ...
&amp;lt;&amp;lt; &amp;gt;&amp;gt;
startxref
960
%%EOF
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to adjust for this you should capture the offset of the version header in your file. If the first pointer is incorrect you should also try the offset of the first pointer plus the content start offset. But you still need to check both.&lt;/p&gt;

&lt;p&gt;This problem accounted for roughly 50% of errors in the sample set.&lt;/p&gt;

&lt;h3&gt;The pointer is in the middle of the xref table&lt;/h3&gt;

&lt;p&gt;For some files there is no content preceding the version header, however the pointer is still wrong and it points inside the xref table content at a random offset.&lt;/p&gt;

&lt;p&gt;For example jumping directly to the specified offset takes you to this position:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;endobj xref
0 246
0000000000 65535 f 
0000184481 00000 n 
00000&amp;lt;---
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was the case for roughly 5 files in the error set.&lt;/p&gt;

&lt;h3&gt;The pointer is 'close' to the xref&lt;/h3&gt;

&lt;p&gt;Similar to the previous error, here there is no version header offset but following the pointer takes you 'almost' to the xref. The most common cases were to be off by a single whitespace/newline, or
in the &lt;code&gt;endobj&lt;/code&gt; marker of the previous object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;endobj
--&amp;gt; xref
0 4
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;or:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;--&amp;gt;endobj
xref
0 7
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;The pointer is correct but the xref offsets are incorrect&lt;/h3&gt;

&lt;p&gt;Sometimes the pointer correctly jumps to the &lt;code&gt;xref&lt;/code&gt; marker but if you parse the object offsets from the table they are incorrect. The table offsets can also be incorrect when the xref offset is also incorrect.&lt;/p&gt;

&lt;p&gt;It can also be the case that offsets are correct for some objects in the table but wrong for others. This was the case for file 0002544.pdf in the sample set which had an initial pointer off-by-7. The locations in the xref table's first subsection were correct, then offsets that were off-by-4 bytes for subsequent subsections.&lt;/p&gt;

&lt;h3&gt;The first pointer is correct but the previous offset is incorrect&lt;/h3&gt;

&lt;p&gt;When a file has been modified the file's trailer (or xref stream dictionary) can contain a &lt;code&gt;/Prev&lt;/code&gt; pointer. This is used to construct a chain of xref tables and streams. Several files had correct initial pointers
however when parsing the trailer's previous offset the second location was incorrect. One file contained a value of &lt;code&gt;0&lt;/code&gt; for the previous pointer which indicates that it had incorrectly written the
default value, rather than an offset.&lt;/p&gt;

&lt;h3&gt;The xref table is not well formatted&lt;/h3&gt;

&lt;p&gt;Beyond the xref pointer issues seen in the sample set, the table structure itself can be malformed in unexpected ways.&lt;/p&gt;

&lt;p&gt;The following examples were reported as Github issues for &lt;a href="https://github.com/UglyToad/PdfPig"&gt;PdfPig&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;No linebreak after &lt;code&gt;xref&lt;/code&gt;, for example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;xref5 2
0000000000 65535 f 
0000134883 00000 n 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;More object entries in a subsection than declared in the header, for example if only 2 objects are declared the table can contain more:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;xref
0 2
0000000000 65535 f 
0000000230 00000 n 
0000000520 00000 n 
0000001000 00000 n 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Garbage in the middle of the table, for example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;xref
0 2
0000000000 65535 f
0000455.8483a a010 00000 n 
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;We looked at how parsing a PDF should proceed according to the specification. We then compared this with a survey of sample files where we saw a 0.5% error rate due to non-compliant files.
All tested PDF viewers (PDF.js, Adobe, Sumatra) were able to open these files because most parsers are extended to support non-compliant files.&lt;/p&gt;

&lt;p&gt;This serves as a brief survey of the challenges of parsing a single part of the PDF specification (22 pages out of 1,300 total from version 1.7).&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2025/8/pdf-parsing-xref</guid>
      <pubDate>Sun, 03 Aug 2025 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Laureles, Medellin swimming pools</title>
      <link>https://eliot-jones.com/2025/4/laureles-swimming-pools</link>
      <description>

&lt;p&gt;Just a brief note to summarise the (non-hotel) swimming pool situation in the Laureles area of Medellin since it is not easy to find/understand all this information.&lt;/p&gt;

&lt;p&gt;There are 3 primary organisation types that are relevant:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Inder. Run by the mayorality this sports department offers access to many different sports facilities for residents and visitors alike. Swimming can be accessed for free through Inder.&lt;/li&gt;
&lt;li&gt;Liga de Natacion de Antioquia. The swimming league of the department of Antioquia they share access to many of the same facilities with Inder; however they provide paid access to these facilities.&lt;/li&gt;
&lt;li&gt;Private organisations. A third category that runs some pools.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It's worth noting that for all pool types the required swimwear is a swimming cap (even for bald people) and lycra (not board) shorts. There are 2 shops at Estadio that sell these, one near the Inder entrance and the other behind the stairs at the Liga entrance. There may also be a shop at Belen.&lt;/p&gt;

&lt;h2&gt;Pools&lt;/h2&gt;

&lt;p&gt;The main pools of interest are the Estadio and Belen sites. Belen has a single Olympic pool (see the private swimming section for details on a second 25m pool in Belen) and Estadio has a range of pools including Olympic, sub-aquatic and many others.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Estadio, has an Inder gate with ticket office &lt;a href="https://maps.app.goo.gl/umPNvW4ut2P25Ghi9"&gt;here&lt;/a&gt; and a Liga gate &lt;a href="https://maps.app.goo.gl/TRHQBc9f2YJ5YFnF8"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Belen, the pool is &lt;a href="https://maps.app.goo.gl/A3SNC96GyKohaccK7"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Swimming with Inder&lt;/h2&gt;

&lt;p&gt;To use Inder pools with a reservation you will need to &lt;a href="https://simon.inder.gov.co/register/"&gt;register with Simon 2.0&lt;/a&gt;. Simon 2.0 is the booking platform for various sports facilities including the pools at Estadio and Belen. Once registered you can book access to a pool session for free, however as of Spring 2025 there is high demand and because many pools, including the Olympic pool, at Estadio are currently being refurbished the available reservation slots fill up quickly.&lt;/p&gt;

&lt;p&gt;Another approach is to join the queue for entry at the pool in Estadio. Each hour (or outside the hour at the discretion of the ticket office) a certain number of people are let in from the queue for free, again depending on occupancy. I don't have first-hand experience with it but in the week it apparently doesn't take too long if you go early. The non-reservation entry queue may also exist at Belen but I haven't validated this.&lt;/p&gt;

&lt;p&gt;You will need your original id, either passport or Cedula (no photocopies), to enter with Inder.&lt;/p&gt;

&lt;h2&gt;Swimming with the Liga&lt;/h2&gt;

&lt;p&gt;The &lt;a href="https://www.nadamejor.com.co/#/servicios/4"&gt;Liga de Natacion de Antioquia&lt;/a&gt; also operates at the Estadio and Belen locations. They don't seem to be mentioned if you ask about swimming in general at Inder locations.&lt;/p&gt;

&lt;p&gt;At Estadio you can enter the complex by the 'secret' Liga gate (Accesso #2) and go past the ticket offices and left, round the back to a ticket office where you can pay for individual entry between 9am - 3pm (~COP17.9k). However during the renovations it is hit-or-miss if they can allow this because of the reduced pool capacity. You can ask at the main ticket offices at this gate first to find out if it is possible, I have had varying success depending on the day and hour.&lt;/p&gt;

&lt;p&gt;The Liga also shares the Olympic pool in Belen with Inder. However you cannot pay for individual entry here, instead you must purchase an annual membership (~COP85k) and then purchase either a 10-swim or monthly (mensualidad) ticket. If you are in Medellin for a while this might be the most convenient approach since the hours for the Belen pool are longer and you don't have to reserve or take the chance in the queue. As of Spring 2025 the Liga hours for Belen are reported as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Monday, Wednesday, Friday: 6.30am - noon, 1pm - 4pm&lt;/li&gt;
&lt;li&gt;Tuesday, Thursday: 6am - noon, 1 - 4pm&lt;/li&gt;
&lt;li&gt;Saturday, Sunday: 7am - 2.45pm (subject to availability)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Liga ticket office at Belen is also not the easiest to find. You need to walk through the door and past the Inder front-desk and to the left to get to it and this is not obvious from outside. If you ask directly the Inder desk can point you to it.&lt;/p&gt;

&lt;p&gt;You will need your original id, either passport or Cedula (no photocopies), to enter with the Liga.&lt;/p&gt;

&lt;h2&gt;Private swimming&lt;/h2&gt;

&lt;p&gt;At Belen there is a second pool, the &lt;a href="https://maps.app.goo.gl/X5ku6oAVnqV2pKWg7"&gt;Piscina Corporación Deportiva y Cultural&lt;/a&gt;, which is operated by a private company. This is quite a shallow pool 1.1 of metres but has good changing facilities and a secure place to leave your bags. This only costs COP12k for a single ticket with no reservations necessary. Note that there are times when the pool is reserved for classes so you need to confirm the hours beforehand. As of Spring 2025 these are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Monday - Friday: 10am - noon, 1pm - 4pm&lt;/li&gt;
&lt;li&gt;Saturday: 11am - 3pm&lt;/li&gt;
&lt;li&gt;Sunday: 11am - 2pm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No id is needed for this pool.&lt;/p&gt;

&lt;p&gt;Also worth a mention is the &lt;a href="http://www.centroacuaticoydeestimulaciondianaespinosa.com/"&gt;Diana Espinosa Aquatics Center&lt;/a&gt; which are smaller pools offering classes for learners/aquafit. These are indoor heated pools.&lt;/p&gt;

&lt;p&gt;There may be more pools in this category but these are the ones I am aware of.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2025/4/laureles-swimming-pools</guid>
      <pubDate>Wed, 23 Apr 2025 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Writing Code for Fun and ... That's It</title>
      <link>https://eliot-jones.com/2023/7/faf-lobbysim</link>
      <description>

&lt;p&gt;Supreme Commander: Forged Alliance is a real-time strategy (RTS) game released in 2007. It is also the last good RTS, and potentially game, ever.&lt;/p&gt;

&lt;p&gt;Despite this most gamers &amp;#8212; not realizing gaming reached a pinnacle in 2007 and has since descended into a mess of RPGification, Loot Boxes and bloom over-use &amp;#8212; have moved on to other games and more importantly other genres&lt;sup&gt;1&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;One need only look at the modern-game design horrors unleashed on the Dawn of War genre to see the decline of RTS and gaming generally more clearly. From the high-point of Dawn of War: Winter Assault in 2005 to the best-forgotten mess of Dawn of War III in 2017 everything has been ruined irrevocably. Nothing is good anymore, food doesn't taste the same, music isn't what it was&lt;sup&gt;2&lt;/sup&gt;. I'm not getting old, things are getting worse. I'm still cool and relevant!&lt;/p&gt;

&lt;p&gt;Few things in gaming quite match the state of stressed, overwhelmed, misery induced by Forged Alliance. Thankfully the &lt;a href="https://www.faforever.com/"&gt;Forged Alliance Forever&lt;/a&gt; (FAF) project has continued to develop Forged Alliance, providing graphical updates, balance changes, matchmaking, performance improvements, new maps and more.&lt;/p&gt;

&lt;p&gt;Because gamers have departed from the True Path matchmaking generally takes a while. A small active user-base means that depending on the time of day and day of week you can be waiting anywhere from 10 minutes to over an hour for a lobby (the pre-game matchmaking bit) to fill.&lt;/p&gt;

&lt;p&gt;It is generally necessary to be ready to balance and start the lobby within a few minutes of it filling. If there's too much of a delay everyone will leave again and the waiting time will have been wasted.&lt;/p&gt;

&lt;p&gt;Which brings me to the justification for my project, &lt;a href="https://github.com/EliotJones/FaFLobbySim"&gt;FAF Lobby Sim&lt;/a&gt;. While the lobby is running on my desktop I don't want to have to sit checking it every few minutes. It would be good to be able to do other things elsewhere while having a way to check on the occupancy status.&lt;/p&gt;

&lt;h3&gt;Design Log&lt;/h3&gt;

&lt;p&gt;What follows is the 'design' process I followed. As you can tell from reading it I really wasn't worrying too much about doing it right, just doing the bare minimum. Developing this way was fun, a nice break from proper open-source and job related development. I wanted to stay in C# .NET because it is the language I know best.&lt;/p&gt;

&lt;p&gt;Whatever is stopping you starting on some project I hope this transparency helps encourage you to just churn out some code and get something shipped.&lt;/p&gt;

&lt;h4&gt;Getting started&lt;/h4&gt;

&lt;p&gt;So the lobby application is running on my computer and I want to check its status on my phone. The lobby for FAF involves 2 running processes. The Forged Alliance game application itself and the Java FAF client application.&lt;/p&gt;

&lt;p&gt;The Java client consumes an API that can report the active lobbies and the occupancy state. This seems a natural starting point. If I can call the same APIs from a mobile client then I'll be done. There are 2 drawbacks to this though:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The API uses OAuth tokens for authentication. I'd need to get my own client id to call it. This is the sort of un-fun development work that involves coordinating between people and waiting for things to get done. Fine for work, not for a weekend project.&lt;/li&gt;
&lt;li&gt;While the occupancy reported to the client by the API is generally correct it doesn't match the real state when open slots are manually marked 'closed' from within the game process. This can happen if a map has 12 slots but 2 of them would have insufficient resources. This is a rarity but combined with point 1 made me consider a different approach.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I hatched a Heath Robinson style plan. If I could run some client monitoring application on my desktop, pass the information to some server and then interact with that server from mobile I'd own all the hops. Should be easy right?&lt;/p&gt;

&lt;p&gt;What's a plan without some arbitrary constraints? Since the client app will be calling a server I want to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Make the client app small, with minimal dependencies.&lt;/li&gt;
&lt;li&gt;Not pass anything other than the bare minimum information to the server.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;Building the client app&lt;/h4&gt;

&lt;p&gt;So I've done some work with the FlaUI automation library in the past. Here's a &lt;a href="https://github.com/EliotJones/FizzBuzzCalc"&gt;FizzBuzz implementation using the Windows 10 calculator&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If I can use FlaUI and grab the information I need from the game lobby process it should be fairly simple. Just poll the game in a loop and report the information to the server. This will address the second drawback listed for using the API directly, since I'm reporting the actual game-state.&lt;/p&gt;

&lt;p&gt;So I launch up &lt;a href="https://github.com/FlaUI/FlaUInspect"&gt;the FlaUI inspector tool&lt;/a&gt; and... there's nothing there, just the window of the process. This is to be expected, it's a game after all, not a UI. The Java client process is far more amenable to UI automation, but it doesn't solve the real-state/closed slots problem I've now fixated on solving.&lt;/p&gt;

&lt;p&gt;I vaguely recall a former boss once used OpenCV to 'bot' a simple game. I guess I can do something similar here. Since FlaUI can take screenshots of the open desktop it should be possible to parse out the info I need using image processing. I definitely don't want to send the screenshots to the server process since they will capture the entire desktop, not just the monitored process if other windows are moved in front of the monitored application.&lt;/p&gt;

&lt;h4&gt;Image processing&lt;/h4&gt;

&lt;p&gt;&lt;a href="/images/lobbysim/sample-lobby.png" target="_blank"&gt;
&lt;img src="/images/lobbysim/sample-lobby.png" alt="lobby screenshot" /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This screenshot shows the layout we need to parse. We 'just' need to pull out the number of "Open", "Closed" and occupied slots in the Nickname column.&lt;/p&gt;

&lt;p&gt;Obviously we don't want to hardcode the positions since the game can run windowed or full-screen on different resolutions. The number of slots can vary from 2 - 16.&lt;/p&gt;

&lt;p&gt;The obvious approach is to use OCR, e.g. Tesseract, to process the text and calculate occupancy from the Nickname column. Pulling in Tesseract means that you have a large dependency for the client application which isn't great if you want to redistribute it. Like everything it's much harder to get Tesseract working on Windows where this client app would be running.&lt;/p&gt;

&lt;p&gt;I also played around with OpenCV and edge detection but didn't want the dependency or to read the documentation to figure out what I needed to do. So I settled on the questionable strategy of building the processing myself.&lt;/p&gt;

&lt;p&gt;The first step is to threshold the image to simplify the input data. Playing around with the image in GIMP I found a reasonable threshold value:&lt;/p&gt;

&lt;p&gt;&lt;a href="/images/lobbysim/sample-lobby-thresholded.png" target="_blank"&gt;
&lt;img src="/images/lobbysim/sample-lobby-thresholded.png" alt="lobby screenshot with threshold applied" /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Applying a threshold to the screenshot was a simple one-liner with ImageSharp:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;image.Mutate(x =&amp;gt; x.BinaryThreshold(0.39f));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I could then map the thresholded image to a C# &lt;code&gt;BitArray&lt;/code&gt; to make it more memory efficient to work with. This would involve flattening the 2D image to an array so it was necessary to have a couple of methods to convert to/from 2D to 1D space:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private static int XyToFlat(int x, int y, WidthHeight widthHeight)
        =&amp;gt; (y * widthHeight.Width) + x;

private static (int x, int y) FlatToXy(int index, WidthHeight widthHeight)
{
    var y = index / (widthHeight.Width);
    var x = index - (y * widthHeight.Width);
    return (x, y);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With these methods mapping a black-and-white image to a bit array is simple:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private static BitArray FlattenThresholded(Image&amp;lt;Rgb24&amp;gt; image, WidthHeight wh)
{
    var result = new BitArray(image.Height * image.Width);

    for (int row = 0; row &amp;lt; image.Height; row++)
    {
        for (int col = 0; col &amp;lt; image.Width; col++)
        {
            var flatIndex = XyToFlat(col, row, wh);
            if (image[col, row].R == 255)
            {
                result[flatIndex] = true;
            }
        }
    }

    return result;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So now we have our image in a black-and-white array (0 and 1). What next?&lt;/p&gt;

&lt;p&gt;Well looking at the example thresholded image we can see that the region of interest is the table highlighted in orange:&lt;/p&gt;

&lt;p&gt;&lt;a href="/images/lobbysim/sample-lobby-thresholded-target-extracted.png" target="_blank"&gt;
&lt;img src="/images/lobbysim/sample-lobby-thresholded-target-extracted.png" alt="Table of interest in orange" /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If the slot is open there are 2 'words' in the Nickname column, "Open" and the chevron symbol for the dropdown containing the option to move into the slot or, if you are the host, close the slot. When I say 'word' here I mean nothing more group of pixels since this can be actual text, a faction symbol, a country flag, a block of color, or something else.&lt;/p&gt;

&lt;p&gt;If the slot is closed there is only the word "Closed" and no chevron.&lt;/p&gt;

&lt;p&gt;For slots occupied by a player there's either the player name and a chevron or, for the current user, simply the username.&lt;/p&gt;

&lt;p&gt;Without OCR to distinguish between "Closed", "Open" and the current username you also need to use the "R" (Rank), "G" (Game count) or "Team" column to identify that a player occupies the current slot (the 'word' in the "Color" column may disappear due to thresholding).&lt;/p&gt;

&lt;p&gt;The approach becomes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Locate the table and columns.&lt;/li&gt;
&lt;li&gt;If the Nickname column contains 1 word and no entries in other columns it is closed.&lt;/li&gt;
&lt;li&gt;If the Nickname column contains 1 word and there are entries in other columns it is occupied by the current player (assuming a single word nickname)&lt;/li&gt;
&lt;li&gt;If the Nickname contains 2 (or more) words and no entries in other columns it is open.&lt;/li&gt;
&lt;li&gt;If the Nickname contains 2 (or more) words and one of the other columns (excluding "--") is occupied then the slot is occupied&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To locate the table without hardcoding the position we need to first detect 'words'. As mentioned above these might be non-word groups of pixels but for our purposes since we're not running OCR the distinction is meaningless.&lt;/p&gt;

&lt;p&gt;How do we detect words? Let's take a look at the "Nickname" text from the thresholded image:&lt;/p&gt;

&lt;p&gt;&lt;a href="/images/lobbysim/scaled-nickname-thresholded.png" target="_blank"&gt;
&lt;img src="/images/lobbysim/scaled-nickname-thresholded.png" alt="Nickname text" /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you're scanning the image top-to-bottom left-to-right when you first encounter a white pixel (marked in green in the image below) you can start the following process:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Look around the neighboring pixels (ignoring pixels to the top-left since we scanned from that location) in a 9-by-9 region.&lt;/li&gt;
&lt;li&gt;Each time you find a white pixel in the neighborhood then move to that pixel (new green pixel), recording where you came from (marked blue in the image).&lt;/li&gt;
&lt;li&gt;Scan the neighborhood of the new pixel and move to any non-visited white pixels in that location (the new green pixel).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first steps of this are shown below, the colors are purely illustrative:&lt;/p&gt;

&lt;p&gt;&lt;a href="/images/lobbysim/scaled-nickname-step-2.png" target="_blank"&gt;
&lt;img src="/images/lobbysim/scaled-nickname-step-2.png" alt="Initial flood fill steps" /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is basically just a flood fill algorithm except you allow for gaps, both for diagonal pixels and entirely disjoint pixels like the dot on the 'i' and next letters in the word.&lt;/p&gt;

&lt;p&gt;The problem with this approach is I wrote it recursively and it causes a stack overflow if the region to be filled is too large. Since large regions are just background noise in the thresholded image I just exit the recursion early if the region to be filled is too large, for some arbitrary value of too large. I should probably have implemented a proper flood fill algorithm instead.&lt;/p&gt;

&lt;p&gt;Full code for this &lt;a href="https://github.com/EliotJones/FaFLobbySim/blob/main/FaFLobbySim/FaFLobbySimClient/DetectImageWords.cs"&gt;is here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using this flood fill word detection the resulting words are fairly well detected and defined:&lt;/p&gt;

&lt;p&gt;&lt;a href="/images/lobbysim/words-detected.png" target="_blank"&gt;
&lt;img src="/images/lobbysim/words-detected.png" alt="With word boundaries highlighted" /&gt;
&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once the 'words' are detected there are just some fairly &lt;a href="https://github.com/EliotJones/FaFLobbySim/blob/main/FaFLobbySim/FaFLobbySimClient/CalculateLobbyOccupancy.cs"&gt;gnarly heuristics&lt;/a&gt; to group them into lines and identify the table header and columns.&lt;/p&gt;

&lt;h3&gt;Building the server app&lt;/h3&gt;

&lt;p&gt;The client runs in a loop, every 5 seconds it uses FlaUI to take a screenshot of the lobby process, run word detection and use the heuristics discussed earlier to calculate the total slots and number occupied.&lt;/p&gt;

&lt;p&gt;The server part is an incredibly simple MVC app that just holds the data in memory. The client posts to the &lt;a href="https://github.com/EliotJones/FaFLobbySim/blob/main/FaFLobbySimServer/Controllers/UploadController.cs"&gt;controller&lt;/a&gt; which stores the latest occupancy and sends a server-sent event to any clients monitoring the lobby.&lt;/p&gt;

&lt;p&gt;The idea is each lobby will be assigned a random identifier by the client on startup and multiple clients and lobbies may report occupancy to the server based on the identifier. In order just to ship it I hardcoded the lobby to a single identifier at this stage.&lt;/p&gt;

&lt;p&gt;The final product is not great looking, but does work, and seems to update fairly reliably:&lt;/p&gt;

&lt;p&gt;&lt;img src="/images/lobbysim/lobby-monitor-site.png" alt="The web UI showing 2 of 10 slots occupied" /&gt;&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Really at this point I couldn't be bothered to put in the necessary work to 'productionize' it. To make a real usable implementation I'd need to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Address the test case that is failing due to thresholding in ImageSharp not matching GIMP&lt;/li&gt;
&lt;li&gt;Make the heuristics for occupancy detection less flaky&lt;/li&gt;
&lt;li&gt;Package the client application and make it more reliable&lt;/li&gt;
&lt;li&gt;Improve the web UI and add rate limiting and other DDOS protection&lt;/li&gt;
&lt;li&gt;Dynamically generate lobby ids and assign a random token to each lobby id so only the client that first reports values for the lobby can send updates for it&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With all those to-dos in mind I'm pleased I managed to get anything shipped and the few times I've used it it has meant I can get live updates pushed to my phone while being away from the computer.&lt;/p&gt;

&lt;p&gt;The code for the client app is super funky and not at all idiomatic C#. I'm hoping to write a post about why I wrote it that way and what I learned from it soon.&lt;/p&gt;

&lt;h4&gt;Footnotes&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;An honorary mention to &lt;a href="https://www.beyondallreason.info/"&gt;Beyond All Reason&lt;/a&gt; an open-source spiritual successor to Supreme Commander.&lt;/li&gt;
&lt;li&gt;I don't believe this at all.&lt;/li&gt;
&lt;/ol&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2023/7/faf-lobbysim</guid>
      <pubDate>Sun, 30 Jul 2023 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Blog Update</title>
      <link>https://eliot-jones.com/2023/7/blog-update-net-7</link>
      <description>

&lt;p&gt;As this blog entered its tenth year it was desperately in need of a facelift. I had effectively stopped writing new posts because the overhead of remembering how to upload a new post each time was off-putting enough to stop me entirely.&lt;/p&gt;

&lt;p&gt;For that reason it has been updated with new - hopefully more consistent - CSS. In addition the code and posts are deployed on each commit by GitHub actions. This means I no longer need to SSH into the server to do things by hand. This should mean the blog is editable from wherever I have git access. I also removed the terribly insecure previous method of uploading posts directly onto the server which was using a plain-text username and password.&lt;/p&gt;

&lt;p&gt;Most importantly privacy-invading Google Analytics has been removed along with almost all JavaScript. I no longer see the need for analytics on this blog. The only remaining scripts are for code highlighting client-side as well as Disqus for commenting. Disqus is opt-in so will only load in if you click the "Load Comments" button at the bottom of each post.&lt;/p&gt;

&lt;p&gt;Unfortunately I still rely on Google Fonts for the title font but the main body font has been updated to use the system font stack.&lt;/p&gt;

&lt;p&gt;Finally it has been updated to .NET 7. &lt;a href="https://github.com/EliotJones/LightBlog/blob/release/EliotJones/LightBlog.csproj"&gt;The previous version&lt;/a&gt; was running .NET Core 1.1 and hadn't been updated since 2017. So much for keeping software up-to-date! &lt;a href="https://github.com/EliotJones/eliot-jones-blog/blob/main/src/LightBlog.Server/LightBlog.Server.csproj"&gt;The new version&lt;/a&gt; is on .NET 7 and the upgrade process was surprisingly easy.&lt;/p&gt;

&lt;p&gt;While the changes between the ASP .NET versions have been a little hard to keep track of with &lt;code&gt;Startup.cs&lt;/code&gt; being removed and everything moving into &lt;code&gt;Program.cs&lt;/code&gt; the migration was made simple by my lazy cheat. I just created a new ASP .NET 7 application from the template in Visual Studio and moved most of the files without any changes, except to update the namespaces.&lt;/p&gt;

&lt;p&gt;I also took the opportunity to add caching. Previously it loaded every post file from disk repeatedly just to show a single page. Now, because posts are only updated whenever the app itself is deployed and restarted, cache invalidation is trivial.&lt;/p&gt;

&lt;p&gt;I have added the images into git too which generally causes a lot of squawking from people who use git properly (nerds), but keeping things simple should hopefully mean I fall into the pit of success. Each PNG image has been compressed further where possible.&lt;/p&gt;

&lt;h3&gt;Deployment&lt;/h3&gt;

&lt;p&gt;Deployment of the blog is pretty much unchanged from the initial set-up following &lt;a href="https://www.hanselman.com/blog/publishing-an-aspnet-core-website-to-a-cheap-linux-vm-host"&gt;the guide by Scott Hanselman&lt;/a&gt; for deploying .NET to a Linux server such as a DigitalOcean VPS. This may no longer be best-practice but has been working for me uninterrupted for over half a decade.&lt;/p&gt;

&lt;p&gt;My DigitalOcean VPS is the cheapest tier ($5 a month originally, now $6-something thanks to inflation) and hosts this blog plus a couple of other applications.&lt;/p&gt;

&lt;p&gt;The application is published from either my Windows machine or the GitHub CI runner using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dotnet publish -c Release -r linux-x64
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which generates a self-contained application (when &lt;code&gt;&amp;lt;SelfContained&amp;gt;&lt;/code&gt; is defined in the .csproj file). The application is then copied to the server (not directly to the deployed directory since this is locked by the running app) using scp:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;scp -r /c/path/to/publish username@ip-or-host:/path/on/remote
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each application is deployed to the &lt;code&gt;/var/{app-folder}&lt;/code&gt; directory on the server and launched and managed by &lt;a href="http://supervisord.org/"&gt;Supervisor&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The Supervisor config files live at &lt;code&gt;/etc/supervisor/conf.d&lt;/code&gt;. Each file defines an application for Supervisor to manage. This blog lives under &lt;code&gt;/var/blog&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[program:blog]
command=/usr/bin/dotnet /var/blog/LightBlog.Server.dll --server.urls:http://*:5000
directory=/var/blog
autostart=true
autorestart=true
stderr_logfile=/var/log/blog.err.log
stdout_logfile=/var/log/blog.out.log
environment=ASPNETCORE_ENVIRONMENT=Production
user=www-data
stopsignal=INT
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To copy the newly &lt;code&gt;scp&lt;/code&gt; published app to the &lt;code&gt;/var/{app-folder}&lt;/code&gt; directory the running application (named blog) is first stopped using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;supervisorctl stop blog
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The existing files are then cleared, the newly uploaded files copied to the target folder and finally the blog restarted using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;supervisorctl start blog
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are more details in Scott's blog-post for configuring NGINX as a reverse proxy and using Let's Encrypt to expose the site over HTTPS.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://github.com/EliotJones/eliot-jones-blog/blob/main/.github/workflows/build-and-deploy.yml"&gt;GitHub actions workflow for deployments is here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Well that's all for this update. I'm hoping to write a post about building stupid code for fun &lt;a href="http://eliot-jones.com:6575/"&gt;to explain FAF Lobby Sim&lt;/a&gt; (warning, not HTTPS!) soon, but based on my track record see you in 2030...&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2023/7/blog-update-net-7</guid>
      <pubDate>Sat, 29 Jul 2023 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Visual Studio 2022 Debugger Freezes</title>
      <link>https://eliot-jones.com/2022/2/visual-studio-2022-freeze-debug</link>
      <description>

&lt;p&gt;Wow, blogging with any kind of regularity is hard I kind of hard I guess. Who knew?&lt;/p&gt;

&lt;p&gt;Anyway this was just a quick note for a problem I had recently.&lt;/p&gt;

&lt;p&gt;I found that my Visual Studio 2022 debugger would hang, freeze or become unresponsive intermittently.
Prior to the last update the process would freeze completely, however even after updating it would
freeze though the IDE itself would remain responsive.&lt;/p&gt;

&lt;p&gt;This freeze seemed to trigger more frequently when using time-travel debugging.&lt;/p&gt;

&lt;p&gt;As usual when weird things happen the antivirus was to blame.&lt;/p&gt;

&lt;p&gt;Excluding the process named &lt;code&gt;VsDebugConsole.exe&lt;/code&gt; seemed to resolve at least all the debugger hangs
after adding the exclusion. No doubt some more will occur but at least VS22 is usable again.&lt;/p&gt;

&lt;p&gt;To get to exclusions on Windows 10 (old-skool) go to Windows Security -&gt; Virus &amp;amp; threat protection -&gt;
Virus &amp;amp; threat protection settings -&gt; Manage settings -&gt; Exclusions -&gt; Add or remove exclusions.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2022/2/visual-studio-2022-freeze-debug</guid>
      <pubDate>Fri, 18 Feb 2022 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Attention Bubbles (Or Why Everything Happens So Much)</title>
      <link>https://eliot-jones.com/2020/1/hackernews-trends</link>
      <description>

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/horse-ebooks.png" alt="horse_ebooks tweet &amp;quot;Everything happens so much&amp;quot;" /&gt;&lt;/p&gt;

&lt;p&gt;Like most side projects that devour hours of time and end up being entirely useless, this one started with a simple question:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Can recessions be predicted by increased interest in news stories about recessions?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The background behind this question -- and you'll have to forgive my complete ignorance of basically the entire field of economics -- is that recessions are a feature of capitalist economies. From what little I've read (and understood); during a boom, businesses scale up their operations to produce more and more "stuff". At a certain point the amount of "stuff" exceeds the demand for "stuff" and businesses and sectors are left holding a load of plant/equipment/employees they no longer need.&lt;/p&gt;

&lt;p&gt;From this (probably wrong) summary of boom and bust it seems there's a certain extent to which recessions are based on people getting scared. When a consumer/business has lower confidence they're less likely to buy a new thing or make a plan for something, thereby reducing demand. This has a cascade effect throughout the market and causes a crash. It's basically a mass-panic. (I appreciate this description is probably making a lot of economists very angry, but I'll counter with my (tongue-in-cheek) belief that neither economics nor money are real, they're just belief systems.)&lt;/p&gt;

&lt;p&gt;Given the mass-panic and social nature of recessions we should be able to spot the signs of a panic slightly before they happen. In the same way that you could tell that TikTok was going to be the next big thing -- yes this is probably going to date this article horribly by the end of the month -- by looking in the right places for increased interest in the app, signs of decreasing confidence should appear somewhat before the main event.&lt;/p&gt;

&lt;p&gt;For this analysis I turned to what I affectionately call the "Orange Hell Site". &lt;a href="https://news.ycombinator.com/"&gt;Hacker News&lt;/a&gt; is a site for news stories across a wide range of topics, mainly focused on topics of interest to Silicon Valley; technology, economics, science and Venture Capitalist culture. Because of its Silicon Valley focus it tends to broadly reflect the beliefs of the elite in Silicon Valley; whether that's techno-utopian solutions to the climate crisis or the belief that someone with no qualifications working 2 minimum wage jobs can reach FIRE (Financial Independence Retire Early) just by applying themselves. This also means it takes a keen interest in all things financial markets, stocks, shares and whatever-the-hell RSUs are.&lt;/p&gt;

&lt;p&gt;TLDR: by looking at what people with a lot of involvement and interest in the stock market are talking about we're going to see if recessions might have signals preceding them.&lt;/p&gt;

&lt;p&gt;One of the main problems with this approach is that fortunately for everyone but unfortunately for the analysis, recessions don't happen often. The last Big One was 2007/8, it seems likely we're due another one anytime soon, but by their very nature that's impossible to predict. Hacker News launched in February of 2007, just before the last recession so we have a very limited set of data to look at.&lt;/p&gt;

&lt;h3&gt;Building It&lt;/h3&gt;

&lt;p&gt;The first problem I encountered was the nature of the &lt;a href="https://github.com/HackerNews/API"&gt;Hacker News API&lt;/a&gt;. While it was extremely useful to have any API, the design of the API requires enumerating every single story, comment, job posting and Ask HN by ID just to find the stories.&lt;/p&gt;

&lt;p&gt;I excluded comments from the analysis since they didn't really seem relevant. I was more interested in the higher-threshold activity of submissions since I felt they would more accurately reflect what was being seen by people.&lt;/p&gt;

&lt;p&gt;At the time the question came to mind I was observing what I believed to be a bubble in stories about recessions (August 2019). In order to validate the approach without enumerating all 22 million items (and flooding the API with requests) I initially downloaded the data with IDs from about 16 million to about 20 million (2017 - 2019).&lt;/p&gt;

&lt;p&gt;The initial dataset was, frankly, useless:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/initial-plot.png" alt="Image shows data from August 2017 to August 2019 with a small increase towards August 2019" /&gt;&lt;/p&gt;

&lt;p&gt;It did appear to show something like an increase in frequency of stories about recession though. I just needed a lot more data. &lt;/p&gt;

&lt;p&gt;This resulted in the need to enumerate the other 16 million entries from 0 - 16,000,000 as well as the new entries from 20 million - 22 million. The crawler I used for the first data-set was very slow. It was using a single thread and a delay between requesting each item (in an attempt to be a good citizen/API consumer) it had taken weeks of running the crawler overnight just to fill the initial 4 million set.&lt;/p&gt;

&lt;p&gt;Since I was running everything on my laptop and didn't want to pay anything to solve what was ultimately a stupid question, any solution was constrained by the lack of disk space, CPU and memory on my fairly cruddy laptop.&lt;/p&gt;

&lt;p&gt;The crawler went through many iterations before reaching its &lt;a href="https://github.com/EliotJones/HnTrends/tree/master/src/HnTrends.Crawler"&gt;final form&lt;/a&gt;. The final crawler is a C# .NET Core console application which uses a configurable number of threads and writes its data to a SQLite backing store. This SQLite database is shared by all applications/ Initially I used my own binary format to reduce file-size but this wasn't very useful when it came to running the crawler and querying the data from a web application.&lt;/p&gt;

&lt;p&gt;I also needed a way to view the data. There's probably a way to analyse the data with statistical methods but at this point my motivation changed from building some kind of predictive model (nowhere near enough data) to building something to visually inspect whether any topic, not just recessions, was undergoing what I call an "attention bubble". To this end I build an &lt;a href="https://github.com/EliotJones/HnTrends/tree/master/src/HnTrends"&gt;ASP.NET Core website&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As it turned out, perhaps unsurprisingly, running a `WHERE title LIKE '%recession%" search on SQLite is very slow. This was a good opportunity to learn a new thing, so I added a &lt;a href=""&gt;Lucene.NET&lt;/a&gt; index to the mix for free text search. The &lt;a href="https://github.com/EliotJones/HnTrends/tree/master/src/HnTrends.Indexer"&gt;indexer code is here&lt;/a&gt;, as it was my first time using Lucene.NET I think I probably missed a whole load of potential optimizations so it's still fairly slow, but much better than it was when using SQLite and probably acceptable.&lt;/p&gt;

&lt;p&gt;The end result is &lt;a href="http://eliot-jones.com:5690/"&gt;hosted here&lt;/a&gt;. It provides search capabilities for terms in story titles in Hacker News postings. Due to the aforementioned "not wanting to spend money on a stupid question", it's piggybacking on this blog's VPS (which is the lowest tier possible machine) so will fall over above about 3 concurrent users, so go easy on it. It runs an update every hour to crawl new stories and index them using ASP.NET Core's
 &lt;code&gt;BackgroundService&lt;/code&gt;. This should probably be hived off to a separate service but having it in-process makes cache invalidation a lot easier, though there's no real drawback to serving stale data for something like this. Also if you hit the site after a cache invalidation it's going to be super-slow for the first request.&lt;/p&gt;

&lt;p&gt;A disclaimer on the front-end code: I built the front-end as a means to an end (no pun intended). For this I used jQuery and didn't even bother retrieving the data from an API endpoint. Instead the data gets bundled up with the server HTML response. For this reason the front-end is a garbage fire.&lt;/p&gt;

&lt;h3&gt;Pretty Pictures&lt;/h3&gt;

&lt;p&gt;Enough talking, let's look at some of the data. First up, our (revised) initial question, was I observing an 'attention bubble' about recessions? This is the count of stories with "recession" in the title by month:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/recession-plot-month-count.png" alt="Shows a large spike in the region of interest (autumn 2019)" /&gt;&lt;/p&gt;

&lt;p&gt;Since there are more posts per-day nowadays it's also useful to look at the count as a percentage of all posts in the period. This is the same data as a percentage of stories in the period rather than count:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/recession-plot-month-percent.png" alt="Shows the same large spikes but 2007-2008 is a lot bigger, 2007/8 is circled in blue, 2019 in red" /&gt;&lt;/p&gt;

&lt;p&gt;Circled in blue is the last "Big One", 2007/8 but it has a long tail into 2009/10. In red is the peak I was observing in Fall/Autumn of 2019. It seems to have fizzled out, perhaps QE is keeping the economy afloat for a few more months, but it will be interesting to see how it develops. There was definitely a spike but whether it represents a foreshock is unknowable.&lt;/p&gt;

&lt;p&gt;An example of a pure attention bubble might be the "Cybertruck", Tesla's new electric truck announcement generated a lot of buzz, with people split between it being the worst vehicle ever designed or a design masterpiece:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/cybertruck-plot-month-count.png" alt="Shows a large spike in winter 2019 falling off again rapidly" /&gt;&lt;/p&gt;

&lt;p&gt;The big spike around the announcement seems to have fizzled out, again it will be interesting to see how it develops, if the Cybertruck is ever actually released.&lt;/p&gt;

&lt;p&gt;Another topic that is unfortunately in the news is the, as yet unnamed, coronavirus. The SARS crisis of 2003 was also a coronavirus which sadly killed quite a few people but was luckily contained, partly because people became symptomatic prior to being infectious; so people tended to have been contained prior to spreading the virus. (A great read on the topic of viruses including SARS as well as other zoonoses is &lt;a href="https://wordery.com/spillover-david-quammen-9780099522850"&gt;Spillover by David Quammen&lt;/a&gt;). Hopefully this coronavirus will also be easily contained. Again we see a huge spike of interest in this topic at the right of the graph, which will hopefully fizzle out quickly. Also circled in red are the only mentions of coronavirus in submissions prior to 2020:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/coronavirus-plot-month-count.png" alt="Shows a large spike happening right now and a couple of tiny mentions prior to 2014 circled in red" /&gt;&lt;/p&gt;

&lt;p&gt;On a less sombre note we can also look at how named technologies are trending, and how they trend after launch, for example Kubernetes as a % by month:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/kubernetes-plot-month-percent.png" alt="An increasing trend starting after 2014" /&gt;&lt;/p&gt;

&lt;p&gt;And the trend of another technology in the same field, Docker:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/docker-plot-month-percent.png" alt="An increasing trend starting around 2013 with the highest peak in 2015" /&gt;&lt;/p&gt;

&lt;h3&gt;Next Steps&lt;/h3&gt;

&lt;p&gt;I don't really intend to do much more work on this project, the result serves its purpose and I've got &lt;a href="https://github.com/UglyToad/PdfPig"&gt;PdfPig&lt;/a&gt; to keep me occupied. However some enhancements would be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Improve scoring of search terms in Lucene using boosting for certain fields.&lt;/li&gt;
&lt;li&gt;Improve performance. Other than putting it on a bigger machine it remains to be seen what the performance is like under high load. It's likely upgrading to .NET Core 3.0 from 2.1 would help here, there are a lot of performance improvements to the framework between these versions. It also seems like sharding the Lucene index might help but that's a lot of work for a side-project.&lt;/li&gt;
&lt;li&gt;Allow multiple trends on the same plot. It would be interesting to compare Kubernetes with Docker directly, or PyTorch with Tensorflow to get an idea of the relative trends in attention.&lt;/li&gt;
&lt;li&gt;Accounting for score received by the submission on Hacker News. This would probably be the most important metric to account for and in retrospect was the main thing I would have changed if I were starting building this now, storing a snapshot of the score -- perhaps after a lead time of several days -- would allow more interesting analysis of the popularity of the topics outside of a naive count.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;Bonus round, TikTok trend:&lt;/h4&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/hntrends/tiktok-plot-month-count.png" alt="TikTok count by month shows an increasing trend starting in June 2018" /&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2020/1/hackernews-trends</guid>
      <pubDate>Fri, 31 Jan 2020 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Bezier Curve Bounding Boxes</title>
      <link>https://eliot-jones.com/2019/12/cubic-bezier-curve-bounding-boxes</link>
      <description>

&lt;p&gt;One of the challenges for generating accurate character sizes in a PDF document I encountered while building &lt;a href="https://github.com/UglyToad/PdfPig"&gt;PdfPig&lt;/a&gt; was working out the bounding box for a cubic Bezier curve.&lt;/p&gt;

&lt;p&gt;A &lt;a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B%C3%A9zier_curves"&gt;cubic Bezier curve&lt;/a&gt; is defined by 4 points; the start, end and 2 control points.&lt;/p&gt;

&lt;p&gt;We can number the points for use in the formulae in this post:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Start: P0&lt;/li&gt;
&lt;li&gt;Control 1: P1&lt;/li&gt;
&lt;li&gt;Control 2: P2&lt;/li&gt;
&lt;li&gt;End: P3&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This gives the formula for the Bezier curve:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/504c44ca5c5f1da2b6cb1702ad9d1afa27cc1ee0" alt="formula from Wikipedia" /&gt;&lt;/p&gt;

&lt;p&gt;We can take advantage of the property that the gradient of the curve will be 0 at the bounds of the curve (as well as including the start and end of the curve).&lt;/p&gt;

&lt;p&gt;To find where the gradient is 0 we can differentiate the curve and then solve the differentiated equation for 0.&lt;/p&gt;

&lt;p&gt;The formula differentiated (from Wikipedia) is:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/bda9197c2e77c17d90839b951cb0035d79c8d417" alt="formula from Wikipedia" /&gt;&lt;/p&gt;

&lt;p&gt;Where &lt;code&gt;P0&lt;/code&gt; is the start control point with both x and y values. Taking just the X dimension (and moving the &lt;code&gt;(1 - t)&lt;/code&gt;), we rewrite the formula as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;P'(x) = 3(P1.x - P0.x)(1 - t)^2 + 6(P2.x - P1.x)(1 - t)t + 3(P3.x - P2.x)t^2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next we can assign some names to some known values:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var i = (P1.x - P0.x)
var j = (P2.x - P1.x)
var k = (P3.x - P2.x)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Allowing us to rewrite the formula as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;P'(x) = 3i(1 - t)^2 + 6j(1 - t)t + 3kt^2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let's multiply out the full thing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;P'(x) = 3i - 3it - 3it + 3it^2 + 6jt - 6jt^2 + 3kt^2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And tidy it up a bit:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;P'(x) = 3i - 6it + 6jt + 3it^2 - 6jt^2 + 3kt^2
P'(x) = 3i + (-6i + 6j)t + (3i - 6j + 3k)t^2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Given we are finding the point where the gradient is 0:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;3i + (-6i + 6j)t + (3i - 6j + 3k)t^2 = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we reorder the terms we see this is a quadratic equation in disguise:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(3i - 6j + 3k)t^2 + (-6i + 6j)t + 3i = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The quadratic equation given by:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ax^2 + bx + c = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Means we need the following values:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;a = (3i - 6j + 3k);
b = (6j - 6i);
c = 3i;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is just a quadratic equation which we can solve using the quadratic formula to find the value of t:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = -b (+/-) sqrt(b^2 - 4ac)) / 2a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We will get between 0 and 2 solutions for &lt;code&gt;t&lt;/code&gt; depending on if:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;b^2 - 4ac
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Is greater than zero. In addition the start and end control points provide us with the other points to build our bounding box.&lt;/p&gt;

&lt;p&gt;How might this look in code? My &lt;a href="https://github.com/UglyToad/PdfPig/blob/master/src/UglyToad.PdfPig/Geometry/PdfPath.cs#L521"&gt;full implementation is here&lt;/a&gt; which is used to calculate the bounding box of Bezier curves in PDF documents and Type 1 fonts.&lt;/p&gt;

&lt;p&gt;To start with let's define our points:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Point start = new Point(5, 7);
Point end = new Point(10, 9);
Point control1 = new Point(6, 5);
Point control2 = new Point(9, 12);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now taking just the x dimension and the naming we established above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;double p0 = start.X;
double p1 = control1.X;
double p2 = control2.X;
double p3 = end.X;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can substitute our named values (i, j and k):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;double i = p1 - p0;
double j = p2 - p1;
double k = p3 - p2;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now for the parts of the quadratic equation (a, b and c) we established above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;double a = (3i - 6j + 3k);
double b = (6j - 6i);
double c = 3i;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;First we need to check if there are any real numbers that solve the &lt;code&gt;sqrt(b^2 - 4ac)&lt;/code&gt; part of the quadratic equation. If the result of &lt;code&gt;b^2 - 4ac&lt;/code&gt; is negative there are only imaginary solutions to the problem.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;double sqrtPart = (b * b) - (4 * a * c);
bool hasSolution = sqrtPart &amp;gt;= 0;
if (!hasSolution) return;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we have real solutions to the square root we can then evaluate the solutions for the value of t:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;double t1 = (-b + Math.Sqrt(sqrtPart)) / (2 * a);
double t2 = (-b - Math.Sqrt(sqrtPart)) / (2 * a);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For Bezier curves, values of &lt;code&gt;t&lt;/code&gt; are only valid if they lie between 0 and 1, so if we have values in this range we can substitute them into the original Bezier equation to find the minimum and maximum values of x:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;P = (1 - t)^3(P0) + 3(1 - t)^2(t)(P1) 
    + 3(1 - t)(t^2)(P2) + (t^3)P3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So in code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static double GetSolutionForT(double t, double p0, double p1, double p2, double p3)
{
    double oneMinusT = (1 - t);

    return (Math.Pow(oneMinusT, 3) * p0)
        + (3 * Math.Pow(oneMinusT, 2) * t * p1)
        + (3 * oneMinusT * Math.Pow(t, 2) * p2)
        + (Math.Pow(t, 3) * p3);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will give 0, 1 or 2 solutions for t (depending on whether t0 and t1 were in the range 0 to 1). The same equation can then be run for y by simply setting &lt;code&gt;p0 = start.Y;&lt;/code&gt; and the same for other points.&lt;/p&gt;

&lt;p&gt;The full code is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public struct Point
{
    public double X { get; }
    public double Y { get; }

    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }
}

public struct Rectangle
{
    public Point Min { get; }
    public Point Max { get; }

    public Rectangle(Point min, Point max)
    {
        Min = min;
        Max = max;
    }
}

public static class BezierSolution
{
    public static Rectangle GetBounds(Point start, Point control1, Point control2, Point end)
    {
        (double? solX1, double? solX2) = SolveQuadratic(start.X, control1.X, control2.X, end.X);
        (double? solY1, double? solY2) = SolveQuadratic(start.Y, control1.Y, control2.Y, end.Y);

        var minX = Math.Min(start.X, end.X);
        var maxX = Math.Max(start.X, end.X);

        if (solX1.HasValue)
        {
            minX = Math.Min(minX, solX1.Value);
            maxX = Math.Max(maxX, solX1.Value);
        }

        if (solX2.HasValue)
        {
            minX = Math.Min(minX, solX2.Value);
            maxX = Math.Max(maxX, solX2.Value);
        }

        var minY = Math.Min(start.Y, end.Y);
        var maxY = Math.Max(start.Y, end.Y);

        if (solY1.HasValue)
        {
            minY = Math.Min(minY, solY1.Value);
            maxY = Math.Max(maxY, solY1.Value);
        }

        if (solY2.HasValue)
        {
            minY = Math.Min(minY, solY2.Value);
            maxY = Math.Max(maxY, solY2.Value);
        }

        return new Rectangle(new Point(minX, minY), new Point(maxX, maxY));
    }

    private static (double? solution1, double? solution2) SolveQuadratic(double p0, double p1, double p2, double p3)
    {
        double i = p1 - p0;
        double j = p2 - p1;
        double k = p3 - p2;

        // P'(x) = (3i - 6j + 3k)t^2 + (-6i + 6j)t + 3i
        double a = (3 * i) - (6 * j) + (3 * k);
        double b = (6 * j) - (6 * i);
        double c = (3 * i);

        double sqrtPart = (b * b) - (4 * a * c);
        bool hasSolution = sqrtPart &amp;gt;= 0;
        if (!hasSolution)
        {
            return (null, null);
        }

        double t1 = (-b + Math.Sqrt(sqrtPart)) / (2 * a);
        double t2 = (-b - Math.Sqrt(sqrtPart)) / (2 * a);

        double? s1 = null;
        double? s2 = null;

        if (t1 &amp;gt;= 0 &amp;amp;&amp;amp; t1 &amp;lt;= 1)
        {
            s1 = GetBezierValueForT(t1, p0, p1, p2, p3);
        }

        if (t2 &amp;gt;= 0 &amp;amp;&amp;amp; t2 &amp;lt;= 1)
        {
            s2 = GetBezierValueForT(t2, p0, p1, p2, p3);
        }

        return (s1, s2);
    }

    private static double GetBezierValueForT(double t, double p0, double p1, double p2, double p3)
    {
        double oneMinusT = 1 - t;

        return (Math.Pow(oneMinusT, 3) * p0)
                + (3 * Math.Pow(oneMinusT, 2) * t * p1)
                + (3 * oneMinusT * Math.Pow(t, 2) * p2)
                + (Math.Pow(t, 3) * p3);
    }
}
&lt;/code&gt;&lt;/pre&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2019/12/cubic-bezier-curve-bounding-boxes</guid>
      <pubDate>Wed, 18 Dec 2019 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Open and Create PNG Images in C#</title>
      <link>https://eliot-jones.com/2019/12/create-png-csharp</link>
      <description>

&lt;p&gt;I wanted a platform independent way to open and create PNG images in C#. &lt;a href="https://github.com/EliotJones/BigGustave"&gt;BigGustave&lt;/a&gt; is a new library which provides a .NET Standard 2.0 compatible way of opening and creating PNG images.&lt;/p&gt;

&lt;p&gt;To open a png image you can pass either the bytes or the stream of the image to &lt;code&gt;Png.Open&lt;/code&gt; and then retrieve the values for pixels at any location in the image:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Png png = Png.Open(File.ReadAllBytes(@"C:\pictures\example.png"));
Pixel first = png.GetPixel(0, 0);
Console.WriteLine($"R: {first.R}, G: {first.G}, B: {first.B}");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To create a .png image in C# use the &lt;code&gt;PngBuilder&lt;/code&gt; to define pixel values before saving to an output stream:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var builder = PngBuilder.Create(2, 2, false);

var red = new Pixel(255, 0, 0);

builder.SetPixel(red, 0, 0);
builder.SetPixel(red, 1, 1);

using (var memory = new MemoryStream())
{
    builder.Save(memory);

    return memory.ToArray();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;BigGustave is completely open source and is &lt;a href="https://www.nuget.org/packages/BigGustave/"&gt;available on NuGet&lt;/a&gt; now so if you need very basic PNG manipulation tools for platform independent .NET code why not check it out?&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2019/12/create-png-csharp</guid>
      <pubDate>Wed, 18 Dec 2019 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>PdfPig Version 0.0.5</title>
      <link>https://eliot-jones.com/2018/12/pdfpig-version-005</link>
      <description>

&lt;p&gt;Today &lt;a href="https://www.nuget.org/packages/PdfPig/"&gt;version 0.0.5 of PdfPig was released&lt;/a&gt;. This is the first version which includes the ability to create PDF documents in C#.&lt;/p&gt;

&lt;p&gt;There aren't many fully open source options around for both reading and writing PDF documents so the addition of PDF document creation to PdfPig is an exciting next step for the API.&lt;/p&gt;

&lt;p&gt;The actual design of document creation isn't finished yet and there's more work to be done around the currently unsupported use cases such as splitting, merging and editing existing documents as well as adding non-ASCII text, working with forms and adding images to new documents but the functionality in 0.0.5 should provide enough for simple use cases and the open source Apache 2.0 license means that it can be used in commercial software.&lt;/p&gt;

&lt;p&gt;You can create a new document using a document builder:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PdfDocumentBuilder builder = new PdfDocumentBuilder();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This creates a completely empty document. To add the first page we use the imaginatively named add page method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PdfPageBuilder page = builder.AddPage(PageSize.A4);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This supports various page sizes defined by the &lt;code&gt;PageSize&lt;/code&gt; enum, such as the North American standard &lt;code&gt;PageSize.Letter&lt;/code&gt;. It also allows the choice of portrait (default) or landscape pages.&lt;/p&gt;

&lt;p&gt;Once a page builder has been created text, lines and rectangles can be added to it. &lt;/p&gt;

&lt;h3&gt;Fonts&lt;/h3&gt;

&lt;p&gt;In order to draw text a font must be chosen. Version 0.0.5 supports TrueType fonts as well as the 14 default fonts detailed in the PDF Specification. These are called the Standard 14 fonts and while their use is beginning to be phased out, all PDF readers should still support them.&lt;/p&gt;

&lt;p&gt;A Standard 14 font is the quickest way to get started since it doesn't require a TrueType file. Because the fonts are already well defined and included with PDF reading software the font does not need to be embedded in the PDF file, leading to much smaller file sizes. The available Standard 14 fonts are represented by the &lt;code&gt;Standard14Font&lt;/code&gt; enum. They are different flavours of the following fonts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Times New Roman&lt;/li&gt;
&lt;li&gt;Helvetica&lt;/li&gt;
&lt;li&gt;Courier&lt;/li&gt;
&lt;li&gt;Symbol&lt;/li&gt;
&lt;li&gt;Zapf Dingbats&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To use a font it should be registered with the document builder. By adding the font to the document builder rather than at the page level, it can be shared across pages in multi-page documents. To use Helvetica:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PdfDocumentBuilder.AddedFont font = builder.AddStandard14Font(Standard14Font.Helvetica);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or for Times New Roman:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PdfDocumentBuilder.AddedFont font = builder.AddStandard14Font(Standard14Font.TimesRoman);
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Text&lt;/h3&gt;

&lt;p&gt;Once a font is registered with a document builder, all pages in that document can use it to draw text. To write some text on the page created earlier we call the &lt;code&gt;AddText&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IReadOnlyList&amp;lt;Letter&amp;gt; letters = page.AddText("Hello World!", 12, new PdfPoint(25, 520), font);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This call will write the text "Hello World" in size 12 font at the provided location, 25 units from the left edge of the document and 520 units from the bottom of the document. Remember coordinates in PDF run up from 0 at the bottom rather than having 0 at the top as in WPF or other graphics systems. The last parameter is the font we registered earlier.&lt;/p&gt;

&lt;p&gt;This method adds the necessary operations to the PDF content stream for this page and returns the letters that will be drawn on the page and their position. This allows you to measure text and draw underlines, or borders around it.&lt;/p&gt;

&lt;p&gt;If you want to just find out the sizes and positions of the letters prior to drawing, for example to calculate text wrapping, you can use the measure method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IReadOnlyList&amp;lt;Letter&amp;gt; letters = page.MeasureText("Hello World!", 12, new PdfPoint(25, 520), font);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The only difference with this method is that it will not add the text to the page and so does not appear in the output document.&lt;/p&gt;

&lt;h3&gt;Geometry&lt;/h3&gt;

&lt;p&gt;In addition to text you can also draw lines and rectangles:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;page.DrawLine(new PdfPoint(25, 70), new PdfPoint(100, 70), 3);
page.DrawRectangle(new PdfPoint(30, 200), 250, 100, 0.5m);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This draws a line from (25, 70) to (100, 70) with a line width of 3 units. This means a horizontal line is drawn 70 units from the bottom of the page from 25 units from the left edge to 100 units from the left edge.&lt;/p&gt;

&lt;p&gt;The rectangle will be drawn from (30, 200) with a width of 250 units and a height of 100 units with a line width of 0.5 units.&lt;/p&gt;

&lt;h3&gt;Color&lt;/h3&gt;

&lt;p&gt;The color of text and geometry can also be set. Stroke color (the color of lines) and Fill/Text color are set by separate methods:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Set line color in RGB.
page.SetStrokeColor(250, 132, 131);
// Set text color in RGB (and the color of any fill operations, not currently used).
page.SetTextAndFillColor(250, 132, 131);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These colors are expressed in RGB from 0 - 255 for the red, green and blue component. Internally PDF uses values from 0 - 1.0 for RGB, this conversion happens within the page builder.&lt;/p&gt;

&lt;p&gt;Once a color is set it will remain active for all future calls to add text, drawing lines and drawing rectangles. To set the color back to the default black you must call:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;page.ResetColor();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which means further calls will use the color black.&lt;/p&gt;

&lt;h3&gt;Full Example&lt;/h3&gt;

&lt;p&gt;The simplest "Hello World!" example is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PdfDocumentBuilder builder = new PdfDocumentBuilder();

PdfPageBuilder page = builder.AddPage(PageSize.A4);

PdfDocumentBuilder.AddedFont font = builder.AddStandard14Font(Standard14Font.Helvetica);

page.AddText("Hello World!", 12, new PdfPoint(25, 520), font);

byte[] result = builder.Build();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Further examples including multiple pages can be found in the &lt;a href="https://github.com/UglyToad/PdfPig/blob/master/src/UglyToad.PdfPig.Tests/Writer/PdfDocumentBuilderTests.cs"&gt;tests for the document builder&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;TrueType&lt;/h3&gt;

&lt;p&gt;In addition to Standard 14 fonts TrueType fonts (fonts with the .ttf extension) are also supported. The raw bytes of the font files must be provided to the &lt;code&gt;AddTrueTypeFont&lt;/code&gt; method. This example uses the System font Baskerville Old Face on Windows 10:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;string file = @"C:\Windows\Fonts\BASKVILL.TTF";

byte[] bytes = File.ReadAllBytes(file);

PdfDocumentBuilder.AddedFont font = builder.AddTrueTypeFont(bytes);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since the result of adding a TrueType font is an &lt;code&gt;PdfDocumentBuilder.AddedFont&lt;/code&gt; which is identical to the result for Standard 14 fonts it can be used in the same way to add and measure text for pages.&lt;/p&gt;

&lt;p&gt;The TrueType font is interpreted and a compressed version of the font file is embedded and distributed with the resulting PDF document. Currently there are no optimizations to use a subset of the font file which most other document producers do so the file size for documents will be larger.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;While it's still early days for the library the addition of Open Source C# PDF document creation should widen the appeal of the &lt;a href="https://github.com/UglyToad/PdfPig"&gt;PdfPig&lt;/a&gt; library and help people who need a truly open source, fully managed .NET PDF creator.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2018/12/pdfpig-version-005</guid>
      <pubDate>Sun, 30 Dec 2018 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Sentence Boundary Detection in C#</title>
      <link>https://eliot-jones.com/2018/9/pragmatic-segmenter-net</link>
      <description>

&lt;p&gt;Sentence Boundary Detection or &lt;a href="https://en.wikipedia.org/wiki/Sentence_boundary_disambiguation"&gt;Segmentation&lt;/a&gt; is the task of splitting an input passage of text into individual sentences. Since the period '.' character may be used in numbers, ellipses or names it's not enough to simply split by the period character.&lt;/p&gt;

&lt;p&gt;When I was researching ways to do this in C# I didn't find much in the way of properly open source libraries. A lot of the libraries I found for other languages referred to the Golden Rule Set (GRS). This set comes from &lt;a href="https://github.com/diasks2/pragmatic_segmenter"&gt;Pragmatic Segmenter&lt;/a&gt;, a Ruby gem to segment text based on rules observed from a varied corpus of text.&lt;/p&gt;

&lt;p&gt;Since I find porting code from other languages helps me understand both the variations in how different languages approach the same problems and also how other people make architectural decisions and structure their code I decided to port it to C#.&lt;/p&gt;

&lt;p&gt;This Pragmatic Segmenter port is &lt;a href="https://www.nuget.org/packages/PragmaticSegmenterNet/"&gt;available to download from NuGet&lt;/a&gt;. The public API is similar to that for the Ruby package however the method is static:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var result = Segmenter.Segment("There it is! I found it.");

Assert.Equal(new[] { "There it is!", "I found it." }, result);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is also support for other languages, the Language enum gives the supported languages:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var result = Segmenter.Segment("Salve Sig.ra Mengoni! Come sta oggi?", Language.Italian);
Assert.Equal(new[] { "Salve Sig.ra Mengoni!", "Come sta oggi?" }, result);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;a href="https://github.com/UglyToad/PragmaticSegmenterNet"&gt;source code&lt;/a&gt; also contains a set of data from various sources I was using to test my port as well as add some behaviour for the sources I was primarily interested in (academic journals). This data can be &lt;a href="https://github.com/UglyToad/PragmaticSegmenterNet/blob/master/PragmaticSegmenterNet.Tests.Unit/Languages/Data/EnglishTestData.xml"&gt;found here&lt;/a&gt;. Hopefully this corpus of annotated sentence boundary data will be useful to people building their own libraries.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2018/9/pragmatic-segmenter-net</guid>
      <pubDate>Sun, 30 Sep 2018 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Using ConvNetSharp With Feature Based Data</title>
      <link>https://eliot-jones.com/2018/4/convnetsharp-with-features</link>
      <description>

&lt;p&gt;&lt;a href="https://github.com/cbovar/ConvNetSharp"&gt;ConvNetSharp&lt;/a&gt; which is descended from &lt;a href="https://github.com/karpathy/convnetjs"&gt;ConvNetJs&lt;/a&gt; is a library which enables you to use Neural Networks in .NET without the need to call out to other languages or services.&lt;/p&gt;

&lt;p&gt;ConvNetSharp also has GPU support which makes it a good option for training networks.&lt;/p&gt;

&lt;p&gt;Since much of the interest (and as a result the guides) around Neural Networks focuses on their utility in image analysis, it's slightly unclear how to apply these libraries to numeric and categorical features you may be used to using for SVMs or other machine learning methods.&lt;/p&gt;

&lt;p&gt;The aim of this blog post is to note how to acheive this.&lt;/p&gt;

&lt;p&gt;Let's take the example of some data observed in a scientific experiment. Perhaps we are trying to predict which snails make good racing snails.&lt;/p&gt;

&lt;p&gt;Our data set looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Age   Stalk Height    Shell Diameter    Shell Color   Good Snail?
1     0.52            7.6               Light Brown   No
1.2   0.74            6.75              Brown         Yes
1.16  0.73            7.01              Grey          Yes
etc...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;ConvNetSharp uses the concept of &lt;code&gt;Volume&lt;/code&gt;s to deal with input and classification data. A Volume is a 4 dimensional shape containing data.&lt;/p&gt;

&lt;p&gt;The 4 dimensions are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Width&lt;/li&gt;
&lt;li&gt;Height&lt;/li&gt;
&lt;li&gt;Depth&lt;/li&gt;
&lt;li&gt;Number of rows/observations&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Width and height only make sense when dealing with image data so we set them to 1. For our data the depth is equal to our number of features. Because we need to map our categorical features to numbers we end up with the following features:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Age&lt;/li&gt;
&lt;li&gt;Stalk Height&lt;/li&gt;
&lt;li&gt;Shell Diameter&lt;/li&gt;
&lt;li&gt;Is Shell Brown&lt;/li&gt;
&lt;li&gt;Is Shell Light Brown&lt;/li&gt;
&lt;li&gt;Is Shell Grey&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So the depth of our input volume is 6.&lt;/p&gt;

&lt;p&gt;Let's create our Net first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Net&amp;lt;double&amp;gt; net = new ConvNetSharp.Core.Net&amp;lt;double&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we define the input layer based on the shape of the data we will provide to it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Define the width and height (1) and the depth equal to our number of features
net.AddLayer(new InputLayer(1, 1, 6));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then we define some layers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;net.AddLayer(new FullyConnLayer(32));
net.AddLayer(new ReluLayer());

// ConvNetSharp supports dropout layers.
// net.AddLayer(new DropoutLayer(0.3));

net.AddLayer(new FullyConnLayer(32));
net.AddLayer(new ReluLayer());

// The last layer before the Softmax for classification must have as many neurons as output features
net.AddLayer(new FullyConnLayer(2));
net.AddLayer(new SoftmaxLayer(2));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our last layer is a SoftMax layer which will predict 2 classes, false and true.&lt;/p&gt;

&lt;p&gt;To provide our data to train the network we need to take the following steps:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;(Optionally) &lt;a href="https://www.kaggle.com/general/10620"&gt;Resample the data&lt;/a&gt; if one output is strongly represented in the training data to balance out the classes.&lt;/li&gt;
&lt;li&gt;Split the data into a training and test set, the trained network will be evaluated against the test set which is not provided to it during training.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Feature_scaling"&gt;Normalize the data&lt;/a&gt;. Store the normalization parameters applied to the training set and apply them against the test set.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;First we create a trainer for our network, we can either use Stochastic Gradient Descent (SGD) or an &lt;a href="https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/"&gt;Adam&lt;/a&gt; trainer.&lt;/p&gt;

&lt;p&gt;We will use SGD for this demo:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var trainer = new ConvNetSharp.Core.Training.Double.SgdTrainer()
{
  LearningRate = 0.01,
  L2Decay = 0.001,
  BatchSize = 70
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once we have normalzed our training data we must convert it to a volume to feed into the trainer.&lt;/p&gt;

&lt;p&gt;If our training set has 70 rows we have input data of the following form - &lt;code&gt;double[70][6]&lt;/code&gt; - where each row is an array containing the numeric value of each of the 6 features.&lt;/p&gt;

&lt;p&gt;Our output data is then - &lt;code&gt;bool[70]&lt;/code&gt; - where each entry indicates the result, whether or not the snail is good at racing, for each row.&lt;/p&gt;

&lt;p&gt;To convert the input data we need our volume to have width and height of 1, a depth of 6 (the number of features) and a 4th dimension equal to the number of rows in the dataset.&lt;/p&gt;

&lt;p&gt;Prior to this we need to flatten our input into a single array of the form - &lt;code&gt;double[70 * 6]&lt;/code&gt;. To do this each row should be mapped to a consecutive set of 6 entries in the array. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var featuresPerRow = input[0].Length;

var flattenedInput = new double[input.Length * featuresPerRow];
for (int i = 0; i &amp;lt; input.Length; i++)
{
    var row = input[i];
    for (int j = 0; j &amp;lt; row.Length; j++)
    {
      flattenedInput[(i * featuresPerRow) + j] = row[j];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This takes each row in the input and maps it to a run of 6 numbers in the flattened array.&lt;/p&gt;

&lt;p&gt;Now we can convert this flattened array to a volume:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var volume = BuilderInstance.Volume.From(flattenedInput, new Shape(1, 1, 6, 70));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where 70 is whatever the number of rows in the input data was and 6 is the number of features in each row.&lt;/p&gt;

&lt;p&gt;The output volume is then a boolean array flattened to 2 numbers per boolean:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var flattenedOutput = new double[output.Length * 2];
for (int i = 0; i &amp;lt; output.Length; i++)
{
  var value = output[i];
  flattenedOutput[2 * i] = value ? 0 : 1;
  flattenedOutput[(2 * i) + 1] = value ? 1 : 0;
}

var outputVolume = BuilderInstance.Volume.From(flattenedOutput, 
new Shape(1, 1, 2, output.Length));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This creates an array where each pair of numbers indicates either false (0, 1) or true(1, 0).&lt;/p&gt;

&lt;p&gt;To create our test volume:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;double[][] testSet;
// Apply whatever normalization technique you are using, e.g. min-max
double[][] normalizedTestSet = Normalize(testSet, trainingSetParameters);

// Apply the same flattening process as we did for our training input array
double[] flattenedTestSet = Flatten(normalizedTestSet);

var testVolume = BuilderInstance.Volume.From(flattenedTestSet, 
new Shape(1, 1, 6, normalizedTestSet.Length));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then we need to run the training process multiple times (epochs) until we start to converge on an accuracy for our test set:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for (int i = 0; i &amp;lt; maxEpochs; i++)
{
  trainer.Train(volume, outputVolume);

  // Evaluate the test set accuracy
  var predictions = net.Forward(testVolume);

  var numberWrong = 0;
  for (int j = 0; j &amp;lt; testOutput.Length; j++)
  {
    var predictedFalseValue = predictions.Get(0, 0, 0, j);

    var predictedValue = predictedFalseValue &amp;lt; 0.5 ? true : false;

    if (predictedValue != testOutput[j])
    {
      numberWrong++;
    }
  }

  var percentIncorrect = (numberWrong /(double) testOutput.Length) * 100;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you've used a dropout layer in the net remember to disable it before evaluating the test set.&lt;/p&gt;

&lt;p&gt;This is the most basic way of training the network. You can enhance this by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Splitting the training of each epoch into steps by partitioning your input set into batches of, for example, 20 rows.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.kaggle.com/dansbecker/cross-validation"&gt;Cross validating&lt;/a&gt; by switching the data used in the test and training data multiple times.&lt;/li&gt;
&lt;li&gt;Adjusting or automatically tuning training parameters or network shape/number of layers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the output you want to predict is a continuous value rather than a classification you need to train a regression. To do this you swap the last SoftMax layer with a Regression layer. For details on this &lt;a href="https://github.com/cbovar/ConvNetSharp/blob/master/Examples/Regression1DDemo/Program.cs" title="Example from GitHub"&gt;see this example&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2018/4/convnetsharp-with-features</guid>
      <pubDate>Sat, 21 Apr 2018 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Alpha Release of PdfPig</title>
      <link>https://eliot-jones.com/2018/1/pdf-reader-c-sharp</link>
      <description>

&lt;p&gt;I'm very pleased to finally have reached the first alpha release of &lt;a href="https://www.nuget.org/packages/PdfPig/" title="NuGet link"&gt;PdfPig (NuGet)&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;image src="https://raw.githubusercontent.com/UglyToad/Pdf/master/documentation/pdfpig.png" width="160px"/&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/UglyToad/PdfPig" title="GitHub link"&gt;PdfPig (GitHub)&lt;/a&gt; is a library that reads text content from PDFs in C#. This will help users extract and index text from a PDF file using C#.&lt;/p&gt;

&lt;p&gt;The current version of the library provides access to the text and text positions in PDF documents. &lt;/p&gt;

&lt;h3&gt;Motivation&lt;/h3&gt;

&lt;p&gt;The library began as an effort to port &lt;a href="https://pdfbox.apache.org/"&gt;PDFBox&lt;/a&gt; from Java to C# in order to provide a native open-source solution for reading PDFs with C#. PdfPig is Apache 2.0 licensed and therefore avoids questionably (i.e. not at all) 'open-source' copyleft viral licenses.&lt;/p&gt;

&lt;p&gt;I had been using the PDFBox library through &lt;a href="https://www.codeproject.com/Articles/538617/Working-with-PDF-files-in-Csharp-using-PdfBox-and" title="CodeProject link to using PDFBox with IKVM"&gt;IKVM&lt;/a&gt; and started the project to investigate the effort required to make the PDFBox work natively with C#.&lt;/p&gt;

&lt;p&gt;In order to understand the specification better I rewrote quite a few parts of the code resulting in many more bugs and fewer features than the original code.&lt;/p&gt;

&lt;p&gt;As the alpha is (hopefully) used and issues are reported I will refine the initial public API. I can't forsee the API expanding much beyond its current surface area for the first proper release.&lt;/p&gt;

&lt;h3&gt;Usage&lt;/h3&gt;

&lt;p&gt;To get the text from a PDF using C# with PdfPig the following code opens and retrieves a page from the document:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using UglyToad.PdfPig;
using UglyToad.PdfPig.Content;

public static void Main()
{
    using (PdfDocument document = PdfDocument.Open(@"C:\my-file.pdf"))
    {
        // Returns the total number of pages in the document.
        int pageCount = document.NumberOfPages;

        // Each page is loaded separately by this method.
        Page page = document.GetPage(1);

        // Sizes are given in typographic points (1/72nd of an inch).
        decimal widthInPoints = page.Width;
        decimal heightInPoints = page.Height;

        // The full text of the page as it is defined in the PDF content.
        string text = page.Text;

        // The text and location of each individual letter on the page.
        IReadOnlyList&amp;lt;Letter&amp;gt; letters = page.Letters;

        page = document.GetPage(2);

        // etc..
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As far as possible the API is restricted to make discoverability easier and immutable to provide proper encapsulation.&lt;/p&gt;

&lt;p&gt;Since PDF defines its content for display rather than readability purposes, the &lt;code&gt;page.Text&lt;/code&gt; may lack spaces or present words in the wrong order.&lt;/p&gt;

&lt;p&gt;For this reason it is necessary for the client to write their own code to form words from the letters provided by &lt;code&gt;page.Letters&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Please bear in mind this is the very first alpha release so highly likely to be unstable.&lt;/p&gt;

&lt;h3&gt;Installation&lt;/h3&gt;

&lt;p&gt;The package is available from &lt;a href="https://www.nuget.org/packages/PdfPig/"&gt;NuGet&lt;/a&gt;. Since it is pre-release in order to see it you will need to tick the pre-release checkbox when searching.&lt;/p&gt;

&lt;p&gt;From the Package Manager command line you can install it using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Install-Package PdfPig -Version 0.0.1-alpha-001
&lt;/code&gt;&lt;/pre&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2018/1/pdf-reader-c-sharp</guid>
      <pubDate>Wed, 17 Jan 2018 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Configuring SonarQube with GitLab and TeamCity</title>
      <link>https://eliot-jones.com/2017/12/configure-gitlab-sonarqube-teamcity</link>
      <description>

&lt;p&gt;Introducing static analysis to a project can help inform code reviews and highlight
areas of the code likely to cause errors as well as expose trends in code
quality over time. The tradeoff is that there are often many false positives
in a report which need to be investigated.&lt;/p&gt;

&lt;p&gt;When I configured &lt;a href="https://www.sonarqube.org/" title="SonarQube website"&gt;SonarQube&lt;/a&gt; (6.4) to provide static analysis for our C# project we struggled to incorporate
it into our normal development process since it sat outside the usual
branch -&gt; build -&gt; merge request workflow.&lt;/p&gt;

&lt;p&gt;For our source control we were using GitLab (10.1.4) and our build server
was running TeamCity (2017.1).&lt;/p&gt;

&lt;h3&gt;Get the plugin&lt;/h3&gt;

&lt;p&gt;Gabriel Allaigre has written the &lt;a href="https://gitlab.talanlabs.com/gabriel-allaigre/sonar-gitlab-plugin" title="GitLab page for plugin"&gt;sonar-gitlab plugin&lt;/a&gt; which enables SonarQube to push its analysis results to GitLab. This presents the results of analysis in the same place we review our merge requests as well as causing build errors when violations occur; and therefore helps incorporate SonarQube into the development workflow.&lt;/p&gt;

&lt;p&gt;First you will need to install the sonar-gitlab plugin to your SonarQube environment and follow the steps detailed in the configuration section of the readme:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Set the GitLab URL from the Administration -&gt; Configuration -&gt; General Settings -&gt; GitLab&lt;/li&gt;
&lt;li&gt;Set the GitLab user token in the same place. This should be a token for a GitLab user with the developer role. You can get this token in GitLab by going to Profile -&gt; Edit Profile -&gt; Access Tokens and generating a new access token.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once this is installed the SonarQube configuration is complete.&lt;/p&gt;

&lt;h3&gt;Configure TeamCity&lt;/h3&gt;

&lt;p&gt;The installation guide for the sonar-gitlab plugin describes how to configure it when using the GitLab CI or Maven for builds. To run the analysis from TeamCity we need to get some additional information for the parameters to the command line.&lt;/p&gt;

&lt;p&gt;If we were running from GitLab's CI we would use the following command to start the Sonar MSBuild Scanner, pushing to GitLab after the analysis completed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SonarQube.Scanner.MSBuild begin /k:"$env:ProjName" /n:"$env:ProjName" /v:"1.0" /d:sonar.gitlab.project_id=$CI_PROJECT_ID /d:sonar.gitlab.commit_sha=$CI_BUILD_REF /d:sonar.gitlab.ref_name=$CI_BUILD_REF_NAME /d:sonar.analysis.mode="preview"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since TeamCity does not have access to the GitLab parameters in this command we need to find them in a different way:&lt;/p&gt;

&lt;h4&gt;$CI_PROJECT_ID&lt;/h4&gt;

&lt;p&gt;This is an integer ID which uniquely identifies the project in GitLab.&lt;/p&gt;

&lt;p&gt;To find out its value you can either go to Project -&gt; Settings -&gt; General settings in GitLab or we can query the GitLab API ourselves. You can navigate to &lt;code&gt;http://$YOUR-GITLAB-URL/api/v4/projects&lt;/code&gt; to display the full list of projects. To view a project by ID and ensure you have the correct project you can view by id at &lt;code&gt;http://$YOUR-GITLAB-URL/api/v4/projects/$ID&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;$CI_BUILD_REF&lt;/h4&gt;

&lt;p&gt;The full SHA of the currently building commit. In PowerShell on TeamCity this can be accessed as follows &lt;code&gt;$commit = "%build.vcs.number%"&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;$CI_BUILD_REF_NAME&lt;/h4&gt;

&lt;p&gt;The branch name. From PowerShell on TeamCity this can be accessed by: &lt;code&gt;$branch = "%teamcity.build.branch%"&lt;/code&gt;. To remove the full qualification you can use &lt;code&gt;$branch = $branch.Replace("refs/heads/", "")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now to start Sonar analysis on TeamCity in a PowerShell step assuming the Sonar MSBuild scanner is in &lt;code&gt;C:\sonar\bin&lt;/code&gt; and your project ID is 3 you can run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$commit = "%build.vcs.number%"
$branch = "%teamcity.build.branch%"
$branch = $branch.Replace("refs/heads/", "")

C:\sonar\bin\SonarQube.Scanner.MSBuild.exe begin /k:"KEY" /n:"PROJECT NAME" /v:"0.0.1" /d:sonar.gitlab.project_id=3 /d:sonar.gitlab.commit_sha=$commit /d:sonar.gitlab.ref_name=$branch /d:sonar.analysis.mode="preview" /d:sonar.scm.provider=git```
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Replace the project key, name, version and id values with your values.&lt;/p&gt;

&lt;p&gt;It's important to set the analysis mode to &lt;strong&gt;preview&lt;/strong&gt; otherwise the sonar-gitlab plugin will not work.&lt;/p&gt;

&lt;p&gt;With the analysis started run your build as normal.&lt;/p&gt;

&lt;p&gt;For completing the analysis no GitLab specific changes are required:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;C:\sonar\bin\SonarQube.Scanner.MSBuild.exe end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will then perform the Sonar Scanner analysis, send the results to the SonarQube server which will then forward them to TeamCity.&lt;/p&gt;

&lt;p&gt;Hopefully this helps you get TeamCity talking to SonarQube talking to GitLab. Let me know what static analysis tools you use for your C# projects in the comments.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2017/12/configure-gitlab-sonarqube-teamcity</guid>
      <pubDate>Tue, 05 Dec 2017 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Visual Studio 2017 Red Underline/Incorrect Highlights</title>
      <link>https://eliot-jones.com/2017/11/clear-vs2017-intellisense-errors</link>
      <description>

&lt;p&gt;There are a lot of answers on this topic but in order to aggregate the steps I usually follow for future reference I'm noting them in this blog post.&lt;/p&gt;

&lt;p&gt;There are few things more annoying than Intellisense going wobbly and flagging successfully compiling code with errors. Obviously the first step is to restart Visual Studio but if the problem persists you need to try something more. These steps are for Visual Studio 2017 Community with Resharper.&lt;/p&gt;

&lt;p&gt;You can check whether the underlines have disappeared after each step or run them all:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Unload then reload the problematic project from Solution Explorer. To do this, right click the project, select &lt;code&gt;Unload Project&lt;/code&gt; and then &lt;code&gt;Reload Project&lt;/code&gt;. This sometimes helps clear incorrect highlighting due to Resharper especially after merges.&lt;/li&gt;
&lt;li&gt;Clear the Resharper cache. This is accessed by going to Resharper &gt; Options &gt; General &gt; Clear caches in the menu. You will need to restart Visual Studio to see if this step worked.&lt;/li&gt;
&lt;li&gt;Disable Resharper from Tools &gt; Options &gt; Resharper &gt; Suspend Now. Then start it again from the same location.&lt;/li&gt;
&lt;li&gt;Close Visual Studio and then delete the &lt;code&gt;.vs&lt;/code&gt; folder from the source folder. This is a hidden folder at the same level as the .sln file.&lt;/li&gt;
&lt;li&gt;With Visual Studio closed delete the &lt;code&gt;obj&lt;/code&gt; folders from the problematic project folders.&lt;/li&gt;
&lt;/ol&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2017/11/clear-vs2017-intellisense-errors</guid>
      <pubDate>Thu, 30 Nov 2017 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>The Curious Case of the Null StringBuilder</title>
      <link>https://eliot-jones.com/2017/8/stringbuilder-nullreferenceexception</link>
      <description>

&lt;p&gt;Today was spent tracking down a very weird bug. In production we were seeing an important part of our document reading fail. We kept getting &lt;code&gt;NullReferenceException&lt;/code&gt;s when calling &lt;code&gt;AppendLine&lt;/code&gt; on a non-null StringBuilder. It didn't prevent us reading the document however the result would be significantly different to the same document on a local instance of our program.&lt;/p&gt;

&lt;p&gt;It only started occurring after the production server had been running for a few days which meant we couldn't debug it locally. We were running .NET 4.5.2.&lt;/p&gt;

&lt;p&gt;Luckily we had lots of logging to track down the issue. The problem was in a class like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class AlgorithmLogicLogger
{
    private readonly StringBuilder stringBuilder;

    public AlgorithmLogicLogger()
    {
        stringBuilder = new StringBuilder();
    }

    public void Append(string s)
    {
        var message = BuildStringDetails(s);

        stringBuilder.AppendLine(message);
    }

    private static string BuildStringDetails(string s)
    {
        return $"{DateTime.UtcNow}: {s}";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was a class which was originally intended to provide detailed logging for a complicated algorithm.&lt;/p&gt;

&lt;p&gt;The call to &lt;code&gt;StringBuilder.AppendLine()&lt;/code&gt; inside &lt;code&gt;Append&lt;/code&gt; was throwing a &lt;code&gt;NullReferenceException&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;After ensuring no weird reflection was taking place and using Ildasm to inspect the compiled code we were sure it wasn't possible for &lt;code&gt;stringBuilder&lt;/code&gt; to be null. It was always instantiated in the constructor and never changed elsewhere.&lt;/p&gt;

&lt;p&gt;The next working theory was that a multi-threading issue was somehow calling &lt;code&gt;Append&lt;/code&gt; prior to the field being set. This was also discounted both because it wouldn't have been possible and also because the code in question was not called from multiple threads.&lt;/p&gt;

&lt;p&gt;After ensuring that it wasn't the case that the garbage collector wasn't somehow incorrectly collecting the string builder (because it was only written to, never read, the reading hadn't been implemented yet) we were beginning to run out of ideas.&lt;/p&gt;

&lt;p&gt;After combing the production logs from the past 3 days we finally located the issue.&lt;/p&gt;

&lt;p&gt;The logger was being created as a singleton:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class LoggerSingleton
{
    public AlgorithmLogicLogger Logger { get; } = new AlgorithmLogicLogger();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since the StringBuilder was never cleared it would eventually grow larger than the &lt;code&gt;MaxCapacity&lt;/code&gt;. When this happened an &lt;code&gt;OutOfMemoryException&lt;/code&gt; was thrown and caught further up the stack. Somehow this resulted in a corrupted state which meant further calls to the singleton instance of the StringBuilder such as &lt;code&gt;Append&lt;/code&gt; and &lt;code&gt;AppendLine&lt;/code&gt; resulted in a &lt;code&gt;NullReferenceException&lt;/code&gt; being thrown internally.&lt;/p&gt;

&lt;p&gt;Fixing this was fairly simple, just removing the singleton since it was no longer required, but it was odd to see the non-null object throw a &lt;code&gt;NullReferenceException&lt;/code&gt; rather than further &lt;code&gt;OutOfMemoryException&lt;/code&gt;s which is what we observed when the code was replicated locally.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2017/8/stringbuilder-nullreferenceexception</guid>
      <pubDate>Mon, 21 Aug 2017 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>ASP.NET Core Identity Using PostgreSQL</title>
      <link>https://eliot-jones.com/2017/6/asp-net-core-identity-post-1</link>
      <description>

&lt;p&gt;Following on from my much older posts about using ASP.NET Identity 2 to manage user accounts in MVC 4 sites, today I needed to use Identity on an ASP.NET Core MVC site.&lt;/p&gt;

&lt;p&gt;As with previous versions, the current &lt;a href="https://github.com/aspnet/Identity" title="GitHub for ASP.NET Core Identity"&gt;Identity library&lt;/a&gt; for .NET Core 1.1 uses Entity Framework out-the-box. Luckily it's much easier to change this behaviour for the simplest register/log-in flow.&lt;/p&gt;

&lt;h3&gt;Install&lt;/h3&gt;

&lt;p&gt;Firstly you need to get the right NuGet package. For the Identity library without Entity Framework this is:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Microsoft.AspNetCore.Identity&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once this is installed in your project you need to provide your own implementation of the &lt;code&gt;IUserStore&amp;lt;TUser&amp;gt;&lt;/code&gt; and &lt;code&gt;IRoleStore&amp;lt;TRole&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Unlike previous versions the &lt;code&gt;TUser&lt;/code&gt; no longer needs to implement a specific interface.&lt;/p&gt;

&lt;p&gt;For my project I was using PostgreSQL as the database and Dapper.Contrib as the ORM. My User class was simply:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Table("\"user\"")]
public class User
{
    [ExplicitKey]
    public Guid Id { get; set; }

    public string UserName { get; set; }

    public string NormalizedUserName { get; set; }

    public string Email { get; set; }

    public string PasswordHash { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(I had to do some faffing around to make sure the table name was detected correctly in my schema but could have called the table anything, it doesn't have to be called "user").&lt;/p&gt;

&lt;p&gt;You also need a class for Roles, since I won't be implementing Roles in this tutorial I just created a blank class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Role { }
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Fun In Store&lt;/h3&gt;

&lt;p&gt;Now we need to implement a couple of interfaces.&lt;/p&gt;

&lt;p&gt;For users I wanted to support password based log-in. &lt;/p&gt;

&lt;p&gt;By default you only need to provide the &lt;code&gt;IUserStore&amp;lt;TUser&amp;gt;&lt;/code&gt; implementation, however for almost all applications the behaviours supported by the &lt;code&gt;IUserPasswordStore&amp;lt;TUser&amp;gt;&lt;/code&gt; are desired. The &lt;code&gt;IUserPasswordStore&amp;lt;TUser&amp;gt;&lt;/code&gt; interface implements &lt;code&gt;IUserStore&amp;lt;TUser&amp;gt;&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class UserPasswordStore : IUserPasswordStore&amp;lt;User&amp;gt;
{
    private readonly IDataContext context;

    public UserPasswordStore(IDataContext context)
    {
        this.context = context;
    }

    public async Task&amp;lt;IdentityResult&amp;gt; CreateAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        await context.CreateAsync(user);

        return IdentityResult.Success;
    }

    public async Task&amp;lt;IdentityResult&amp;gt; DeleteAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        await context.DeleteAsync(user);

        return IdentityResult.Success;
    }

    public void Dispose()
    {
    }

    public async Task&amp;lt;User&amp;gt; FindByIdAsync(string userId, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        Guid id;
        if (!Guid.TryParse(userId, out id))
        {
            throw new ArgumentException("Id was not a valid Guid: " + userId, nameof(userId));
        }

        return await context.GetByIdAsync&amp;lt;User&amp;gt;(id);
    }

    public async Task&amp;lt;User&amp;gt; FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        var users = await context.GetAllAsync&amp;lt;User&amp;gt;();

        return users.FirstOrDefault(x =&amp;gt; string.Equals(normalizedUserName, x.NormalizedUserName, StringComparison.OrdinalIgnoreCase));
    }

    public Task&amp;lt;string&amp;gt; GetNormalizedUserNameAsync(User user, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        return Task.FromResult(user.NormalizedUserName);
    }

    public Task&amp;lt;string&amp;gt; GetPasswordHashAsync(User user, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        return Task.FromResult(user.PasswordHash);
    }

    public Task&amp;lt;string&amp;gt; GetUserIdAsync(User user, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        return Task.FromResult(user.Id.ToString());
    }

    public Task&amp;lt;string&amp;gt; GetUserNameAsync(User user, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        return Task.FromResult(user.UserName);
    }

    public Task&amp;lt;bool&amp;gt; HasPasswordAsync(User user, CancellationToken cancellationToken)
    {
        return Task.FromResult(true);
    }

    public Task SetNormalizedUserNameAsync(User user, string normalizedName, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        user.NormalizedUserName = normalizedName;

        return Task.CompletedTask;
    }

    public Task SetPasswordHashAsync(User user, string passwordHash, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        user.PasswordHash = passwordHash;

        return Task.CompletedTask;
    }

    public Task SetUserNameAsync(User user, string userName, CancellationToken cancellationToken)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        user.UserName = userName;

        return Task.CompletedTask;
    }

    public async Task&amp;lt;IdentityResult&amp;gt; UpdateAsync(User user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }

        await context.UpdateAsync(user);

        return IdentityResult.Success;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A lot of this code is boilerplate to check for cancellation tokens and to verify arguments, the underlying logic for data access is very basic.&lt;/p&gt;

&lt;p&gt;I have not yet implemented the lock-out code in the sample above but it will be fairly simple and similar to the existing code. Just implement &lt;code&gt;IUserLockoutStore&amp;lt;T&amp;gt;&lt;/code&gt; in addition to &lt;code&gt;IUserPasswordStore&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;IDataContext&lt;/code&gt; class used here is just my custom injectable wrapper around the Dapper/PostgreSQL connection, if you wanted you could directly connect to the database or use whichever data access library you want.&lt;/p&gt;

&lt;p&gt;My data context class uses Dapper.Contrib to perform simple CRUD operations:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class DapperDataContext : IDataContext, IDisposable
{
    private readonly IDbConnection connection;

    public DapperDataContext(IOptions&amp;lt;DatabaseOptions&amp;gt; databaseOptions)
    {
        connection = new NpgsqlConnection(databaseOptions.Value.ConnectionString);
    }

    public async Task CreateAsync&amp;lt;T&amp;gt;(T item) where T : class
    {
        if (item == null)
        {
            throw new ArgumentNullException(nameof(item));
        }

        await connection.InsertAsync(item);
    }

    public async Task DeleteAsync&amp;lt;T&amp;gt;(T item) where T : class
    {
        if (item == null)
        {
            throw new ArgumentNullException(nameof(item));
        }

        await connection.DeleteAsync(item);
    }

    public async Task&amp;lt;T&amp;gt; GetByIdAsync&amp;lt;T&amp;gt;(Guid id) where T : class
    {
        return await connection.GetAsync&amp;lt;T&amp;gt;(id);
    }

    public void Dispose()
    {
        connection.Dispose();
    }

    public async Task&amp;lt;IReadOnlyCollection&amp;lt;T&amp;gt;&amp;gt; GetAllAsync&amp;lt;T&amp;gt;() where T : class
    {
        var items = await connection.GetAllAsync&amp;lt;T&amp;gt;();

        var result = new List&amp;lt;T&amp;gt;();
        result.AddRange(items);

        return result;
    }

    public async Task UpdateAsync&amp;lt;T&amp;gt;(T item) where T : class
    {
        await connection.UpdateAsync(item);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You also need to provide an implementation of the &lt;code&gt;IRoleStore&amp;lt;TRole&amp;gt;&lt;/code&gt; which for this demo I am ignoring and leaving the methods not implemented. These methods will not be called for our default code, except for the dispose method. For this reason remember to remove the &lt;code&gt;NotImplementedException&lt;/code&gt; from the &lt;code&gt;Dispose&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class RoleStore : IRoleStore&amp;lt;Role&amp;gt;
{
    public Task&amp;lt;IdentityResult&amp;gt; CreateAsync(Role role, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task&amp;lt;IdentityResult&amp;gt; DeleteAsync(Role role, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public void Dispose()
    {
    }

    public Task&amp;lt;Role&amp;gt; FindByIdAsync(string roleId, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task&amp;lt;Role&amp;gt; FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task&amp;lt;string&amp;gt; GetNormalizedRoleNameAsync(Role role, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task&amp;lt;string&amp;gt; GetRoleIdAsync(Role role, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task&amp;lt;string&amp;gt; GetRoleNameAsync(Role role, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task SetNormalizedRoleNameAsync(Role role, string normalizedName, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task SetRoleNameAsync(Role role, string roleName, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }

    public Task&amp;lt;IdentityResult&amp;gt; UpdateAsync(Role role, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Register Services&lt;/h3&gt;

&lt;p&gt;Now all that's left to do is register the services at the start up of your MVC or Web API application.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;ConfigureServices&lt;/code&gt; method of the &lt;code&gt;Startup.cs&lt;/code&gt; class register your user, role, user store and role store classes as well as any injectable services required by your code.&lt;/p&gt;

&lt;p&gt;To register the identity classes correctly, use the &lt;code&gt;AddIdentity&amp;lt;TUser, TRole&amp;gt;&lt;/code&gt; extension method. Then register both the user and role store. These method calls must be chained off/follow the call to &lt;code&gt;AddIdentity&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity&amp;lt;User, Role&amp;gt;()
        .AddRoleStore&amp;lt;RoleStore&amp;gt;()
        .AddUserStore&amp;lt;UserPasswordStore&amp;gt;()
        .AddDefaultTokenProviders();

    services.AddMvc();

    // Add application services.
    services.AddTransient&amp;lt;IDataContext, DapperDataContext&amp;gt;();

    services.Configure&amp;lt;DatabaseOptions&amp;gt;(Configuration.GetSection("Database"));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Calling The Store&lt;/h3&gt;

&lt;p&gt;Once the services are registered you can request an instance &lt;code&gt;UserManager&amp;lt;User&amp;gt;&lt;/code&gt; and/or &lt;code&gt;SignInManager&amp;lt;User&amp;gt;&lt;/code&gt; in your controller's constructor. The Identity and Dependency Injection code will handle resolving and registering these based off the store implementations we provided. These then support registration and log-in methods. The log-in method is shown in the controller below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Authorize]
public class AccountController : Controller
{
    private readonly UserManager&amp;lt;User&amp;gt; _userManager;
    private readonly SignInManager&amp;lt;User&amp;gt; _signInManager;

    public AccountController(UserManager&amp;lt;User&amp;gt; userManager, SignInManager&amp;lt;User&amp;gt; signInManager,)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task&amp;lt;IActionResult&amp;gt; Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To easily get controller templates with the usual set of registration and log-in methods supported, simply create a new MVC project from the Visual Studio 2017 template with the Individual Accounts option enabled. Then remove the Entity Framework based Identity library and related classes (such as &lt;code&gt;ApplicationUser&lt;/code&gt;) and instead implement the code from this guide.&lt;/p&gt;

&lt;p&gt;This gets you the simplest working log-in and registration system, but there's a lot left to implement including the lockout store and the role store as well as 3rd party authentication providers depending on the requirements of your application.&lt;/p&gt;

&lt;p&gt;I've put a simple version of this code which uses text files to store data &lt;a href="https://github.com/EliotJones/AspIdentityCoreDemo" title="Code on GitHub"&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2017/6/asp-net-core-identity-post-1</guid>
      <pubDate>Sun, 25 Jun 2017 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>White Automation</title>
      <link>https://eliot-jones.com/2017/5/white-automation</link>
      <description>

&lt;p&gt;I've spent a few days getting very in-depth with White for WPF UI automation so in order to store the information while it's still fresh in my mind I am writing a blog post.&lt;/p&gt;

&lt;p&gt;White is a framework for automating interactions with desktop Windows applications. It is built on top of the UIAutomation library which is part of the .NET framework. The project is currently not very active on GitHub but despite this it's still very good at dealing with desktop interactions on Windows.&lt;/p&gt;

&lt;h3&gt;Automate all the things&lt;/h3&gt;

&lt;p&gt;For this tutorial I've decided to automate interactions with the Visual Studio 2015 application; since it's software that most people interested in following this tutorial will probably have.&lt;/p&gt;

&lt;p&gt;I'm creating my application as a .NET 4.6.1 console application. Generally White is used for automated UI tests, so you might be using a test project. Whichever project type you choose the information in this tutorial will still be relevant.&lt;/p&gt;

&lt;p&gt;First we need to add the &lt;code&gt;TestStack.White&lt;/code&gt; NuGet package. Right click your project and select &lt;code&gt;Manage NuGet Packages&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/white-automation/add-nuget-package.png" alt="add TestStack.White as a NuGet package" /&gt;&lt;/p&gt;

&lt;p&gt;Search the online packages for White and install the &lt;code&gt;TestStack.White&lt;/code&gt; package. &lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/white-automation/white-package.png" alt="Add TestStack.White" /&gt;&lt;/p&gt;

&lt;p&gt;Alternatively you can run the installation command from the package manager console. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Install-Package TestStack.White
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once the package is intalled we can start writing code. I have a blank console main method where I'll be putting my code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main()
{
    // Writing code here
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Launch the application&lt;/h3&gt;

&lt;p&gt;The first thing we need to do is launch the application under test (AUT). The White &lt;code&gt;Application&lt;/code&gt; class provides a wrapper over the underlying Windows process.&lt;/p&gt;

&lt;p&gt;Add a using statement for the White classes and the process start info:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System.Diagnostics;
using TestStack.White;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can launch an application, to do this we'll use &lt;code&gt;ProcessStartInfo&lt;/code&gt; since it provides us more control over how the application is started, most importantly the Working Directory, otherwise file system access might not work correctly in your application.&lt;/p&gt;

&lt;p&gt;The Visual Studio executable is located at the following path for my install:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To launch it we use the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var processStartInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe")
{
    WorkingDirectory = @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE"
};

var application = Application.Launch(processStartInfo);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will run the .exe from its normal location. Once the application is running we can get the windows it opens:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var windows = application.GetWindows();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method blocks until the application opens a window. For Visual Studio this works well since the splash screen is not counted as a window for this purpose; however for other applications the splash screen may display in its own window.&lt;/p&gt;

&lt;p&gt;You could wait for a window with some desired property to load using the following code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var window = windows.FirstOrDefault(x =&amp;gt; x.Name.EndsWith("Visual Studio", true, CultureInfo.CurrentCulture));
while (window == null)
{
    Thread.Sleep(1000);

    window = application.GetWindows().FirstOrDefault(x =&amp;gt; x.Name.EndsWith("Visual Studio", true, CultureInfo.CurrentCulture));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are probably nicer ways to do this, but in essence we poll every second to check if any of the application windows have the name we want.&lt;/p&gt;

&lt;p&gt;If you need to maximise the window once launched you can &lt;a href="http://stackoverflow.com/a/4566650/1775471" title="How to maximise the White window"&gt;use PInvoke&lt;/a&gt;. To get the main window handle use &lt;code&gt;application.Process.MainWindowHandle&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once we have the window we want, it's useful to encapsulate it in another class and centralise all logic that is specific to your UI. This is similar to the &lt;em&gt;Page Object Model&lt;/em&gt; pattern for Selenium. The benefit is when the UI changes you have 1 place to change your code. Since the default WPF window is usually called MainWindow I create a MainWindow class to mirror this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using TestStack.White.UIItems.WindowItems;

public class MainWindow
{
    private readonly Window window;

    public MainWindow(Window window)
    {
        this.window = window;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that we added another &lt;code&gt;using&lt;/code&gt; statement for the &lt;code&gt;Window&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;Now we will use our automated Visual Studio 2015 UI to create a new project. To do this we first need to click &lt;code&gt;File &amp;gt; New &amp;gt; Project&lt;/code&gt;. This is shown in the screenshot below:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/white-automation/file-new-project.png" alt="The menu interaction is File &amp;gt; New &amp;gt; Project" /&gt;&lt;/p&gt;

&lt;h3&gt;The set menu&lt;/h3&gt;

&lt;p&gt;To click these menu items we find each of them by their text and click them in turn:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void ClickNewProject()
{
    IUIItem file = window.Get(SearchCriteria.ByText("File"));
    file.Click();

    IUIItem newItem = window.Get(SearchCriteria.ByText("New"));

    newItem.Click();

    IUIItem projectItem = window.Get(SearchCriteria.ByText("Project..."));
    projectItem.Click();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This requires the followingt &lt;code&gt;using&lt;/code&gt; statements:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using TestStack.White.UIItems;
using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.WindowItems;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once the &lt;code&gt;Project...&lt;/code&gt; menu item is clicked a new modal window opens for the user to choose the project type. This is what we need to interact with next.&lt;/p&gt;

&lt;h3&gt;New project dialog&lt;/h3&gt;

&lt;p&gt;We will create a new class to contain interaction logic for the "New Project" dialog window. Imaginatively I will call this &lt;code&gt;NewProjectDialog&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This class will take a reference to its White window in the constructor. This window is different to the main window, but both are of the White type &lt;code&gt;Window&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using TestStack.White.UIItems.WindowItems;

public class NewProjectDialog
{
    private readonly Window window;

    public NewProjectDialog(Window window)
    {
        this.window = window;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we call &lt;code&gt;MainWindow.ClickNewProject()&lt;/code&gt; it will return us an instance of the &lt;code&gt;NewProjectDialog&lt;/code&gt;. To do this we make use of the built in method White has to get modal dialogs (windows which lock focus and do not let you continue using the main window).&lt;/p&gt;

&lt;p&gt;The code for &lt;code&gt;ClickNewProject&lt;/code&gt; is modified so it returns an object of the type &lt;code&gt;NewProjectDialog&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public NewProjectDialog ClickNewProject()
{
    IUIItem file = window.Get(SearchCriteria.ByText("File"));
    file.Click();

    IUIItem newItem = window.Get(SearchCriteria.ByText("New"));

    newItem.Click();

    IUIItem projectItem = window.Get(SearchCriteria.ByText("Project..."));
    projectItem.Click();

    // Just take the first since it will (should!) be the only one
    var dialog = new NewProjectDialog(window.ModalWindows()[0]);

    return dialog;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Finding yourself&lt;/h3&gt;

&lt;p&gt;This is where the help of a tool to find elements which understands the UIAutomation visual tree becomes invaluable. The latest guidance from Microsoft seems to be to use their &lt;code&gt;Inspect.exe&lt;/code&gt; tool which is included in the &lt;a href="https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk" title="Download Windows 10 SDK"&gt;Windows 10 SDK&lt;/a&gt;. Alternatives include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;UISpy (obsolete)&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/cplotts/snoopwpf/releases" title="Snoop releases on GitHub"&gt;Snoop&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Visual Studio Live Visual Tree for debuggable applications &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since I can't be bothered to spend my evenings working out which combination of options needs to be set just-so for the Inspect tool to install, I instead use Snoop to inspect elements.&lt;/p&gt;

&lt;p&gt;For this tutorial however I'll be using the debugger to find elements like some sort of caveman.&lt;/p&gt;

&lt;h3&gt;Peter Piper picked a project&lt;/h3&gt;

&lt;p&gt;Our &lt;code&gt;NewProjectDialog&lt;/code&gt; will initially support 3 methods.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Select project type. e.g. Class Library, Console Application etc.&lt;/li&gt;
&lt;li&gt;Set project name. Set the full name of the project using the textbox.&lt;/li&gt;
&lt;li&gt;Click ok. Click the ok button to create the project with the selected settings.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I have scaffolded these out and put the first line in the selecting project type method. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using TestStack.White.UIItems.Finders;
using TestStack.White.UIItems.WindowItems;

public class NewProjectDialog
{
    private readonly Window window;

    public NewProjectDialog(Window window)
    {
        this.window = window;
    }

    public void SelectType(string type)
    {
        var allChildren = window.GetMultiple(SearchCriteria.All);
    }

    public void SetName(string projectName)
    {
        throw new System.NotImplementedException();
    }

    public void ClickOk()
    {
        throw new System.NotImplementedException();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to find what the item we want to click when we change the project type is I've added this line to the &lt;code&gt;SelectType&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var allChildren = window.GetMultiple(SearchCriteria.All);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This finds all controls that are a child of the dialog, so is quite slow. When we debug it we find the project types are displayed using labels. Therefore we can change the slow line to instead find the label with the text we want.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var item = window.Get&amp;lt;TestStack.White.UIItems.Label&amp;gt;(SearchCriteria.ByText(type));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This returns the label. We can then click it to select the project type.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;item.Click();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our project type is now selected, rejoice!&lt;/p&gt;

&lt;h3&gt;Change of name&lt;/h3&gt;

&lt;p&gt;In order to name the project we need to find the text box used to name the project. Once again we get all items in the window so we know how to refine our search:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var allChildren = window.GetMultiple(SearchCriteria.All);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This time in the debugger we find we need to get the text box with the id "txt_Name". We find the item and set the text:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void SetName(string projectName)
{
    var textBox = window.Get&amp;lt;TestStack.White.UIItems.TextBox&amp;gt;(SearchCriteria.ByAutomationId("txt_Name"));

    textBox.Text = projectName;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally to click the "OK" button to create the project the &lt;code&gt;ClickOk&lt;/code&gt; method looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void ClickOk()
{
    var button = window.Get&amp;lt;TestStack.White.UIItems.Button&amp;gt;(SearchCriteria.ByText("OK"));

    button.Click();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Under the hood&lt;/h3&gt;

&lt;p&gt;Initially when I looked at the File menu I couldn't find a way to locate the menu bar itself. This is because the File menu items are &lt;code&gt;MenuProxy&lt;/code&gt; objects instead of the normal menu items.&lt;/p&gt;

&lt;p&gt;It's useful to know how to narrow down your element search when the items cannot be found by text or automation id. Generally I use a search for all items:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;window.GetMultiple(SearchCriteria.All);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or find all items of a custom type if I know it's a user control or some 3rd party control:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;window.GetMultiple(SearchCriteria.ByControlType(ControlType.Custom));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When you run the debugger to evaluate these statements you can inspect the result. This is the best way to make sure you're only looking at what White can see.&lt;/p&gt;

&lt;p&gt;While I was looking for the menu items White didn't seem to be able to find them (before I realised it could if I simply searched by text). For this reason I ended up reinventing the &lt;code&gt;SearchCriteria.ByText&lt;/code&gt; searching provided by White. To replicate this functionality I wrote a custom searcher which used the underlying UIAutomation framework. I include it here because it's handy to know how to walk the full tree of UIAutomation &lt;code&gt;AutomationElement&lt;/code&gt;s.&lt;/p&gt;

&lt;p&gt;In order to use the UIAutomation framework code I had to add the following references to my project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;UIAutomationTypes&lt;/li&gt;
&lt;li&gt;UIAutomationClient&lt;/li&gt;
&lt;li&gt;WindowsBase&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To add these right click the project and select "Add Reference...".&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/white-automation/system-windows-automation.png" alt="Add Reference" /&gt;&lt;/p&gt;

&lt;p&gt;Each &lt;code&gt;IUIItem&lt;/code&gt; in White such as Window, TextBox, Button, etc, exposes an &lt;code&gt;AutomationElement&lt;/code&gt; as a property. This is the class used by the UIAutomation framework.&lt;/p&gt;

&lt;p&gt;The code below will recursively walk the controls in the window and find any that contain the text passed in. If it doesn't find a match it will return &lt;code&gt;null&lt;/code&gt;. I added the method in &lt;code&gt;MainWindow.cs&lt;/code&gt; but it could go anywhere:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private static AutomationElement FindAutomationElement(AutomationElement element, string text)
{
    if (element == null)
    {
        return null;
    }

    // Use the tree walker and start at the root element.
    AutomationElement elementNode = TreeWalker.ControlViewWalker.GetFirstChild(element);

    while (elementNode != null)
    {
        // Check the name property to see if it matches the search item.
        if (elementNode.Current.Name.Equals(text, StringComparison.InvariantCultureIgnoreCase))
        {
            return elementNode;
        }

        // Iterate to next element.
        var value = FindAutomationElement(elementNode, text);

        // If we find something we can exit our recursive method early.
        if (value != null)
        {
            return value;
        }

        elementNode = TreeWalker.ControlViewWalker.GetNextSibling(elementNode);
    }

    // No more items in this branch of the tree.
    return null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;using&lt;/code&gt; statements required in &lt;code&gt;MainWindow.cs&lt;/code&gt; for this code are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Windows.Automation;
using TestStack.White.UIItems;
using TestStack.White.UIItems.WindowItems;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally I used this method to right click the references node in solution explorer and add a reference to my new project. This method which I put in &lt;code&gt;MainWindow.cs&lt;/code&gt; shows how to use White to navigate the UI and filter searches by searching from child objects.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public void AddReference(string referenceName)
{
    var solutionExplorerTab = window.Get(SearchCriteria.ByText("Solution Explorer"));

    // Focus the tab
    solutionExplorerTab.Click();

    // Get the solution explorer tree control
    var solutionExplorerTree = window.Get&amp;lt;Tree&amp;gt;(SearchCriteria.ByAutomationId("SolutionExplorer"));

    // The References node seems to throw an error when clicked normally, so I use my custom method.            
    var node = FindAutomationElement(solutionExplorerTree.AutomationElement, "References");

    var nodeItem = new UIItem(node, window);

    // Focus
    nodeItem.Click();

    // Click
    nodeItem.RightClick();

    // The context menu is accessed as a popup on the window.
    window.Popup.Item("Add Reference...").Click();

    // Get the only modal window.
    var dialog = window.ModalWindows()[0];

    // Click the list item for the reference type to activate it and reveal the checkbox.
    var listItem = dialog.Get(SearchCriteria.ByText(referenceName));

    listItem.Click();

    var checkBox = listItem.Get&amp;lt;CheckBox&amp;gt;(SearchCriteria.ByControlType(ControlType.CheckBox));

    checkBox.Checked = true;

    // Click "OK" to close the dialog.
    dialog.Get&amp;lt;Button&amp;gt;(SearchCriteria.ByText("OK")).Click();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;The full code&lt;/h3&gt;

&lt;p&gt;You can find the final code for this tutorial &lt;a href="https://github.com/EliotJones/white-automation-tutorial" title="GitHub Repository"&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2017/5/white-automation</guid>
      <pubDate>Wed, 10 May 2017 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>How it works: Selenium</title>
      <link>https://eliot-jones.com/2017/5/how-it-works-selenium</link>
      <description>

&lt;p&gt;I've done quite a bit of work with Selenium on and off, mainly for browser automation tests. There are many high quality official libraries for Selenium covering a range of languages. It's an amazing technology and a real joy to work with; however sometimes stuff can go wrong and it's useful to know what's going on under the hood in order to debug where the problem lies.&lt;/p&gt;

&lt;p&gt;For this reason I present my very-probably-wrong guide to Selenium.&lt;/p&gt;

&lt;h3&gt;Gecko, drivers!? What's going on?&lt;/h3&gt;

&lt;p&gt;There are 3 components in code that interacts with Selenium (ignoring &lt;code&gt;RemoteWebDriver&lt;/code&gt; use cases):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Your code&lt;/li&gt;
&lt;li&gt;A driver&lt;/li&gt;
&lt;li&gt;The browser&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For each browser that supports Selenium, the browser vendor provides a "driver". This is usually a small executable (.exe) program tailored for a specific browser:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://sites.google.com/a/chromium.org/chromedriver/" title="Google Chrome / Chromium"&gt;Chrome / Chromium&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/mozilla/geckodriver" title="Firefox"&gt;Firefox&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/" title="Edge"&gt;Edge&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Other drivers available&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This driver is the part your code actually interacts with. The driver then communicates with the browser using whatever magic the vendors design. In order to change browsers while using the same code, the drivers expose interfaces/endpoints that implement the &lt;a href="https://w3c.github.io/webdriver/webdriver-spec.html" title="WebDriver W3C Spec"&gt;WebDriver specification&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Put simply, this means the drivers are a simple RESTful API.&lt;/p&gt;

&lt;h3&gt;Demo&lt;/h3&gt;

&lt;p&gt;To demonstrate this I'll use the ChromeDriver &lt;a href="https://chromedriver.storage.googleapis.com/index.html?path=2.29/" title="ChromeDriver version 2.29"&gt;version 2.29&lt;/a&gt; which is the latest version at the time of writing. Drivers can only talk to the versions of the browser they are compatible with. In this demo I'm running Chrome on version 58.&lt;/p&gt;

&lt;p&gt;Once you have downloaded the driver you get a simple program called chromedriver.exe. If you double click the exe it launches a console window with some information about the driver version you are running and what port it's listening on:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/selenium1/chromedriver-launch.png" alt="The driver logs its version and the port it&amp;#39;s listening on" /&gt;&lt;/p&gt;

&lt;p&gt;On start-up the driver logs the message:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 9515
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This tells us we can access the driver at the URL &lt;code&gt;http://localhost:9515&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now that the driver is listening we can ask it to launch a browser instance for us. To do this we need to send an HTTP &lt;strong&gt;POST&lt;/strong&gt; request to the following URL:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;http://localhost:9515/session
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href="https://w3c.github.io/webdriver/webdriver-spec.html#new-session" title="W3C spec for new session"&gt;This method is defined in the specification&lt;/a&gt;. We also need to provide some extra information about the capabilities we want from the browser instance. To do this we pass JSON in the request body.&lt;/p&gt;

&lt;p&gt;For a blank set of capabilities the JSON looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
    "desiredCapabilities": {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To interact with the driver using HTTP requests I am going to use PowerShell since it's installed on all Windows systems. You can use Postman or Fiddler or curl or whichever client you want.&lt;/p&gt;

&lt;p&gt;After launching PowerShell we define the JSON for the request body and then send the request using PowerShell's &lt;code&gt;Invoke-RestMethod&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$body = @{
    desiredCapabilities = @{}
}

# Change the body object to something we can use to send a request
$json = $body | ConvertTo-Json

# Send the actual request
$response = Invoke-RestMethod -Method Post -Uri http://localhost:9515/session -Body $json
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After sending the last line, a new browser window should open. If you don't see the window try typing &lt;code&gt;$response.value&lt;/code&gt; into the PowerShell window and hitting enter. This should contain a message telling you what went wrong.&lt;/p&gt;

&lt;p&gt;This window has a unique &lt;code&gt;SessionId&lt;/code&gt; we use to interact with it specifically. We can display this id and assign it to a variable using PowerShell:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Store the id
$sessionId = $response.sessionId

# Show us what it is
Write-Host $sessionId
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For Chrome the session Id is some hash, for example &lt;code&gt;3c0802805fbec93515dacdcc2e6bba72&lt;/code&gt;. For Edge it's a GUID.&lt;/p&gt;

&lt;p&gt;Now we have a blank window, the next step is to navigate to a web page. &lt;a href="https://w3c.github.io/webdriver/webdriver-spec.html#go" title="Navigation from the spec"&gt;From the spec&lt;/a&gt; we need to hit the URL &lt;code&gt;http://localhost:9515/session/{session id}/url&lt;/code&gt; where &lt;code&gt;{session id}&lt;/code&gt; is the actual id of the session we created (and helpfully stored in the &lt;code&gt;$sessionId&lt;/code&gt; variable). We also need to tell the driver what URL we want to navigate to. Again we provide this information in the request body as JSON:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{ "url" : "https://w3c.github.io/webdriver/webdriver-spec.html#go" }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To achieve this in PowerShell we do the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$body = @{ url = "https://w3c.github.io/webdriver/webdriver-spec.html#go" }

$json = $body | ConvertTo-Json

# PowerShell will replace $sessionId in the URL with the actual session Id
$response = $response = Invoke-RestMethod -Method Post -Uri http://localhost:9515/session/$sessionId/url -Body $json
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After the last line the browser should navigate to the page in the specification. Finally let's find and click a button. Based on the information from the specification:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Define how we want to search for the element, in this case the element with the id "respec-pill"
$json = @{
    "using" = "id"
    "value" = "respec-pill"
} | ConvertTo-Json

# Find the element using the search parameters defined above
$response = Invoke-RestMethod -Method Post -Uri http://localhost:9515/session/$sessionId/element -Body $json

# Store the ID of the located element
$elementId = $response.value.ELEMENT

# Click the element using the ID we found, no need to post any JSON for this call
$response = Invoke-RestMethod -Method Post -Uri http://localhost:9515/session/$sessionId/element/$elementId/click
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully this shows you that the Selenium interaction that occurs when your code uses a library for Selenium is actually (fairly) simple. The complicated and magic part happens when the driver talks to the browser.&lt;/p&gt;

&lt;p&gt;Some key parts which can go wrong are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your code is using a version of the Selenium library which is sending requests that the driver doesn't understand.&lt;/li&gt;
&lt;li&gt;Your driver is the wrong version to interact with the version of the browser.&lt;/li&gt;
&lt;li&gt;The driver you are using has a bug or does not yet support a feature of the WebDriver specification (for example Edge supports a quite limited subset at the moment).&lt;/li&gt;
&lt;li&gt;Your code has a bug.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Of these, the last item is the absolute, 99.9%, most likely culprit for any bug. Followed by a version mismatch between any 2 of the components. Using your knowledge of how to interact with the driver without any intermediate code you can now perform an extra check to verify where the problem likely lies.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2017/5/how-it-works-selenium</guid>
      <pubDate>Thu, 04 May 2017 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Writing a custom debug visualizer for Visual Studio 2015</title>
      <link>https://eliot-jones.com/2016/11/visual-studio-2015-visualizer</link>
      <description>

&lt;p&gt;Often at work I'll be debugging some incredibly complex logic with lists that can be hundreds, if not thousands, of items long. While the ability to inspect these lists using the normal debugging tools is useful, it gets annoying trying to scroll to the 700th item in a list and then accidentally moving the mouse focus away and having to start again.&lt;/p&gt;

&lt;p&gt;For this reason I wanted to look into the possiblity of creating a custom display for certain objects while debugging in Visual Studio. For those of you who have worked with the &lt;code&gt;DataTable&lt;/code&gt; you might be familiar with this screen:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/Visualizer/data-table-visualizer.png" alt="data table visualizer" /&gt;&lt;/p&gt;

&lt;p&gt;This can be accessed by hovering over the object when paused in the debugger and clicking the magnifying glass icon as shown here:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/Visualizer/magnifying-glass.png" alt="magnifying glass accessed from debugger" /&gt;&lt;/p&gt;

&lt;p&gt;Visual Studio supports &lt;a href="https://msdn.microsoft.com/en-us/library/e2zc529c.aspx" title="how to: write a visualizer"&gt;creating custom screens&lt;/a&gt; like this called &lt;strong&gt;Visualizers&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;Getting Started&lt;/h3&gt;

&lt;p&gt;The &lt;a href="https://msdn.microsoft.com/en-us/library/e2zc529c.aspx" title="how to: write a visualizer"&gt;linked MSDN guide&lt;/a&gt; and similar guides detail how to create the custom screen using WinForms. I wanted to use WPF because it was the desktop UI technology I was most familiar with. 
I followed the &lt;a href="https://msdn.microsoft.com/en-us/library/ms164759.aspx" title="walkthrough: writing a visualizer"&gt;walkthrough&lt;/a&gt; but used this code to display the Visualizer:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var window = new MainWindow();
window.ShowDialog();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This worked well and my empty WPF window was displayed, but when I closed the window a &lt;em&gt;CannotUnloadAppDomainException&lt;/em&gt; was thrown and the WPF window reopened:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;System.CannotUnloadAppDomainException was unhandled
HResult=-2146234347 Message=Error while unloading appdomain. (Exception from HRESULT: 0x80131015) 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I spent a couple of hours trying to figure this out and ended up talking to myself on StackOverflow, in the end it turned out it was &lt;a href="http://stackoverflow.com/questions/40685957/visualizer-an-unhandled-exception-of-type-system-cannotunloadappdomainexceptio/40687053" title="stackoverflow: cannot unload appdomain exception"&gt;due to the Stylus Input thread refusing to close&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The solution to this was to explicitly close the WPF Dispatcher when closing the window:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;protected override void OnClosing(CancelEventArgs e)
{
    Dispatcher.InvokeShutdown();

    base.OnClosing(e);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This closed the stylus input (touchscreen) thread properly and my Visualizer now worked properly.&lt;/p&gt;

&lt;h3&gt;Custom Objects&lt;/h3&gt;

&lt;p&gt;Since I wanted to write Visualizers for custom types rather than just the system types, the next step was to experiment with a custom class. For testing I imaginatively created a person class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Person
{
    public Guid Id { get; private set; }

    public string FirstName { get; private set; }

    public string LastName { get; private set; }

    public string FavoriteColor { get; private set; }

    public DateTime BirthDate { get; set; }

    public Person(string firstName, string lastName, DateTime birthDate, string favoriteColor)
    {
        Id = Guid.NewGuid();
        FirstName = firstName;
        LastName = lastName;
        BirthDate = birthDate;
        FavoriteColor = favoriteColor;
    }

    private Person()
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Generally if a class is marked with the &lt;code&gt;[Serializable]&lt;/code&gt; attribute it can be passed directly to your Visualizer. This is because the active object from Visual Studio must be serialized and passed to the debugger side which runs separately, the Visualizer doesn't have access to the original object. When the type is marked with the serializable attribute it can be easily retrieved using the method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;objectProvider.GetObject();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However since a lot of the classes I was working with weren't going to be &lt;code&gt;[Serializable]&lt;/code&gt; I needed to support types without this attribute.&lt;/p&gt;

&lt;h3&gt;Non-Serializable types&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;Person&lt;/code&gt; class above is not marked as &lt;code&gt;[Serializable]&lt;/code&gt; in order to experiment with visualizing non-serializable types.&lt;/p&gt;

&lt;p&gt;Since we need to pass objects between the process being debugged and the Visualizer I opted to use JSON.&lt;/p&gt;

&lt;p&gt;My Visualizer code was:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;assembly: DebuggerVisualizer(typeof(DebuggerSide), typeof(PersonObjectSource),
    Target = typeof(Person), Description = "Person Visualizer")]
namespace Visualizer
{
    public class DebuggerSide : DialogDebuggerVisualizer
    {
        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            try
            {
                using (var reader = new StreamReader(objectProvider.GetData()))
                {
                    var result = reader.ReadToEnd();

                    var person = JsonConvert.DeserializeObject&amp;lt;Person&amp;gt;(result, new JsonSerializerSettings
                    {
                        ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                        ContractResolver = new PrivatePropertyResolver()
                    });

                    if (person == null)
                    {
                        MessageBox.Show("Cannot visualize this object, please use a different visualizer.", "Type Not Supported", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }

                    var window = new MainWindow(person);

                    window.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                Trace.Fail(ex.Message, ex.StackTrace);
            }

        }

        public static void TestShowVisualizer(object thingToVisualize)
        {
            var visualizerHost = new VisualizerDevelopmentHost(thingToVisualize, typeof(DebuggerSide), typeof(PersonObjectSource));
            visualizerHost.ShowVisualizer();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's worth noting that this handles the case where it's been handled the wrong object type gracefully using a WinForms message box to inform the user the object is wrong:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (person == null)
{
    MessageBox.Show("Cannot visualize this object, please use a different visualizer.", "Type Not Supported", MessageBoxButtons.OK, MessageBoxIcon.Information);

    return;
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This turns out to be useful for a List visualizer where, even if only want to provide visualization for a single type of object, you can't specify the type of T in a Visualizer for &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; so you must handle Visualization requests for the wrong type.&lt;/p&gt;

&lt;p&gt;In order to provide the &lt;code&gt;Person&lt;/code&gt; to this Visualizer we must write it to the stream. We do this by specifying that our Visualizer uses a &lt;code&gt;PersonObjectSource&lt;/code&gt;. This class inherits from the normal &lt;code&gt;VisualizerObjectSource&lt;/code&gt; but overrides &lt;code&gt;GetData&lt;/code&gt; to use JSON serialization instead:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class PersonObjectSource : VisualizerObjectSource
{
    public override void GetData(object target, Stream outgoingData)
    {
        var person = target as Person;

        if (person == null)
        {
            return;
        }

        var writer = new StreamWriter(outgoingData);

        var content = JsonConvert.SerializeObject(person);

        writer.WriteLine(content);

        writer.Flush();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again we use the &lt;code&gt;as&lt;/code&gt; operator here to handle the case where we get an unexpected or null object type.&lt;/p&gt;

&lt;p&gt;Now we have our person object in our Visualizer we can use it in our WPF window and write a normal WPF application. For this example I put together a terrible UI:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/Visualizer/person-visualizer.png" alt="person visualizer showing name and favorite color" /&gt;&lt;/p&gt;

&lt;h3&gt;Lists&lt;/h3&gt;

&lt;p&gt;I also wanted to support Visualization of lists of a certain type. Unfortunately it's not possible to specify the type of &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; you wish to provide Visualization support for so Visual Studio will provide your visualizer for all Lists. &lt;/p&gt;

&lt;p&gt;Since the Visualizer I was intending to write would be internal to the company it would be acceptable to handle the case where the List was of the wrong type by displaying a message box, but this would be annoying to general users.&lt;/p&gt;

&lt;p&gt;To specify that your Visualizer supports Lists you simply specify this in the assembly attribute:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[assembly: DebuggerVisualizer(typeof(DebuggerSide), typeof(VisualizerObjectSource),
    Target = typeof(List&amp;lt;&amp;gt;), Description = "My List Visualizer")]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And then handle being passed the wrong type in the &lt;code&gt;Show&lt;/code&gt; method.&lt;/p&gt;

&lt;h3&gt;A more advanced case&lt;/h3&gt;

&lt;p&gt;I am terrible at both pronouncing and writing Regexes (Ree-gexes?) and struggle with cases more complex than &lt;code&gt;.*&lt;/code&gt;. My favourite site for writing Regexes is &lt;a href="http://regexstorm.net/" title="Regex Storm - Online .NET regex"&gt;Regex Storm&lt;/a&gt; since it is based on the .NET regex engine and provides a clean, simple UI.&lt;/p&gt;

&lt;p&gt;Despite having that site available I still struggle with getting Regexes right, especially when using named Groups.&lt;/p&gt;

&lt;p&gt;For that reason to practice writing Visualizers I put together this basic Visualizer for a &lt;code&gt;MatchCollection&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/Visualizer/regex-visualizer.png" alt="regex visualizer showing matches, groups and captures" /&gt;&lt;/p&gt;

&lt;p&gt;The full code for this Visualizer and the simpler Person Visualizer can be found &lt;a href="https://github.com/EliotJones/VS2015Visualizer" title="source on github"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Installation&lt;/h3&gt;

&lt;p&gt;In order to install a Visualizer the .dll simply needs to be placed in (assuming a default Visual Studio installation):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You will need an administrator account to move files into this folder.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2016/11/visual-studio-2015-visualizer</guid>
      <pubDate>Sun, 20 Nov 2016 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Reading from a COM port</title>
      <link>https://eliot-jones.com/2016/11/csharp-serial-port</link>
      <description>

&lt;p&gt;I was recently researching how to read from a COM (Serial) port in order to communicate with an old embedded system. If you're not familiar with them that's one of these:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/Serial_port.jpg" alt="a serial port has a 9 pin connection" /&gt;&lt;/p&gt;

&lt;p&gt;C# provides the &lt;code&gt;SerialPort&lt;/code&gt; class for just this purpose which is hugely helpful. However there's one problem with this class which is that it's just not... very good. I didn't know about this but &lt;a href="http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport"&gt;this post&lt;/a&gt; by Ben Voigt should leave you in no doubt that it has some problems.&lt;/p&gt;

&lt;h3&gt;Setup&lt;/h3&gt;

&lt;p&gt;In order to test the code on my machine without access to the actual device which was elsewhere, I installed Eltima's &lt;a href="http://www.eltima.com/products/vspdxp/"&gt;Virtual Serial Port Driver&lt;/a&gt; which would allow me to test with emulated serial ports. Once I had set up a pair of ports I could send data from one end using PowerShell. &lt;/p&gt;

&lt;p&gt;I created a pair of virtual ports called COM1 and COM2, COM1 would be the port I was using C# to read from. COM2 would emulate the device sending data.&lt;/p&gt;

&lt;p&gt;For testing I was just sending blocks of text from COM2 using the following PowerShell script:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$port = New-Object System.IO.Ports.SerialPort COM2,9600,None,8,one
$port.Open()
$port.WriteLine("some test data")
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;The Code&lt;/h3&gt;

&lt;p&gt;Because the application I was using to read from the port would be a C# console application I didn't have any way to use async-await properly so stuck with the approach outline in &lt;a href="http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport"&gt;Ben's blog post&lt;/a&gt;, namely using &lt;code&gt;IAsyncResult&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The code which listens to and reads from the result looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class COMReader
{
    private static readonly BlockingCollection&amp;lt;byte[]&amp;gt; queue = new BlockingCollection&amp;lt;byte[]&amp;gt;();

    public static int Main()
    {
        using (var port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
        {
            Handshake = Handshake.None,
            ReadTimeout = 1000,
            WriteTimeout = 1000
        })
        {
            port.Open();

            var consumer = new Consumer(queue);
            var buffer = new byte[256];
            Action startListen = null;
            var onResult = new AsyncCallback(result =&amp;gt; OnResult(result, startListen, port, buffer));

            Task.Run(() =&amp;gt; consumer.Start());

            startListen = () =&amp;gt; 
            {
                port.BaseStream.BeginRead(buffer, 0, buffer.Length, onResult, null);
            };

            startListen();

            while (true &amp;amp;&amp;amp; port.IsOpen)
            {
                // handle user's console window interaction.
            }

            queue.CompleteAdding();

            if (port.IsOpen)
            {
                port.Close();
            }
        }

        return 0;
    }

    private static void OnResult(IAsyncResult result, Action startListen, SerialPort port, byte[] buffer)
    {
        try
        {
            if (!port.IsOpen)
            {
                return;
            }

            var actualLength = port.BaseStream.EndRead(result);

            var received = new byte[actualLength];

            Buffer.BlockCopy(buffer, 0, received, 0, actualLength);

            queue.Add(received);
        }
        catch (IOException)
        {
            Console.WriteLine("I/O exception encountered. Closing.");
            port.Close();
            queue.CompleteAdding();
            return;
        }

        startListen();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Most of this is fairly self explanatory, we create a &lt;code&gt;SerialPort&lt;/code&gt; instance (in a &lt;code&gt;using&lt;/code&gt; statement since it implements &lt;code&gt;IDisposable&lt;/code&gt;) and then open it. We also create a new &lt;code&gt;Consumer&lt;/code&gt;, which I will talk about in a moment.&lt;/p&gt;

&lt;p&gt;Next as in the blog post I mentioned we have an action to execute, this is declared separately to its assignment since it needs to run itself when it finishes reading. The body of the code to execute once the async read finishes is in the &lt;code&gt;OnResult&lt;/code&gt; method. This just reads the current bytes from the port's stream.&lt;/p&gt;

&lt;p&gt;The next step is to start the &lt;code&gt;Consumer&lt;/code&gt; running on another thread using &lt;code&gt;Task.Run()&lt;/code&gt;. Then we simply start the action which listens to the port.&lt;/p&gt;

&lt;p&gt;This will listen for incoming messages on the port and each time something is received it will call the code in &lt;code&gt;OnResult(..)&lt;/code&gt; and then start listening again.&lt;/p&gt;

&lt;h3&gt;Consuming&lt;/h3&gt;

&lt;p&gt;In order to read the output data two things have to be done:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Return to the &lt;code&gt;startListen()&lt;/code&gt; method at the end of &lt;code&gt;OnResult&lt;/code&gt; as quickly as possible to avoid missing data.&lt;/li&gt;
&lt;li&gt;Notify some subscriber to the data and work out if the received data forms a complete message.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since the SerialPort will read data whenever it feels like it instead of waiting for a complete message we need to know what our definition of a "message" is, in the case of my PowerShell script its end is the &lt;code&gt;\n&lt;/code&gt; character.&lt;/p&gt;

&lt;p&gt;This is an almost perfect use case for a &lt;code&gt;BlockingCollection&lt;/code&gt;, this provides a location for the &lt;code&gt;OnResult&lt;/code&gt; method to dump the data and allows us to write a consumer for the data which only runs when new data is found.&lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;Consumer&lt;/code&gt; class is constructed by passing in the blocking collection &lt;code&gt;queue&lt;/code&gt; which the main method writes to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var consumer = new Consumer(queue);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code for consumer is below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Consumer
{
    private const byte TerminatingCharacter = 10;

    private readonly BlockingCollection&amp;lt;byte[]&amp;gt; producer;

    private readonly List&amp;lt;byte&amp;gt; bytes = new List&amp;lt;byte&amp;gt;();

    public Consumer(BlockingCollection&amp;lt;byte[]&amp;gt; producer)
    {
        this.producer = producer;
    }

    public void Start()
    {
        Console.WriteLine("Start listening");

        foreach (var item in producer.GetConsumingEnumerable())
        {
            ProcessInput(item);
        }

        Console.WriteLine("Finish listening");
    }

    private void ProcessInput(byte[] input)
    {
        if (input == null || input.Length == 0)
        {
            return;
        }

        if (input[input.Length - 1] == TerminatingCharacter)
        {
            var message = Encoding.UTF8.GetString(bytes.Concat(input).ToArray());

            Console.WriteLine($"Message Received: {Environment.NewLine}{message}{Environment.NewLine}");

            bytes.Clear();
        }
        else
        {
            bytes.AddRange(input);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This class keeps a reference to the producer's blocking collection. When it starts listening using the &lt;code&gt;Start&lt;/code&gt; method it will keep listening to the collection until &lt;code&gt;queue.CompleteAdding();&lt;/code&gt; is called. Every time a new item is added to the queue the consumer will run the &lt;code&gt;ProcessInput&lt;/code&gt; method where &lt;code&gt;item&lt;/code&gt; is the byte array we placed on the queue in the producer.&lt;/p&gt;

&lt;p&gt;Using this approach we can perform a slower analysis of the messages we have received so far in order to pull the complete messages out. For this demo application I just check for the last byte received to be the character &lt;code&gt;\n&lt;/code&gt; but your definition of message may be more complex depending on the device which produces the message.&lt;/p&gt;

&lt;p&gt;Because we run the consumer on its own thread:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Task.Run(() =&amp;gt; consumer.Start());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The time taken for the listener to respond to new data from the port is completely decoupled from the code to process these events.&lt;/p&gt;

&lt;p&gt;This isn't perfect code because in the failure case it doesn't wait for the consumer to finish processing the queue before shutting down and there is insufficient error handling around parts of it. However it will hopefully provide an idea how the &lt;code&gt;BlockingCollection&lt;/code&gt; can be used to communicate between a publisher and subscriber on separate threads and how that principle can be applied to Serial Ports.&lt;/p&gt;

&lt;h3&gt;4096 limit&lt;/h3&gt;

&lt;p&gt;It's worth noting that by default a message is limited to 4096 bytes, if the end of the message isn't received in this time the rest of the message will be dropped. In order to avoid this set the &lt;code&gt;ReadBufferSize&lt;/code&gt; on the &lt;code&gt;SerialPort&lt;/code&gt; to something higher than 4096.&lt;/p&gt;

&lt;p&gt;I'm not an embedded systems person so all of this is my best guess, if I've done something completely idiotic, please let me know in the comments.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2016/11/csharp-serial-port</guid>
      <pubDate>Mon, 14 Nov 2016 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>New Site</title>
      <link>https://eliot-jones.com/2016/11/new-site</link>
      <description>

&lt;p&gt;I've not been able to find time to blog at all since starting my new job in March, working at a startup
means learning a lot but also working long hours!&lt;/p&gt;

&lt;p&gt;Almost a year and a half after first blogging about vNext/.NET core I've finally written my first
(almost) functional program in it. I've changed this blog from a horrible mess of PHP to a nice
MVC6 site running on an Ubuntu server using .NET core. The nice part is noticeable in the code,
the UI still remains a dumpster-fire.&lt;/p&gt;

&lt;p&gt;The motivation to finally get a site running using .NET core was from &lt;a href="http://www.hanselman.com/blog/PublishingAnASPNETCoreWebsiteToACheapLinuxVMHost.aspx"&gt;this blog post&lt;/a&gt; by Scott
Hanselman which shows just how easy it is to get something running on .NET core. I grabbed a very cheap
Ubuntu droplet from Digital Ocean and followed along, all development was done on my awful 8 year old
laptop running xUbuntu. It's so nice to be able to build C# apps and have them run across platforms.&lt;/p&gt;

&lt;p&gt;Another improvement is I have scripted my entire deployment using a shell script, as soon as I'm happy
with my changes I can run one script which will build, package, deploy and start the site. No more tedious manual
FTP interaction. &lt;/p&gt;

&lt;p&gt;The code for the blog is &lt;a href="https://github.com/EliotJones/LightBlog"&gt;on GitHub&lt;/a&gt; so you can see just how badly written it is and probably hack
my terrible home-brew security stuff.&lt;/p&gt;

&lt;p&gt;I'm still missing a couple of features from the old blog which I was too lazy to port across but hopefully they
won't be missed by anyone, if you want them back (code snippets hosted on this site for some older tutorials)
let me know in the comments.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2016/11/new-site</guid>
      <pubDate>Sat, 05 Nov 2016 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Run tests task for Elixir in Visual Studio Code</title>
      <link>https://eliot-jones.com/2016/2/elixir-test-visual-studio-code</link>
      <description>

&lt;p&gt;In order to learn Linux I'm biting off more than I can chew by trying to learn &lt;a href="http://elixir-lang.org/" title="Official Elixir language site"&gt;Elixir&lt;/a&gt; at the same time. From the available code editors for Linux I'm using &lt;a href="https://code.visualstudio.com/" title="Visual Studio Code site"&gt;Visual Studio Code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Visual Studio Code has the ability to configure custom tasks.&lt;/p&gt;

&lt;p&gt;To get to the custom task configuration you can use the command palette with &lt;code&gt;Ctrl + Shift + P&lt;/code&gt; and type &lt;code&gt;Tasks: Configure Task Runner&lt;/code&gt;. This will open "tasks.json". Replace the contents with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
    "version": "0.1.0",
    "command": "bash",
    "isShellCommand": true,
    "showOutput": "always",
    "args": [
        "-c"
    ],
    "tasks": [
        {
            "taskName": "Elixir-Test",
            "suppressTaskName": true,
            "isTestCommand": true,
            "args": ["mix test"]
        }
    ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And save the file. Now if you use &lt;code&gt;Ctrl + Shift + T&lt;/code&gt; mix will run your tests for the project (assuming you have the &lt;code&gt;mix.exs&lt;/code&gt; level folder open) and print the output to the console.&lt;/p&gt;

&lt;p&gt;This command could probably be improved by checking that it's executing in the correct folder first but I'm nowhere near confident enough with Bash to write it yet.&lt;/p&gt;

&lt;h3&gt;Further notes from adventures in Elixir&lt;/h3&gt;

&lt;h4&gt;Function capturing (Capture operator)&lt;/h4&gt;

&lt;p&gt;This concept took me a little while to get to grips with because I couldn't think of an equivalent from C#.&lt;/p&gt;

&lt;p&gt;A typical anonymous function in Elixir might take this form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;square = fn x -&amp;gt; x * x end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You would then call it with the dot "." between the function name and the argument like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Outputs 9
square.(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;function capturing operator&lt;/strong&gt; (&amp;amp;) allows us to express the same function even more quickly:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;square = &amp;amp;(&amp;amp;1 * &amp;amp;1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We call this function in the same way and the output is exactly the same:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Outputs 9
square.(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You could break this down further to understand it:&lt;/p&gt;

&lt;pre&gt;&lt;code class=" hljs cs"&gt;
# Start anonymous function definition with unknown number of arguments.
# e.g. fn ? -&gt;
&amp;(

# Take the first argument (&amp;1) to the anonymous function and multiply by the same argument
&amp;1 * &amp;1

# End anonymous function
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you try to pass more than one argument to this function you will get an error:&lt;/p&gt;

&lt;pre&gt;&lt;code class=" hljs cs"&gt;
# (BadArityError) function with arity 1 called with 2 arguments (0, 3)
square.(0, 3)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The arity is the number of arguments the function takes. &lt;/p&gt;

&lt;p&gt;Equally if you try to define the function without using all the positional arguments in the function you get a compile error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Won't compile
square = &amp;amp;(&amp;amp;2 * &amp;amp;2)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is another form of function capture which only works with named functions. For example for the standard anonymous function (using the length named function from the String module):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;len = fn s -&amp;gt; String.length(s) end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running that will give the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Outputs 9
len.("chow chow")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using our current understanding of the capture operator we could rewrite to the equivalent but shorter form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;len = &amp;amp;(String.length(&amp;amp;1))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is a second form we can use which is equivalent:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;len2 = &amp;amp;String.length/1    
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can also verify these functions are identical:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Outputs true
len == len2
&lt;/code&gt;&lt;/pre&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2016/2/elixir-test-visual-studio-code</guid>
      <pubDate>Fri, 12 Feb 2016 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Git for beginners</title>
      <link>https://eliot-jones.com/2016/2/git-for-beginners</link>
      <description>

&lt;p&gt;Out of the different Source Control options Git is definitely the one most worth learning, however, it's also one of the most confusing.&lt;/p&gt;

&lt;p&gt;With that in mind I'm going to add to the crowded market of "Git beginners" tutorials. Hopefully given that I can still remember the struggle of learning it and that my current level of understanding probably rates as "simpleton" this will be a useful tutorial.&lt;/p&gt;

&lt;p&gt;I'm going to be writing for Git on Windows and will try to assume no existing knowledge beyond knowing what a file and folder is. Because of this I'm going to make a lot of oversimplifications.&lt;/p&gt;

&lt;h3&gt;Install It&lt;/h3&gt;

&lt;p&gt;Use the download link &lt;a href="https://git-scm.com/downloads" title="Download the Git for windows tools from the official Git site"&gt;here&lt;/a&gt; or Google "Windows Git" and click the first link.&lt;/p&gt;

&lt;p&gt;After using the installation defaults, you're done.&lt;/p&gt;

&lt;p&gt;&lt;details&gt;
&lt;summary&gt;Where does it install?&lt;/summary&gt;&lt;/p&gt;

&lt;p&gt;Depending on which architecture version (x86/x64) you installed it will probably install in either &lt;code&gt;C:\Program Files\Git&lt;/code&gt; or &lt;code&gt;C:\Program Files (x86)\Git&lt;/code&gt;.
&lt;/details&gt;&lt;/p&gt;

&lt;h3&gt;Launch It&lt;/h3&gt;

&lt;p&gt;Since using one of the nice user interfaces will only shield you from the true horror, it's best to start using console.&lt;/p&gt;

&lt;p&gt;Search for "Git Bash" in your start menu or find it in the install location. Once launched you should see this window:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/blank-prompt.png" alt="A blank git prompt" /&gt;&lt;/p&gt;

&lt;p&gt;Depending on how comfortable you are with Window's command prompt you're either happy with what's going on, or the panic is already setting in.&lt;/p&gt;

&lt;h3&gt;Bash&lt;/h3&gt;

&lt;p&gt;Bash is effectively the Linux version of the command prompt from Windows. The command prompt is just a window which you type stuff into and things happen.&lt;/p&gt;

&lt;p&gt;The dollar sign "$" is the prompt, it's asking you to write something on that line and when you hit enter it will run your command.&lt;/p&gt;

&lt;p&gt;Let's start by working out where we are. Type the following command at the prompt:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;pwd
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And hit enter. You should see something like the following result:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/current-directory.png" alt="pwd tells you the current directory" /&gt;&lt;/p&gt;

&lt;p&gt;By using pwd (print working directory) we're able to see that our current command prompt (Bash) is pointing at "C:\Users\Eliot" (or your equivalent)&lt;/p&gt;

&lt;p&gt;&lt;details&gt;
    &lt;summary&gt;Why does the file path look weird?&lt;/summary&gt;
    &lt;p&gt;This is because Windows decided to be difficult and use a different way of showing folder and file locations to everyone else. Since Bash is like running Linux it uses forward slashes "/" instead of back slashes "\".&lt;/p&gt;
&lt;/details&gt;&lt;/p&gt;

&lt;p&gt;Now let's move somewhere useful.&lt;/p&gt;

&lt;p&gt;Since I'm exceedingly lazy I like to store all my code directly on my C drive, rather than in my Users folder. I have a folder located at C:\code (for the sake of the tutorial you should create one too).&lt;/p&gt;

&lt;p&gt;For navigating folders Git Bash uses the same command as Windows. &lt;code&gt;cd&lt;/code&gt; -change directory. Go ahead and type the following command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd /c/code
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Your console output should look similar to this:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/change-directory.png" alt="change directory command changes the active path" /&gt;&lt;/p&gt;

&lt;p&gt;Notice how the yellow tilde character "~" above the prompt has changed to be "/c/code"? From this we learn that the yellow text shows us our currently active folder. To verify this you could type &lt;code&gt;pwd&lt;/code&gt; and check it prints out "/c/code". &lt;/p&gt;

&lt;p&gt;This also tells us that the "~" character has a special meaning. It corresponds to the base folder of the user's environment, mine is located at "C:\Users\Eliot".&lt;/p&gt;

&lt;p&gt;So far we've not actually used any Git commands, these have been Bash commands. Git commands can are run through Bash.&lt;/p&gt;

&lt;h3&gt;Gitting Started&lt;/h3&gt;

&lt;p&gt;If you're still here after that terrible pun, it's time to actually do something with Git.&lt;/p&gt;

&lt;p&gt;Let's create some code we might want to store under source control. For this demo I'm just going to make a project containing some static HTML and css.&lt;/p&gt;

&lt;p&gt;In a new folder located at &lt;code&gt;C:\code\my-website&lt;/code&gt; I made an html page and some css (index.html and site.css). Create the folder called my-website now and add these files. You can leave them empty for now if you don't know how to write html or css:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/no-git.png" alt="I have an html and css page in my my-website folder" /&gt;&lt;/p&gt;

&lt;p&gt;To prepare to use our first Git command, move into this folder using Bash. If your current directory is &lt;code&gt;C:\code&lt;/code&gt; you can type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd my-website
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or to get to it from anywhere:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd /c/code/my-website
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now for our first Git command, type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git init
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You should see the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Initialized empty Git repository in C:/code/my-website/.git/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is how we create a Git &lt;strong&gt;repository&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A Git repository is a basically a folder which is under source control.&lt;/p&gt;

&lt;p&gt;&lt;details&gt;
    &lt;summary&gt;
        How does the repository work?
    &lt;/summary&gt;
    &lt;p&gt;If you look at the C:\code\my-website folder in Windows file explorer you should see a new folder called ".git" alongside your files. If you can't see it you may need to enable viewing hidden folders.&lt;/p&gt;
    &lt;p&gt;This .git folder contains the files Git uses to track changes under source control. This makes it easy to delete a repository while keeping the files. All you need to do is delete the .git folder.&lt;/p&gt;
&lt;/details&gt;&lt;/p&gt;

&lt;p&gt;There's a new bit of information in the line above the prompt in Git Bash. After the current active path there's the word "master" in brackets. This is the current branch name. &lt;/p&gt;

&lt;p&gt;Don't worry too much about branches for now, we'll get to them in a bit.&lt;/p&gt;

&lt;p&gt;All we have to do to make our repository active in Bash is navigate to the folder containing the repository (or any folders under that folder). If we use the &lt;code&gt;cd&lt;/code&gt; command to navigate up a level and then back into our my-website folder, we see the branch name disappears then reappears from the text above the prompt. The branch name only shows when we're in a repository. Try these commands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd ..
cd my-website
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For an illustration of what you should see, look at the screenshot below:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/leave-and-enter-repository.png" alt="The master in brackets shows the branch in the active repository" /&gt;&lt;/p&gt;

&lt;h3&gt;Fear of Commitment&lt;/h3&gt;

&lt;p&gt;We've know that the Bash console shows us which branch is currently active when we're in a repository. Another way to get this information is the command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git status
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As well as printing the branch name this command also prints the status of files in the folder (repository):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;On branch master

Initial commit

Untracked files:
  (use "git add &amp;lt;file&amp;gt;..." to include in what will be committed)

        index.html
        site.css

nothing added to commit but untracked files present (use "git add" to track)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This tells us we have 2 untracked files. An untracked file is one which isn't under source control. If we delete it, or mess it up in some way, Git isn't going to help us. With that in mind let's track it. As the output from &lt;code&gt;git status&lt;/code&gt; helpfully suggests, we can use the following command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git add
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you type just that statement you get the following output:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Nothing specified, nothing added.
Maybe you wanted to say 'git add .'?
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The argument to &lt;code&gt;git add&lt;/code&gt; is the path to the file or files you want to track. The '.' dot means "all currently untracked files". Let's use the following two commands to add the files and then check the status:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git add .
git status
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/git-add.png" alt="Git add tracks both the files" /&gt;&lt;/p&gt;

&lt;p&gt;Our changes are now "staged" and we're ready to commit them. A commit is a snapshot of how all files in the project looked at a particular point in time. It's a bit like if we copied our project folder and renamed it "my-website-20160209". &lt;/p&gt;

&lt;p&gt;Once you have a commit you can always go back to how the files looked when you made that commit.&lt;/p&gt;

&lt;p&gt;This is an exciting moment for us, the first commit in our repository! The simplest way to make a commit is with the following command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git commit -m "our first commit"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;-m&lt;/code&gt; &lt;strong&gt;option&lt;/strong&gt; tells Git we will provide the message for our commit along with the command. This message can be anything; "toast", "tire iron", "updated tests to use mocks". It's just a friendly label we can use to remind people and ourselves what we did between this commit and the last one.&lt;/p&gt;

&lt;p&gt;Now if we use &lt;code&gt;git status&lt;/code&gt; we can see that nothing has changed in our repository since we made our commit.&lt;/p&gt;

&lt;h3&gt;Captain's Log&lt;/h3&gt;

&lt;p&gt;Now we've made a commit how do we view the commits in our repository? The answer is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git log
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/git-commit.png" alt="Git commit creates a snapshot of the project files" /&gt;&lt;/p&gt;

&lt;p&gt;The log lists all the commits in our repository with the latest at the top of the log. The long yellow word containing both numbers and letters is the &lt;strong&gt;hash&lt;/strong&gt; of our commit. This is a unique bit of text which identifies our commit for Git commands.&lt;/p&gt;

&lt;h3&gt;From Logs to Branches&lt;/h3&gt;

&lt;p&gt;I mentioned earlier that the "master" in brackets tells us which branch we're on. Now we've got our first commit it's time to learn about branches.&lt;/p&gt;

&lt;p&gt;A branch is a way of having multiple different sets of the same code which are changing in different ways. For example if you have a text file (file.txt) that both you and your friend Eric are editing, you might share a folder containing "file.txt, my-file.txt, eric-file.txt". This way you can work on your file, Eric can work on his and neither of you are going to irreversibly mess up the original file.&lt;/p&gt;

&lt;p&gt;Every Git repository starts with a branch called "master". That's why, when you used the &lt;code&gt;git init&lt;/code&gt; command, the active branch name was "master".&lt;/p&gt;

&lt;p&gt;To see every branch in your repository you can type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git branch -a
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;-a&lt;/code&gt; option tells Git to list all branches. The output of this command is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;* master
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The asterisk '*' shows which branch is currently active.&lt;/p&gt;

&lt;p&gt;Now let's assume we want to change our files, but these are experimental css changes which we might throw away. To create a new branch:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git checkout -b css-changes
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;-b&lt;/code&gt; option means this command will create a new branch, rather than moving between existing branches.&lt;/p&gt;

&lt;p&gt;If you type &lt;code&gt;git branch -a&lt;/code&gt; now, you'll see that there are two branches and the branch css-changes is active. The text above the bash prompt will also have updated:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/git-branch.png" alt="Git checkout with the b switch creates a new branch" /&gt;&lt;/p&gt;

&lt;p&gt;If we use &lt;code&gt;git log&lt;/code&gt; to check our commit history we can see it's the same as master. Creating a new branch from another branch will bring all the commits from the source branch.&lt;/p&gt;

&lt;p&gt;Now to make some changes to a file update site.css to add some styles to it, for instance:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;div{
    box-sizing: border-box;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once you save these changes in your editor, type &lt;code&gt;git status&lt;/code&gt; to see what's going on.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;On branch css-changes
Changes not staged for commit:
  (use "git add &amp;lt;file&amp;gt;..." to update what will be committed)
  (use "git checkout -- &amp;lt;file&amp;gt;..." to discard changes in working directory)

        modified:   site.css

no changes added to commit (use "git add" and/or "git commit -a")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Git has detected that our site.css has changed. We need to use the &lt;code&gt;git add&lt;/code&gt; command again to be able to commit the file. Use the following 2 commands:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git add .
git commit -m "css changes"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we type git log we now see 2 commits in this branch. &lt;/p&gt;

&lt;p&gt;After making this commit let's also change the index.html file. I added the line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;iframe&amp;gt;&amp;lt;/iframe&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now this was a mistake, iframes are bad. How do we undo this? If you type &lt;code&gt;git status&lt;/code&gt; the output should say something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;On branch css-changes
Changes not staged for commit:
  (use "git add &amp;lt;file&amp;gt;..." to update what will be committed)
  (use "git checkout -- &amp;lt;file&amp;gt;..." to discard changes in working directory)

        modified:   index.html

no changes added to commit (use "git add" and/or "git commit -a")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One option is to use &lt;code&gt;git checkout -- index.html&lt;/code&gt; which will reset the file. However we could also reset everything to be like the last commit.&lt;/p&gt;

&lt;h3&gt;Reset&lt;/h3&gt;

&lt;p&gt;In order to reset our branch to be like the last commit we can (unsurprisingly) use &lt;code&gt;git reset&lt;/code&gt;. First you need the hash of the commit you want to return to. Use &lt;code&gt;git log&lt;/code&gt; and select the first 6-9 characters of the hash of the top commit in the log. For example my output is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;commit dd1f49b24a190c2c28e42a361e7e8ddaa697aab4
Author: Eliot Jones &amp;lt;elioty@hotmail.co.uk&amp;gt;
Date:   Tue Feb 9 19:00:33 2016 +0000

    css changes

commit 14eff26985b984143cadf32f1a3bd111f7f6c7e2
Author: Eliot Jones &amp;lt;elioty@hotmail.co.uk&amp;gt;
Date:   Tue Feb 9 18:38:32 2016 +0000

    our first commit
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Your commit hashes will be different, select the first part of the top one. In my case the text I want is "dd1f49b". Next we can use a hard reset to get our branch looking like it was at the time of that commit:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git reset --hard dd1f49b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that the hard reset command is dangerous and you could lose work, it's generally better to use &lt;code&gt;git checkout -- &amp;lt;file&amp;gt;&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Now if we type &lt;code&gt;git status&lt;/code&gt; we can see that we have no changes in our branch.&lt;/p&gt;

&lt;h3&gt;Recap&lt;/h3&gt;

&lt;p&gt;So far we've:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Created our repository&lt;/li&gt;
&lt;li&gt;Made our first commit on master branch&lt;/li&gt;
&lt;li&gt;Branched from master to css-changes&lt;/li&gt;
&lt;li&gt;Made another commit on the css-changes branch&lt;/li&gt;
&lt;li&gt;Discarded some unwanted changes on the css-changes branch by rolling back to a previous commit&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we illustrate commits with circles and branches with lines, then our current branches and commits look like this:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/branch-diagram.png" alt="We have 2 branches with 2 commits, only 1 commit on master" /&gt;&lt;/p&gt;

&lt;p&gt;The beauty of Git is we can go back to master branch and interact with our code as it looked before we made the commit to change the site css in our css-changes branch. To do this we don't even need to do a hard reset. Use the command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git checkout master
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This change your active branch and set your active view of the repository back to how the code looked in the master branch. &lt;/p&gt;

&lt;p&gt;&lt;details&gt;
    &lt;summary&gt;
        Where are the files in the css-changes branch?
    &lt;/summary&gt;
    &lt;p&gt;One of the things which differs in Git to other version control systems is that there's only ever a single version of a file on disk at a given time. Git doesn't store branches in separate folders, everything is stored in Git's database. This means that branching is an incredibly low cost operation, you can make many branches with no real memory or performance issues.
    &lt;/p&gt;
&lt;/details&gt;&lt;/p&gt;

&lt;h3&gt;Merge&lt;/h3&gt;

&lt;p&gt;Now we've verified we're happy with the code in our css-changes branch it's time to merge it into master. Generally you want to reserve master for completed "shippable" code. This means you merge into master when a commit (or series of commits) is ready to be used/deployed/released. &lt;/p&gt;

&lt;p&gt;Given our current active branch is master all we have to do to complete the merge is enter the command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git merge css-changes
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now one last time let's type &lt;code&gt;git log&lt;/code&gt; to see our commit history:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/git/git-merge.png" alt="When in master merge the css changes branch in" /&gt;&lt;/p&gt;

&lt;p&gt;After the merge the changes from our css-changes branch have been brought into master. Effectively we've copied the commit from css-changes to master. We still have the css-changes branch, you can verify this using &lt;code&gt;git branch -a&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The merge operation &lt;code&gt;git merge &amp;lt;branch&amp;gt;&lt;/code&gt; will transfer any commits with different hashes from the branch passed as the argument to the currently active branch.&lt;/p&gt;

&lt;h3&gt;Wrapping Up&lt;/h3&gt;

&lt;p&gt;That concludes this post. In the next post we'll take a look at working with remotes, using GitHub as our example and also rebasing, merge-conflicts and more. &lt;/p&gt;

&lt;p&gt;Feel free to point out any terrible errors or missing information in the comments.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2016/2/git-for-beginners</guid>
      <pubDate>Mon, 08 Feb 2016 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Fixie Data Driven tests</title>
      <link>https://eliot-jones.com/2016/2/fixie-data-driven-tests</link>
      <description>

&lt;p&gt;I tend to spend all my coding time nowadays plagued with guilt. I try to be a good developer and refactor the code, after running the tests, after writing the code, after running the tests, after writing the tests. But in the interests of getting any code written at all, I end up skipping between one and all of these steps (generally not the writing code part).&lt;/p&gt;

&lt;p&gt;If this sounds like you, I cannot recommend &lt;a href="http://fixie.github.io/" title="Fixie homepage"&gt;Fixie&lt;/a&gt; strongly enough. &lt;/p&gt;

&lt;p&gt;It's a low ceremony test framework that presents the minimum possible barrier to entry for the guilt driven tester/developer.&lt;/p&gt;

&lt;h3&gt;Positives&lt;/h3&gt;

&lt;p&gt;Fixie is so nice for a few reasons. Firstly it's self contained. After installing from NuGet, the Visual Studio test runner for Fixie is already set up.&lt;/p&gt;

&lt;p&gt;This means you don't have to locate the correct package for your Visual Studio version. If you're lazy like me then you'll appreciate this time-saver. &lt;/p&gt;

&lt;p&gt;To install from the package manager console use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Install-Package Fixie
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or search "fixie" on the NuGet package manager.&lt;/p&gt;

&lt;p&gt;The next point in its favour is your tests are just code. While MSTest and to some extent NUnit are an alphabetti spaghetti of attributes which challenge you to remember the difference between your &lt;code&gt;[TestFixture]&lt;/code&gt; and &lt;code&gt;[TestClass]&lt;/code&gt; attributes, Fixie requires no attributes to start working.&lt;/p&gt;

&lt;p&gt;By default any &lt;code&gt;public void&lt;/code&gt; or &lt;code&gt;public async Task&lt;/code&gt; method is detected as a test as long as the parent class name ends with "Tests". Test set-up and tear-down are handled by constructors and &lt;code&gt;IDisposable&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;An example test:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class OrderDateTests : IDisposable
{
    private readonly DateTime frozenDate;

    public OrderDateTests()
    {
        frozenDate = new DateTime(2016, 02, 04);
        SystemTime.Freeze(frozenDate);
    }

    public void OrderDateCannotBeInFuture()
    {
        try
        {
            var order = new OrderDate(frozenDate.AddDays(7));
        }
        catch (OrderDateException)
        {
            // Could run assertion here if desired
        }
    }

    public void OrderDateCanBeCurrentDate()
    {
        var order = new OrderDate(frozenDate);

        // Assert.Equal(frozenDate, order.Date);
    }

    public void Dispose()
    {
        SystemTime.UnFreeze();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This uses the constructor to freeze the SystemTime (class not shown) in order to test the constructor of the class OrderDate (also not shown). OrderDate uses &lt;code&gt;SystemTime.Now&lt;/code&gt; internally.&lt;/p&gt;

&lt;p&gt;After each test Fixie will take care of unfreezing the system time based on the logic in &lt;code&gt;Dispose()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As you can see from the example, the test methods are about as clean as it's possible to get without not having tests. Your test class doesn't even need to reference Fixie, it's a blissful escape from the moral burden of writing tests because it's just writing code.&lt;/p&gt;

&lt;p&gt;Another plus point is the massive array of configuration options if the defaults don't suit you. I have only skimmed the surface but there are full details in the &lt;a href="http://fixie.github.io/docs/" title="Fixie documentation"&gt;documentation&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Undecided Points&lt;/h3&gt;

&lt;p&gt;At the time of writing Fixie doesn't run tests in parallel by default. For some use cases this is positive (e.g. integration tests) but some people may miss the parallel speed boost (not that I've found parallelism to ever deliver a speed boost).&lt;/p&gt;

&lt;p&gt;You may also find yourself hunting around for the &lt;code&gt;Assert.Equal()&lt;/code&gt; classes  and methods you're used to from other test frameworks. Fixie doesn't include assertions because the library authors believe that the choice of assertion library is unrelated to the test framework. &lt;/p&gt;

&lt;p&gt;After initially being bewildered by this I now simply install &lt;a href="https://www.nuget.org/packages/Shouldly/" title="NuGet Shouldly download"&gt;Shouldly&lt;/a&gt;, and feel like the exclusion of assertions is a Good Thing (TM); but your mileage may vary.&lt;/p&gt;

&lt;h3&gt;Extending It&lt;/h3&gt;

&lt;p&gt;This is where it transpires this entire post is an advertorial. &lt;/p&gt;

&lt;p&gt;Currently Fixie doesn't have support for data driven tests out of the box. It's easy enough to set up and the documentation details it well but it's still a barrier for the lazy tester.&lt;/p&gt;

&lt;p&gt;Data driven tests are where one test method runs multiple test cases by passing parameters into that method.&lt;/p&gt;

&lt;p&gt;In an entirely artificial example let's say an OrderDate may be created 5 or more days in the future (but not between 1 to 4 days in the future).&lt;/p&gt;

&lt;p&gt;Using xUnit style &lt;code&gt;InlineData&lt;/code&gt; attributes we could test this as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[InlineData(1)]
[InlineData(2)]    
[InlineData(3)]
[InlineData(4)]
public void OrderDateCannotBeLessThan5DaysInFuture(int daysInFuture)
{
    try
    {
        var order = new OrderDate(frozenDate.AddDays(daysInFuture));
    }
    catch (OrderDateException)
    {
        // Could run some assertion here if desired
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will run 4 tests to check we cover the range we're expecting to be disallowed.&lt;/p&gt;

&lt;p&gt;Maybe we also want to prevent a future date being a Saturday. You may think we could use the same in-line data attribute approach, e.g.:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[InlineData(new DateTime(2016, 03, 9))]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However C# attributes cannot contain &lt;code&gt;DateTime&lt;/code&gt; or &lt;code&gt;decimal&lt;/code&gt; data. This is due to Common Language Runtime (CLR) &lt;a href="http://stackoverflow.com/a/507533/1775471" title="StackOverflow answer detailing primitive type attribute restrictions"&gt;restrictions on how attributes are  stored in the compiled code&lt;/a&gt;. This means we can't use our &lt;code&gt;InlineData&lt;/code&gt; attribute for tests where the data isn't a primitive CLR type.&lt;/p&gt;

&lt;p&gt;Fortunately xUnit provides the &lt;code&gt;MemberData&lt;/code&gt; attribute for just this occasion. This attribute looks for a static method, property or field on a class based on the name of the member. &lt;/p&gt;

&lt;p&gt;For our not-on-Saturdays test this might work as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// The member used to provide test data
public static IEnumerable&amp;lt;object[]&amp;gt; SaturdayDates
{
    get
    {
        return new[]
        {
            new object[] {new DateTime(2016, 03, 5)},
            new object[] {new DateTime(2016, 03, 9)},
            new object[] {new DateTime(2016, 07, 9)}
        };
    }
}

// The test
[MemberData("SaturdayDates")]
public void OrderDateCannotBeOnSaturdays(DateTime saturdayDate)
{
    try
    {
        var order = new OrderDate(saturdayDate);
    }
    catch (OrderDateException)
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Take my word for it that the Saturday dates in the property are all actually on Saturday.&lt;/p&gt;

&lt;p&gt;This example will run 3 tests from the single test method to verify that a set of different Saturdays throws. You'd probably choose better edge cases, far into the future or closer to the SystemTime date, to check against.&lt;/p&gt;

&lt;p&gt;I've carefully made a point of saying these are xUnit attributes, but luckily for you, dear reader, some kind soul has created the equivalent attributes in a &lt;a href="https://www.nuget.org/packages/UglyToad.Fixie.DataDriven/" title="NuGet Fixie.DataDriven download"&gt;handy NuGet package&lt;/a&gt; for Fixie.&lt;/p&gt;

&lt;p&gt;To install from the package manager console use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Install-Package UglyToad.Fixie.DataDriven
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or searching "fixie" in the NuGet package manager should return it.&lt;/p&gt;

&lt;p&gt;Once it's installed you need to define a custom Fixie convention in order to use the attributes. This convention class can live anywhere in your test project. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using Fixie;
using UglyToad.Fixie.DataDriven;

public class TestConfiguration : Convention
{
    public TestConfiguration()
    {
        Classes.NameEndsWith("Tests");

        Methods.Where(method =&amp;gt; method.IsVoid());

        Parameters
            .Add&amp;lt;ProvideTestDataFromInlineData&amp;gt;()
            .Add&amp;lt;ProvideTestDataFromMemberData&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then the attributes are available in your test project and will be detected by the test runner. The attributes are in the namespace &lt;code&gt;UglyToad.Fixie.DataDriven&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Have fun redeeming your immortal programming soul with some tests!&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2016/2/fixie-data-driven-tests</guid>
      <pubDate>Thu, 04 Feb 2016 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Automated web UI testing using Selenium with Python</title>
      <link>https://eliot-jones.com/2015/11/selenium-behave-python</link>
      <description>

&lt;p&gt;Legacy applications are a fact of life in software development. However well a piece of software starts and no matter how much care is taken to document it, as people leave and new people are assigned to look after it, knowledge about what the software does or how it's meant to work is lost.&lt;/p&gt;

&lt;p&gt;For older code which was written before a time of TDD and testable architecture this creates a fear of change, both for a developer and for the business. Testing is time consuming and manual and the knowledge of what the expected inputs and outputs of the application are, are lost and changed as ownership of the application changes hands.&lt;/p&gt;

&lt;p&gt;In his book &lt;a href="http://www.amazon.co.uk/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052"&gt;Working Effectively with Legacy Code&lt;/a&gt; Michael Feathers outlines steps which can be taken inside the code to refactor it and start adding test coverage. Depending on the size of the codebase and the budgetary and time constraints it can be difficult to get very far with refactoring the codebase itself.&lt;/p&gt;

&lt;h2&gt;A useful tool&lt;/h2&gt;

&lt;p&gt;While automated tests should also be used for new software they can be just as, if not more, useful when it comes to legacy software. For example, the UI of a legacy application tends to be much more fixed than for a project currently undergoing development.&lt;/p&gt;

&lt;p&gt;Automated UI tests for a web application can provide a useful time-saver and allow you to quickly cover the application with regression tests at a higher level. &lt;/p&gt;

&lt;p&gt;One of the most popular tools for automated UI testing is &lt;a href="http://www.seleniumhq.org/"&gt;Selenium&lt;/a&gt;. Selenium offers support for a range of languages, including .NET, Java, Ruby, etc. With Selenium you can quickly script interaction with different browsers, primarily Firefox but there are also drivers available for Internet Explorer, Google Chrome and Phantom.&lt;/p&gt;

&lt;h2&gt;A natural fit&lt;/h2&gt;

&lt;p&gt;While the concept of Business Driven Development (BDD) is orthogonal to automation testing, the two work well together. &lt;/p&gt;

&lt;p&gt;Even though BDD is about more than just a diferent way of coding, the Gherkin style Given, When, Then syntax is a good fit for UI tests. Since these Gherkin requirements often represent the outcome the user is expecting to see when they use the application they tend to align more naturally with UI testing.&lt;/p&gt;

&lt;p&gt;As an example of a business requirement written in the Gherkin style (I may have my Given and When the wrong way round in terms of the meaning of the steps):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Given a user requests access
When I am administrating the system
Then I can deny the access request
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Using it&lt;/h2&gt;

&lt;p&gt;I've been playing around with the Python &lt;a href="http://pythonhosted.org/behave/index.html"&gt;behave&lt;/a&gt; library and the Selenium bindings for Python. While I've written Selenium tests in .NET before this seems like overkill for what is effectively scripting a test suite. Python as a language seems a nicer, more lightweight, fit for Selenium with BDD and it ticks those nice open source boxes.&lt;/p&gt;

&lt;p&gt;Since early project set-up can be an issue for adopting a UI testing approach I decided to make a &lt;a href="https://github.com/EliotJones/behave-selenium-template"&gt;reusable project template&lt;/a&gt; which can be used and extended for building UI tests. The nice thing about this project is as long as you have Python (3.5+) and a web browser on your system you can download it and have it running almost instantly.&lt;/p&gt;

&lt;p&gt;This means you can start developing your features and steps without having to write any set-up code.&lt;/p&gt;

&lt;p&gt;The project comes with one feature containing two demo scenarios:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Feature: Load Wikipedia home

Scenario: Load it
    Given I am not logged in
    When I am on the homepage
    Then I should see the English option

Scenario: Search Cats
    Given I am on the homepage
    When I search cats
    Then I should go to the cats page  
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All the plumbing responsible for changing browsers in the configuration and easily accessing your own additional configuration settings from code is taken care of.&lt;/p&gt;

&lt;p&gt;As a result you can just write your features and steps without worrying about anything else. Here are the steps (except the "I am on the homepage" step which is in the shared steps) for the above feature:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import behave
from selenium import webdriver
from helpers import configuration
from selenium.webdriver.common.keys import Keys

@given("I am not logged in")
def step_impl(context):
    pass

@then('I should see the English option')
def step_impl(context):
    link = context.browser.find_element_by_link_text("English")
    assert True is True

@when("I search cats")
def step_impl(context):
    search = context.browser.find_element_by_id("searchInput")
    search.send_keys("cats")
    search.submit()

@then("I should go to the cats page")
def step_impl(context):
    title = context.browser.find_element_by_tag_name("h1")
    assert "Cat" in title.text 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The project also offers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Support for Internet Explorer, Chrome and Firefox&lt;/li&gt;
&lt;li&gt;Screenshots on test failure&lt;/li&gt;
&lt;li&gt;Configurable deletion of cookies to take place after Steps, Scenarios, Features or the entire test run&lt;/li&gt;
&lt;li&gt;A single script to install all dependencies and create a isolated Virtual Environment to avoid polluting your global installation&lt;/li&gt;
&lt;li&gt;Reporting of tests results in the JUnit format.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you don't want to use Git you can just download the project as a zip and use it as the base for your development. Thanks to the install script it's also easy to integrate with Jenkins.&lt;/p&gt;

&lt;p&gt;The best documentation for using the Selenium driver with Python is &lt;a href="http://selenium-python.readthedocs.org/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Go &lt;a href="https://github.com/EliotJones/behave-selenium-template"&gt;give it a go&lt;/a&gt; and let me know how it goes :)&lt;/p&gt;

&lt;p&gt;I'm hoping to extend it with support for Phantom as well as more utility functions for quickly selecting from a dropdown, etc.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/11/selenium-behave-python</guid>
      <pubDate>Sun, 29 Nov 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>PostHaste</title>
      <link>https://eliot-jones.com/2015/10/posthaste</link>
      <description>

&lt;p&gt;I haven't blogged in a while, simply because I've not thought of any interesting topics to blog about, hopefully something will come along sooner or later!&lt;/p&gt;

&lt;p&gt;In the meantime I'm promoting my little Visual Studio extension, &lt;a href="https://visualstudiogallery.msdn.microsoft.com/f3ccaa45-c306-44bd-b435-495132d3383f"&gt;PostHaste&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This extension aims to make sending code to &lt;a href="http://hastebin.com/"&gt;hastebin&lt;/a&gt; (it's like a good version of PasteBin) from inside Visual Studio easier. Not that it could be much easier but it seemed like a fun way to learn Visual Studio extensibility.&lt;/p&gt;

&lt;p&gt;It's (hopefully) compatible with Visual Studio 2013 and 2015, why not give it a try? :)&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/posthaste/screenshot.png" alt="A screenshot of PostHaste in action." /&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/10/posthaste</guid>
      <pubDate>Tue, 13 Oct 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>MVC postback for users without JavaScript - Post 2</title>
      <link>https://eliot-jones.com/2015/6/mvc-postback-2</link>
      <description>

&lt;p&gt;Posts in this series:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/2015/06/mvc-postback" title="The first post in the series"&gt;Post 1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Post 2&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So far we have created a form which performs a postback to the server to add more input fields to the same page. We have encountered an issue with MVC seeming to cache partial views (or at least the values inside them).&lt;/p&gt;

&lt;h3&gt;Step 4&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-4/EliotJones.PostbackTutorial" title="The code for the fourth step on GitHub"&gt;Step 4&lt;/a&gt; attempts to fix the caching of the selected value field.&lt;/p&gt;

&lt;p&gt;I spent hours looking for a way to stop MVC caching partial views, which is what I thought was happening. I tried disabling the output cache and loading the partial views via actions, neither of which helped. I finally found &lt;a href="http://stackoverflow.com/questions/7414351/mvc-3-html-editorfor-seems-to-cache-old-values-after-ajax-call/7449628#7449628" title="How to stop MVC caching values in partial views"&gt;this answer&lt;/a&gt; on StackOverflow; the ModelState holds the old values when a view is reloaded via an HTTP POST even if you change the values of the model in the action.&lt;/p&gt;

&lt;p&gt;By removing the specific value from the ModelState the value clears properly and the view displays as expected.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private ActionResult AddPostback(OrderViewModel model)
{
    ModelState.Remove("SelectedMenuItem");
    model.SelectedMenuItem = null;

    return View("Order", model);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The form now works as expected, the "add another" button adds another input to the page by reloading the page, the submit button still submits the form to the server and redirects to the summary screen. Now we have the screen working for users without JavaScript however users get a "screen flicker" due to reloading the page when clicking "Add another".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://eliot-jones.com/images/postback/screen-flicker.gif" title="A gif showing the screen flicker the user sees when the page posts back"&gt;See this image&lt;/a&gt; for an example of the screen flicker non-JavaScript users will see, this seems like an acceptable compromise, since there's no way to prevent the page having to reload for these users. However for people with JavaScript enabled it would be nice to offer a cleaner user experience.&lt;/p&gt;

&lt;h3&gt;Step 5&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-5/EliotJones.PostbackTutorial" title="The code for the last step on GitHub"&gt;This step&lt;/a&gt; mainly focuses on using jQuery Ajax to submit the form in a user friendly way. I originally started using the Microsoft Ajax &lt;code&gt;@Ajax.Helper()&lt;/code&gt; methods but it turned out to be easier to just write the JavaScript in this case.&lt;/p&gt;

&lt;p&gt;The first main change is that the body of the form now lives in a new partial view (_OrderPartial) which contains the Current and Previous input partial views:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model EliotJones.PostbackTutorial.ViewModels.Menu.OrderViewModel

@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.Partial("_Previous", Model)
@Html.Partial("_Current", Model, ViewData)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The button for "Add another" in the &lt;code&gt;_Current&lt;/code&gt; partial view now calls a JavaScript function using the onclick attribute:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;button type="submit" name="submit" value="add" onclick="addMore(event);"&amp;gt;
    &amp;lt;span class="glyphicon glyphicon-plus"&amp;gt;&amp;lt;/span&amp;gt;
    Add another
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that we pass &lt;code&gt;event&lt;/code&gt; to the onclick attribute, this is required for the code to work on Firefox.&lt;/p&gt;

&lt;p&gt;The code for this JavaScript function is in the Order view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model EliotJones.PostbackTutorial.ViewModels.Menu.OrderViewModel
&amp;lt;h2&amp;gt;Order&amp;lt;/h2&amp;gt;
&amp;lt;hr/&amp;gt;

@using (Html.BeginForm("Order", "Menu", FormMethod.Post, htmlAttributes: new { id = "form" }))
{
    &amp;lt;div id="form-for-ajax"&amp;gt;
        @Html.Partial("_OrderPartial", Model)
    &amp;lt;/div&amp;gt;
    &amp;lt;button type="submit" name="submit" value="submit"&amp;gt;
        Submit
    &amp;lt;/button&amp;gt;
}

@section scripts{
    &amp;lt;script&amp;gt;
        function addMore(event) {
            // The code goes here
        }
    &amp;lt;/script&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code uses the jQuery Ajax post function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function addMore(event) {
    $.post('@Url.Action("Order", new { submit = "add" })', $('#form').serialize())
        .done(function (data) {
            $('#form-for-ajax').html(data);
        }).fail(function () {
            return true;
        });

    event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first parameter of the call to &lt;code&gt;$.post()&lt;/code&gt; is a the URL to post to for this request. I've used the Razor helpers here to avoid hard-coding the entire URL. Since the value of &lt;code&gt;submit&lt;/code&gt; will no longer come from the button we add it as a QueryString parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$.post('@Url.Action("Order", new { submit = "add" })',
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The single quotes ensure the URL helper value is a string in the JavaScript, miss them out at your peril.&lt;/p&gt;

&lt;p&gt;The next argument to &lt;code&gt;$.post()&lt;/code&gt; is the data to submit to the URL, this uses jQuery's Serialize to send the form data in the format required.&lt;/p&gt;

&lt;p&gt;After a call to &lt;code&gt;$.post(url, data)&lt;/code&gt; the code will continue to the next line, this is not the line you think it might be. Because the post runs asynchronously the next line which runs is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;event.preventDefault ? event.preventDefault() : event.returnValue = false;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This stops the browser submitting the form on click of the submit button in a similar way to &lt;code&gt;return false;&lt;/code&gt;. This means for users with JavaScript this button will instead call an Ajax request whereas for users without the form will still submit (because none of this JavaScript code will run).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;done&lt;/code&gt; function does not run immediately because it is a "promise", which means it executes asynchronously. When the Ajax request completes successfully the code in &lt;code&gt;done&lt;/code&gt; will run, alternatively if there's an error then &lt;code&gt;fail&lt;/code&gt; will run.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$.post(url, submittedData)
    .done(function (data) {
        $('#form-for-ajax').html(data);
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The data passed to the function in &lt;code&gt;done&lt;/code&gt; is the data returned by the request, in our case this is HTML, so we can just replace the content of the form with the returned data (using &lt;code&gt;.html()&lt;/code&gt;) since the postback just returns the form with the extra input fields.&lt;/p&gt;

&lt;p&gt;The problem now is that the controller code currently returns the entire form including layout again so we end up with nested forms:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/postback/nested-screens.png" alt="The postback inserts everything including the page header into the form region." /&gt;&lt;/p&gt;

&lt;h3&gt;Returning partial views when required&lt;/h3&gt;

&lt;p&gt;Luckily for us MVC 5 offers a convenience method for detecting Ajax requests:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (Request.IsAjaxRequest())
{
    return PartialView("_OrderPartial", model);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This looks for the &lt;code&gt;X-Requested-With: XMLHttpRequest&lt;/code&gt; header used by jQuery Ajax requests (&lt;a href="http://stackoverflow.com/questions/17478731/whats-the-point-of-x-requested-with-header/22533680#22533680" title="The reason the X-Requested-With header is sent with Ajax requests"&gt;mainly for security reasons, e.g. CSRF&lt;/a&gt;) and can be used to return the partial view for these JavaScript requests. This check is added in two places. &lt;a href="https://github.com/EliotJones/PostbackTutorial/blob/step-5/EliotJones.PostbackTutorial/Controllers/MenuController.cs" title="The code for the final Menu controller on GitHub"&gt;See the full code&lt;/a&gt; for the finished Menu controller.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Order(OrderViewModel model, string submit)
{
    if (model.SelectedMenuItem.HasValue)
    {
        model.SelectedItems.Add(model.SelectedMenuItem.Value);
    }

    BindSelectLists(model);

    if (!ModelState.IsValid || string.IsNullOrWhiteSpace(submit))
    {
        if (Request.IsAjaxRequest())
        {
            return PartialView("_OrderPartial", model);
        }
        return View(model);
    }

    switch (submit)
    {
        case AddValue:
            return AddPostback(model);
        default:
            return SubmitPostback(model);
    }
}

private ActionResult AddPostback(OrderViewModel model)
{
    ModelState.Remove("SelectedMenuItem");

    model.SelectedMenuItem = null;
    if (Request.IsAjaxRequest())
    {
        return PartialView("_OrderPartial", model);
    }
    return View("Order", model);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Summary&lt;/h3&gt;

&lt;p&gt;In summary:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create the form and controller action with one submit button.&lt;/li&gt;
&lt;li&gt;Add another submit button with a name and a different value.&lt;/li&gt;
&lt;li&gt;You can use a parameter to the controller action with the name of the button to check the value of where the submit came from.&lt;/li&gt;
&lt;li&gt;Return the correct ActionResult for your desired action, watching out for caching in the ModelState.&lt;/li&gt;
&lt;li&gt;Add an Ajax request to the onclick of the submit button which calls the same controller action but returns partial views instead.&lt;/li&gt;
&lt;/ol&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/6/mvc-postback-2</guid>
      <pubDate>Sun, 21 Jun 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>MVC postback for users without JavaScript - Post 1</title>
      <link>https://eliot-jones.com/2015/6/mvc-postback</link>
      <description>

&lt;p&gt;Posts in this series:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Post 1&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/2015/06/mvc-postback-2" title="Second post in this series"&gt;Post 2&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Despite only around 1.2% of users having JavaScript disabled there is still a requirement to develop sites which work for users who have JavaScript turned off, especially sites which provide government services. The UK's Government Digital Services (GDS) require that a site works without JavaScript and is then enhanced using JavaScript. This causes all sorts of problems designing forms, especially where there is an "Add more" option for input fields.&lt;/p&gt;

&lt;p&gt;Designing something like an "Add more" functionality with JavaScript is fairly trivial, having it work for those without is less so. Having encountered this problem several times I've written a summary of the approach I have used to address this.&lt;/p&gt;

&lt;h3&gt;The code&lt;/h3&gt;

&lt;p&gt;All the code for this tutorial is available on &lt;a href="https://github.com/EliotJones/PostbackTutorial" title="All code for these tutorials on GitHub"&gt;GitHub&lt;/a&gt;. I have used Git's branches to take snapshots of development changes. The final code is in the branch &lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-5/EliotJones.PostbackTutorial" title="The code for the last step on GitHub"&gt;"step-5"&lt;/a&gt;. Additonally I have hosted the website on Azure so you can see what the final page does &lt;a href="http://postbacktest.azurewebsites.net/" title="The product hosted on Azure"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;The product&lt;/h3&gt;

&lt;p&gt;We are designing a page to allow users to choose items from a menu, once they have selected as many items as they want, they submit the form and are taken to a summary of their active orders:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/postback/final-screen.png" alt="The screen features dropdowns containing menu items and an add another button allowing the user to add more input dropdowns" /&gt;&lt;/p&gt;

&lt;h3&gt;Getting started&lt;/h3&gt;

&lt;p&gt;The postback concept is from ASP.NET Webforms and there's no real parallel in MVC, which is a good thing because the postback model encouraged ignorance of a site working with HTTP in a stateless manner. However it is still possible to create a postback style model in MVC.&lt;/p&gt;

&lt;p&gt;We start with a simple almost empty MVC web application project with a Home controller and a Menu controller:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class MenuController : Controller
{
    [HttpGet]
    public ActionResult Order()
    {
        return View();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There's also a Meal model in the Models folder:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Meal
{
    public int Id { get; set; }

    public decimal Price { get; set; }

    public string Name { get; set; }

    public int NumberRemaining { get; set; }

    public decimal TimeToServe { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And a class called Menu which provides a list of different meals and the ability to order them.&lt;/p&gt;

&lt;h3&gt;Step 1&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-1/EliotJones.PostbackTutorial" title="The code for the first step on GitHub"&gt;The first step&lt;/a&gt; is to create a form to allow the user to select one meal and post to the server. We use a ViewModel for data binding to our view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class OrderViewModel
{
    public SelectList MenuItems { get; set; }

    [Required(ErrorMessage = "Please select a menu item.")]
    public int? SelectedMenuItem { get; set; }

    public IList&amp;lt;int&amp;gt; SelectedItems { get; set; }

    public OrderViewModel()
    {
        this.SelectedItems = new List&amp;lt;int&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This has a corresponding Get and Post action on the [controller] and the following view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@{
    ViewBag.Title = "Order";
}

&amp;lt;h2&amp;gt;Order&amp;lt;/h2&amp;gt;

@using (Html.BeginForm())
{
    @Html.ValidationSummary()

    &amp;lt;div class="form-group"&amp;gt;
        @Html.LabelFor(m =&amp;gt; m.SelectedMenuItem, "Select a menu item")
        @Html.ValidationMessageFor(m =&amp;gt; m.SelectedMenuItem)
        @Html.DropDownListFor(m =&amp;gt; m.SelectedMenuItem, Model.MenuItems, "Please select", new {@class = "form-control"})
    &amp;lt;/div&amp;gt;
    &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Currently this view has one submit button which posts the entire form.&lt;/p&gt;

&lt;h3&gt;Step 2&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-2/EliotJones.PostbackTutorial" title="The code for the second step on GitHub"&gt;The next step&lt;/a&gt; adds a second submit button to the view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div class="form-group"&amp;gt;
    @Html.LabelFor(m =&amp;gt; m.SelectedMenuItem, "Select a menu item", new { @class = "dropdown-label" })
    @Html.ValidationMessageFor(m =&amp;gt; m.SelectedMenuItem)
    @Html.DropDownListFor(m =&amp;gt; m.SelectedMenuItem, Model.MenuItems, "Please select", new {@class = "form-control dropdown"})
    &amp;lt;button type="submit" name="submit" value="add"&amp;gt;&amp;lt;span class="glyphicon glyphicon-plus"&amp;gt;&amp;lt;/span&amp;gt;Add another&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;button type="submit" name="submit" value="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Both buttons now have a name attribute (submit) and different value attributes, "add" and "submit" respectively.&lt;/p&gt;

&lt;p&gt;We can now detect which of the two buttons have been clicked in the controller action and do different things for either button. Currently our controller submits the form for both buttons.&lt;/p&gt;

&lt;h3&gt;Step 3&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-3/EliotJones.PostbackTutorial" title="The code for the third step on GitHub"&gt;Next&lt;/a&gt; we set the controller to treat a post sent using the add button differently to one sent using submit:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[HttpPost]
public ActionResult Order(OrderViewModel model, string submit)
{
    if (model.SelectedMenuItem.HasValue)
    {
        model.SelectedItems.Add(model.SelectedMenuItem.Value);
    }

    BindSelectLists(model);

    if (!ModelState.IsValid || string.IsNullOrWhiteSpace(submit))
    {
        return View(model);
    }

    switch (submit)
    {
        case AddValue:
            return AddPostback(model);
        default:
            return SubmitPostback(model);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The controller action takes a string parameter with the same name as the submit buttons, the value of this will either be "add" or "submit", the values we set for the buttons in our HTML.&lt;/p&gt;

&lt;p&gt;The action first adds the currently selected item to the list of previously selected items if present. After checking that the ModelState is valid (i.e. that there is a currently selected item) it chooses one of two methods to call depending on the button pressed. There is a method for the add post and the submit post.    &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ActionResult AddPostback(OrderViewModel model)
{
    model.SelectedMenuItem = null;

    return View("Order", model);
}

public ActionResult SubmitPostback(OrderViewModel model)
{
    foreach (var id in model.SelectedItems)
    {
        Meal meal = Menu.Single(m =&amp;gt; m.Id == id);

        Menu.Order(meal);
    }

    return RedirectToAction("Summary");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
&lt;li&gt;Add: Sets the currently selected item to null and returns the view.&lt;/li&gt;
&lt;li&gt;Submit: Orders the items and moves to the summary screen.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It's important to note that this approach goes against the way the MVC framework is designed, &lt;a href="http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx" title="An MSDN blog post explaining how rendering views on POST is different"&gt;by design&lt;/a&gt; MVC treats the return of a view (rather than a redirect) from an HTTP POST as being due to Validation errors.&lt;/p&gt;

&lt;p&gt;In this step there have been some changes to the view to provide &lt;a href="https://github.com/EliotJones/PostbackTutorial/tree/step-3/EliotJones.PostbackTutorial/Views/Menu" title="The code for the menu view on GitHub"&gt;partial views&lt;/a&gt; showing the current selection input and previously selected items.&lt;/p&gt;

&lt;p&gt;Currently we have a problem, when we click "Add another" and the page performs a postback, the current input still loads with the previous value selected. Even though we set the selected value to null in the &lt;code&gt;AddPostback&lt;/code&gt; method and it loads in the view as null it's not resetting in the view. Somehow MVC has cached the value for this dropdown.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/postback/cache-problem.png" alt="The current dropdown has the same value as the previous." /&gt;&lt;/p&gt;

&lt;p&gt;We will address this problem in the &lt;a href="http://eliot-jones.com/2015/06/mvc-postback-2" title="Second post in this series"&gt;next post&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/6/mvc-postback</guid>
      <pubDate>Sat, 20 Jun 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Core CLR and System.Xml</title>
      <link>https://eliot-jones.com/2015/6/asp-vnext-system-xml</link>
      <description>

&lt;p&gt;If you need to use some package which is dependent on System.Xml with Core CLR / DNX Core you simply add the Nuget package &lt;code&gt;System.Xml.XmlDocument&lt;/code&gt; rather than referencing the GAC System.Xml. &lt;/p&gt;

&lt;p&gt;This allows you to keep your code in Core CLR friendly mode.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/system-xml/system-xml.png" alt="System.Xml.XmlDocument on NuGet" /&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/6/asp-vnext-system-xml</guid>
      <pubDate>Tue, 09 Jun 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Visual Studio 2015 and Gulp</title>
      <link>https://eliot-jones.com/2015/6/visual-studio-2015-gulp</link>
      <description>

&lt;p&gt;Having played around with the Visual Studio 2015 preview a bit I've tried to learn how Gulp integrates with the Web Application project.&lt;/p&gt;

&lt;p&gt;Gulp seems like one of those many, many, constantly appearing JavaScript libraries with names like YamahaPotplantSaucepan.js which are impossible to keep up with. However since it takes the place of the Bundle config it's important to be able to achieve a basic level of familiarity with it.&lt;/p&gt;

&lt;h3&gt;What does it do?&lt;/h3&gt;

&lt;p&gt;Gulp describes itself as a "&lt;em&gt;streaming build system&lt;/em&gt;" which basically means you can wire up a pipeline of operations to perform on your content, such as JavaScript and CSS.&lt;/p&gt;

&lt;p&gt;By default the project template comes with a gulpfile (shown in the image as #1). This is configured to take the dependencies from Bower (which is a package manager loading a few jQuery packages in by default) and copy them to the &lt;code&gt;wwwroot/lib&lt;/code&gt; folder (#3 in the image).&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/gulp/Project-Layout.png" alt="1 is gulpfile.js, 2 is package.json, 3 is wwwroot folder, 4 is dependencies folder" /&gt;&lt;/p&gt;

&lt;p&gt;The Bower packages are listed in the bower.json file.&lt;/p&gt;

&lt;p&gt;The standard gulpfile looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;binding Clean='clean' /&amp;gt;

var gulp = require("gulp"),
        rimraf = require("rimraf"),
        fs = require("fs");


eval("var project = " + fs.readFileSync("./project.json"));

var paths = {
    bower: "./bower_components/",
    lib: "./" + project.webroot + "/lib/"
};

gulp.task("clean", function (cb) {
    rimraf(paths.lib, cb);
});

gulp.task("copy", ["clean"], function () {
    var bower = {
        "bootstrap": "bootstrap/dist/**/*.{js,map,css,ttf,svg,woff,eot}",
        "bootstrap-touch-carousel": "bootstrap-touch-carousel/dist/**/*.{js,css}",
        "hammer.js": "hammer.js/hammer*.{js,map}",
        "jquery": "jquery/jquery*.{js,map}",
        "jquery-validation": "jquery-validation/jquery.validate.js",
        "jquery-validation-unobtrusive": "jquery-validation-unobtrusive/jquery.validate.unobtrusive.js",
        "jquery-ui": "jquery-ui/*.{js,map}"
    }

    for (var destinationDir in bower) {
        gulp.src(paths.bower + bower[destinationDir])
          .pipe(gulp.dest(paths.lib + destinationDir));
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This script defines 2 Gulp tasks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;clean&lt;/strong&gt; - uses a force clean to delete everything in the &lt;code&gt;wwwroot/lib&lt;/code&gt; folder (rimraf is a npm package which recursively force deletes all files in the target folder, equivalent to the &lt;code&gt;rm -rf&lt;/code&gt; command).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;copy&lt;/strong&gt; - runs a clean first and then copies the scripts from their Bower package location to the &lt;code&gt;wwwroot/lib/NAME&lt;/code&gt; folder, where NAME is the left hand of the &lt;code&gt;bower&lt;/code&gt; json object.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;How do I run it?&lt;/h3&gt;

&lt;p&gt;The Gulp tasks can be run manually from the Task Runner Explorer (if you can't see it go to &lt;code&gt;Views &amp;gt; Other Windows &amp;gt; Task Runner Explorer&lt;/code&gt;). The result of running the copy task is shown below:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/gulp/Task-Runner.png" alt="Output of the task runner" /&gt;&lt;/p&gt;

&lt;p&gt;The left hand side has the 2 tasks listed, clean and copy. Right click a task and click "Run" to run it. Tasks can also be bound to some defined bindings, for example you may want to copy on every build:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/gulp/Task-Runner-Binding.png" alt="Right click the task and select bindings, then the binding you want" /&gt;&lt;/p&gt;

&lt;h3&gt;How do I modify it?&lt;/h3&gt;

&lt;p&gt;In order to use our own files with Gulp we need to modify the Gulp task or write a new one. There are good guides on &lt;a href="http://www.smashingmagazine.com/2014/06/11/building-with-gulp/"&gt;using Gulp to build a pipeline&lt;/a&gt;. This blog post isn't one of them.&lt;/p&gt;

&lt;p&gt;We have a folder we use to write all our custom Javascript in, for this tutorial this is in &lt;code&gt;ProjectRoot/Scripts&lt;/code&gt;. First we can define this path as a JavaScript variable, I stole space in the pre-defined &lt;code&gt;paths&lt;/code&gt; object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var paths = {
    bower: "./bower_components/",
    lib: "./" + project.webroot + "/lib/",
    scripts: "./Scripts/"
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;.&lt;/code&gt; is the project root.&lt;/p&gt;

&lt;p&gt;Since I don't want to be running multiple tasks where I only need one I'm going to put my code in the &lt;strong&gt;copy&lt;/strong&gt; task:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gulp.task("copy", ["clean"], function () {
    var bower = {
        "bootstrap": "bootstrap/dist/**/*.{js,map,css,ttf,svg,woff,eot}",
        // The rest of the bower paths
    }

    for (var destinationDir in bower) {
        gulp.src(paths.bower + bower[destinationDir])
          .pipe(gulp.dest(paths.lib + destinationDir));
    }

    // Copy all project scripts into the lib folder.
    gulp.src(paths.scripts + '**.js')
        .pipe(gulp.dest(paths.lib));
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This takes all my scripts from the source (&lt;code&gt;./Scripts&lt;/code&gt; folder), it then pipes them into the destination operation which writes them into the &lt;code&gt;./wwwroot/lib&lt;/code&gt; folder. &lt;/p&gt;

&lt;p&gt;Note - if the scripts don't show up, look at the lib folder in the Windows File Explorer; Visual Studio sometimes doesn't show the copied Gulp files.&lt;/p&gt;

&lt;p&gt;Now we'd like to minify these files, luckily for us we can add a step to our streaming operation.&lt;/p&gt;

&lt;p&gt;First we need a component to do the minification. We'll use the node package &lt;code&gt;gulp-uglify&lt;/code&gt; to do this. To install this package open the &lt;code&gt;Package.json&lt;/code&gt; folder (#2 from the first picture). Put a line in there to reference the uglify package:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  "name": "ASP.NET",
  "version": "0.0.0",
  "devDependencies": {
    "gulp": "3.8.11",
    "rimraf": "2.2.8",
    "gulp-uglify": "1.2.0"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will cause the node package manager to automatically restore these dependencies. We can now use this in our gulpfile. Modify the top of the gulpfile to include the uglify component:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var gulp = require("gulp"),
        rimraf = require("rimraf"),
        fs = require("fs"),
        uglify = require("gulp-uglify");
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally you can change the custom code in the &lt;strong&gt;copy&lt;/strong&gt; task to add an Uglify step to the pipeline:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Copy all project scripts into the lib folder.
gulp.src(paths.scripts + '**.js')
    .pipe(uglify())
    .pipe(gulp.dest(paths.lib));
&lt;/code&gt;&lt;/pre&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/6/visual-studio-2015-gulp</guid>
      <pubDate>Wed, 03 Jun 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>SpecFlow looking for When instead of Given step</title>
      <link>https://eliot-jones.com/2015/5/specflow-when-instead-of-given</link>
      <description>

&lt;p&gt;When writing some automation tests using Selenium with SpecFlow recently I was faced with an odd error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    No matching step definition found for the step. Use the following code to create one:
    [When(@"I add a new dog")]
    public void WhenIAddANewDog()
    {
        ScenarioContext.Current.Pending();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The suggested code was using a &lt;code&gt;[When("My Scenario")]&lt;/code&gt; step despite the feature file declaring it as a &lt;code&gt;Given&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Scenario: Check for existing dog
    Given I have a new Dog Controller
    And I add a new dog
    When I check if the added dog exists
    Then The check is true
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(This feature is written badly to illustrate the error).&lt;/p&gt;

&lt;p&gt;The step it couldn't find was the &lt;code&gt;And I add a new dog&lt;/code&gt; step. Despite showing as bound in the feature file and being able to navigate to the step definition, the running test couldn't find it and was looking for a &lt;code&gt;When&lt;/code&gt; instead of a &lt;code&gt;Given&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is because the previous step was calling sub steps as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class DogControllerSteps : Steps
{
    [Given("I have a new Dog Controller")]
    public void CreateDogController()
    {
        Given("I have a new query bus");

        When("I create a new dog controller");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Inheriting from &lt;code&gt;Steps&lt;/code&gt; allows us to reuse step definitions from the same or other step files.&lt;/p&gt;

&lt;p&gt;When SpecFlow runs this it knows that it last ran a &lt;code&gt;When&lt;/code&gt; step, despite being in the definition of a &lt;code&gt;Given&lt;/code&gt;. Therefore when the next step is defined with &lt;code&gt;And&lt;/code&gt;, it looks for a &lt;code&gt;When&lt;/code&gt;. To fix this you can simply change your feature to be more specific:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Scenario: Check for existing dog
    Given I have a new Dog Controller
    Given I add a new dog
    When I check if the added dog exists
    Then The check is true
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Passing tests :)&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/5/specflow-when-instead-of-given</guid>
      <pubDate>Wed, 20 May 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>3-tier CQRS using Web API as a command/query bus</title>
      <link>https://eliot-jones.com/2015/5/cqrs-web-api</link>
      <description>

&lt;p&gt;We recently started using CQRS on a project to provide a new web application to manage a complicated permit process. The CQRS pattern combined with a proper domain model seemed like a good fit for the business logic.&lt;/p&gt;

&lt;p&gt;Midway through development of our 2 tier solution (Web &amp;lt;-&gt; Database) we were asked to instead asked to develop a 3 tier solution (Web &amp;lt;-&gt; Api &amp;lt;-&gt; Database) to avoid exposing the database to the web server (no WCF allowed).&lt;/p&gt;

&lt;p&gt;Initially the change slowed development and resulted in an explosion in the Lines of Code to functionality ratio. After some thinking we realised it might be possible to use Web API as a command/query bus for our pre-existing CQRS setup, effectively allowing us to "pass-through" the API without needing to write a controller action per command.&lt;/p&gt;

&lt;p&gt;This post summarises the ideas behind the working approach we developed. All the code used in this post can be found &lt;a href="https://github.com/EliotJones/MediAPIr"&gt;on Github&lt;/a&gt; but the code is very obviously simplified; both to avoid revealing implementation specific details such as security and to allow this post to focus on the concepts.&lt;/p&gt;

&lt;h3&gt;CQRS&lt;/h3&gt;

&lt;p&gt;If you're not familiar with CQRS &lt;a href="http://martinfowler.com/bliki/CQRS.html"&gt;read some of the articles&lt;/a&gt; available on the advantages and disadvantages of the pattern. Basically you separate commands (actions which update data) from queries (which read data).&lt;/p&gt;

&lt;p&gt;This post will only deal with implementing the query side of CQRS over Web API. Commands should be simpler.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Query&lt;/code&gt; and &lt;code&gt;QueryHandler&lt;/code&gt; interfaces are defined in a separate CQRS class library (ideally Queries and Query handlers live in separate libraries because your web project shouldn't have to reference query handlers).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface IQuery&amp;lt;TReturn&amp;gt;
{
}

public interface IQueryHandler&amp;lt;TQuery, TReturn&amp;gt; where TQuery : IQuery&amp;lt;TReturn&amp;gt;
{
    Task&amp;lt;TReturn&amp;gt; Send(TQuery query);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;All aboard the query bus&lt;/h3&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/cqrs-api/bus.jpg" alt="Picture of a bus" /&gt;&lt;/p&gt;

&lt;p&gt;We generally want to use our bus as a mediator so we don't have to specifically tie queries and handlers together. The idealised implementation is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;TQueryResult result = await queryBus.SendAsync(new Query());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The bus should find and call the correct handler for the query and return the result. In this implementation the Web API controller action replaces the bus.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class QueryController : ApiController
{
    private readonly IServiceLocator serviceLocator;

    public QueryController()
    {
        serviceLocator = new NaiveLocator();
    }

    public async Task&amp;lt;object&amp;gt; Send(QueryRequest query)
    {
        // TODO: Implement the quey bus, find the right handler for the query.
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I haven't wired up a dependency injection container in this example so created a very simple service locator (anti-pattern!):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;internal interface IServiceLocator
{
    object Resolve(Type serviceType);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The implementation of this locator takes the type of &lt;code&gt;QueryHandler&lt;/code&gt; to find and returns that handler. In a real example this could be replaced with a dependency injection container's resolve method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;internal class NaiveLocator : IServiceLocator
{
    private readonly Dictionary&amp;lt;Type, object&amp;gt; services; 

    public NaiveLocator()
    {
        this.services = new Dictionary&amp;lt;Type, object&amp;gt;();

        services.Add(typeof(IQueryHandler&amp;lt;GetAllRappers, Rapper[]&amp;gt;), new GetAllRappersHandler(new Data()));
        services.Add(typeof(IQueryHandler&amp;lt;GetRapperByName, Rapper&amp;gt;), new GetRapperByNameHandler(new Data()));
    }

    public object Resolve(Type serviceType)
    {
        return services[serviceType];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Getting on the bus&lt;/h3&gt;

&lt;p&gt;Because we are sending our queries as HTTP requests to our API the queries have to be serialized somehow and all generic type parameter information is lost.&lt;/p&gt;

&lt;p&gt;One approach is to wrap the query as Json in a parent Json object which also contains type information:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class QueryRequest
{
    public string QueryTypeName { get; set; }

    public string QueryData { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When the website sends the request it has to generate this object (this method is in &lt;code&gt;ApiClient&lt;/code&gt; in the Api.Client project):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public async Task&amp;lt;TResult&amp;gt; Send&amp;lt;TQuery, TResult&amp;gt;(TQuery query) where TQuery : IQuery&amp;lt;TResult&amp;gt;
{
    var request = new QueryRequest
    {
        QueryData = JsonConvert.SerializeObject(query),
        QueryTypeName = typeof(TQuery).AssemblyQualifiedName
    };

    var response = await client.PostAsJsonAsync("api/Query/Send", request);

    return await response.Content.ReadAsAsync&amp;lt;TResult&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's important to use the &lt;code&gt;AssemblyQualifiedName&lt;/code&gt; rather than &lt;code&gt;FullName&lt;/code&gt; or just &lt;code&gt;Name&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;The wheels on the bus&lt;/h3&gt;

&lt;p&gt;When our QueryRequest object arrives the API knows nothing about it. The first thing to do is work out what the query is and what we're expected to return. In our API controller we construct an object representing what we know about the request:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var typeInformation = new QueryRequestTypeInformation(query);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The constructor for &lt;code&gt;QueryRequestTypeInformation&lt;/code&gt; looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;internal class QueryRequestTypeInformation
{
    public Type QueryType { get; private set; }

    public Type ResultType { get; private set; }

    public QueryRequestTypeInformation(QueryRequest query)
    {
        this.QueryType = Type.GetType(query.QueryTypeName);
        this.ResultType = this.QueryType.GetInterfaces().Single(i =&amp;gt; i.Name.Contains("IQuery")).GetGenericArguments()[0];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This object will now contain information about the query type and the result type.&lt;/p&gt;

&lt;p&gt;We can then use this to work out the type of handler we need our Service Locator to locate (in the API controller):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var queryObject = JsonConvert.DeserializeObject(query.QueryData, typeInformation.QueryType);

var handlerType = typeof(IQueryHandler&amp;lt;,&amp;gt;).MakeGenericType(typeInformation.QueryType, typeInformation.ResultType);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Jonas Gauffin's &lt;a href="https://github.com/jgauffin/dotnetcqs/blob/master/src/DotNetCqs.Autofac/ContainerQueryBus.cs"&gt;CQS library&lt;/a&gt; provided the inspiration for much of the controller code. &lt;/p&gt;

&lt;p&gt;Given we now have the type of the handler we need, we can request it from our service locator (yes, I'm trying to mention the name of that particular anti-pattern enough times to drive home the point that this isn't the best code, but it works):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var handler = serviceLocator.Resolve(handlerType);
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;A moment of reflection&lt;/h3&gt;

&lt;p&gt;The rest of the code uses reflection heavily, of course there are performance penalties associated with the use of reflection. So far this seems negligible compared to the time for 2 web request/responses (client -&gt; web -&gt; api -&gt; web -&gt; client) and the data access time.&lt;/p&gt;

&lt;p&gt;To call the right handler for our query and return an object the API controller then does this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var sendMethodInfo = handlerType.GetMethod("Send");

return await (dynamic)sendMethodInfo.Invoke(handler, new[] { queryObject });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I wasn't aware that dynamics could be awaited in this manner until reading a comment from Stephen Cleary on my &lt;a href="http://stackoverflow.com/questions/30176781/implication-of-calling-result-on-awaited-task"&gt;Stack Overflow question on the topic&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The full API controller code then looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public async Task&amp;lt;object&amp;gt; Send(QueryRequest query)
{
    var typeInformation = new QueryRequestTypeInformation(query);

    var queryObject = JsonConvert.DeserializeObject(query.QueryData, typeInformation.QueryType);

    var handlerType = typeof(IQueryHandler&amp;lt;,&amp;gt;).MakeGenericType(typeInformation.QueryType, typeInformation.ResultType);

    var handler = serviceLocator.Resolve(handlerType);

    var sendMethodInfo = handlerType.GetMethod("Send");

    return await (dynamic)sendMethodInfo.Invoke(handler, new[] { queryObject });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Summary&lt;/h3&gt;

&lt;p&gt;As mentioned in the introduction this is not a complete sample and should not be used in production! For a start there's no security at all between the API and web layer. Additionally there's no error handling anywhere.&lt;/p&gt;

&lt;p&gt;This post outlines a possible approach to a generic endpoint for a Web API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/EliotJones/MediAPIr"&gt;Full code with working sample&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;bus: https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/ICCE_Fist_Student_Wallkill_bus.JPG/640px-ICCE_Fist_Student_Wallkill_bus.JPG&lt;/em&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/5/cqrs-web-api</guid>
      <pubDate>Sat, 16 May 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Fun with Nuget</title>
      <link>https://eliot-jones.com/2015/4/nuget-tutorial</link>
      <description>

&lt;p&gt;I recently finished the first release of &lt;a href="https://www.nuget.org/packages/UglyToad.DataTable/"&gt;my 2nd Nuget package&lt;/a&gt; which provides a class to convert an ADO.Net DataTable to a list of objects. This is the result of an effort to create a library for the conversion technique outlined in &lt;a href="http://eliot-jones.com/2014/07/dataset-to-poco"&gt;this post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I've also created a Nuget package to help out with MVC 5 Radio Buttons located &lt;a href="https://www.nuget.org/packages/EliotJones.RadioButtons/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This post summarises some things I learned from creating these Nuget packages.&lt;/p&gt;

&lt;h3&gt;Simplest package&lt;/h3&gt;

&lt;p&gt;For simply packing a class library targeting a single version of the .Net framework you can simply invoke the Nuget.exe with the path to the .csproj:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.\.nuget\NuGet.exe pack .\Path\To\Project.csproj -Prop Configuration=Release
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If your solution doesn't have a copy of the Nuget exe in the .nuget solution folder you can &lt;a href="https://nuget.codeplex.com/releases/view/58939"&gt;download the exe separately&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This command will create the nuget package in the current directory with the metadata declared in the AssemblyInfo.cs for the project.&lt;/p&gt;

&lt;h3&gt;Creating a specification&lt;/h3&gt;

&lt;p&gt;The default nuspec specification file created by calling:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Nuget.exe spec
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Is fairly self explanatory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version="1.0"?&amp;gt;
&amp;lt;package &amp;gt;
  &amp;lt;metadata&amp;gt;
    &amp;lt;id&amp;gt;Package&amp;lt;/id&amp;gt;
    &amp;lt;version&amp;gt;1.0.0&amp;lt;/version&amp;gt;
    &amp;lt;authors&amp;gt;Eliot&amp;lt;/authors&amp;gt;
    &amp;lt;owners&amp;gt;Eliot&amp;lt;/owners&amp;gt;
    &amp;lt;licenseUrl&amp;gt;http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE&amp;lt;/licenseUrl&amp;gt;
    &amp;lt;projectUrl&amp;gt;http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE&amp;lt;/projectUrl&amp;gt;
    &amp;lt;iconUrl&amp;gt;http://ICON_URL_HERE_OR_DELETE_THIS_LINE&amp;lt;/iconUrl&amp;gt;
    &amp;lt;requireLicenseAcceptance&amp;gt;false&amp;lt;/requireLicenseAcceptance&amp;gt;
    &amp;lt;description&amp;gt;Package description&amp;lt;/description&amp;gt;
    &amp;lt;releaseNotes&amp;gt;Summary of changes made in this release of the package.&amp;lt;/releaseNotes&amp;gt;
    &amp;lt;copyright&amp;gt;Copyright 2015&amp;lt;/copyright&amp;gt;
    &amp;lt;tags&amp;gt;Tag1 Tag2&amp;lt;/tags&amp;gt;
    &amp;lt;dependencies&amp;gt;
      &amp;lt;dependency id="SampleDependency" version="1.0" /&amp;gt;
    &amp;lt;/dependencies&amp;gt;
  &amp;lt;/metadata&amp;gt;
&amp;lt;/package&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you have several dlls which target different versions of the .Net framework (for example) you can declare the mapping of files to the package contents like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version="1.0"?&amp;gt;
&amp;lt;package &amp;gt;
  &amp;lt;metadata&amp;gt;
    &amp;lt;id&amp;gt;Package&amp;lt;/id&amp;gt;
    &amp;lt;version&amp;gt;1.0.0&amp;lt;/version&amp;gt;
    &amp;lt;authors&amp;gt;Eliot&amp;lt;/authors&amp;gt;
    &amp;lt;owners&amp;gt;Eliot&amp;lt;/owners&amp;gt;
    &amp;lt;licenseUrl&amp;gt;http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE&amp;lt;/licenseUrl&amp;gt;
    &amp;lt;projectUrl&amp;gt;http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE&amp;lt;/projectUrl&amp;gt;
    &amp;lt;iconUrl&amp;gt;http://ICON_URL_HERE_OR_DELETE_THIS_LINE&amp;lt;/iconUrl&amp;gt;
    &amp;lt;requireLicenseAcceptance&amp;gt;false&amp;lt;/requireLicenseAcceptance&amp;gt;
    &amp;lt;description&amp;gt;Package description&amp;lt;/description&amp;gt;
    &amp;lt;releaseNotes&amp;gt;Summary of changes made in this release of the package.&amp;lt;/releaseNotes&amp;gt;
    &amp;lt;copyright&amp;gt;Copyright 2015&amp;lt;/copyright&amp;gt;
    &amp;lt;tags&amp;gt;Tag1 Tag2&amp;lt;/tags&amp;gt;
    &amp;lt;dependencies&amp;gt;
      &amp;lt;dependency id="SampleDependency" version="1.0" /&amp;gt;
    &amp;lt;/dependencies&amp;gt;
  &amp;lt;/metadata&amp;gt;
    &amp;lt;files&amp;gt;
        &amp;lt;file src="Project\bin\Release\Project.dll" target="lib\net45"/&amp;gt;
        &amp;lt;file src="Project\bin\Release\Project.dll" target="lib\net40"/&amp;gt;
    &amp;lt;/files&amp;gt;
&amp;lt;/package&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Additionally content you want to install into the user's project on installation of your package can be declared in the files area:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;files&amp;gt;
    &amp;lt;file src="..\MvcProject\Views\Shared\EditorTemplates\*.cshtml" target="Content\Views\Shared\EditorTemplates\"/&amp;gt;
    &amp;lt;file src="..\OtherProject\bin\Release\OtherProject.dll" target="lib\net45"/&amp;gt;
&amp;lt;/files&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Targeting multiple versions of the .Net framework&lt;/h3&gt;

&lt;p&gt;One thing I wanted to do with the DataTable converter project was allow users of .Net 3.5, 4.0 and 4.5 to install and use the converter. Assuming you have a project currently targeting .Net 4.5 that you want to provide compatible versions of for other frameworks you can create a new project with the correct Target Framework, e.g. &lt;code&gt;My.Project&lt;/code&gt; and &lt;code&gt;My.Project.Net35&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To avoid having multiple versions of the same code you can then add the code from your main version of the library as linked files.&lt;/p&gt;

&lt;p&gt;For example with the following project and new Net 3.5 version:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/nuget-tutorial/SolutionExplorer.png" alt="Solution explorer with .Net 4.5 and .Net 3.5 versions" /&gt;&lt;/p&gt;

&lt;p&gt;You can add the classes already defined by right clicking the project and choosing &lt;code&gt;Add -&amp;gt; Existing Item&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/nuget-tutorial/AddExisting.png" alt="Add existing item to .Net 3.5 solution" /&gt;&lt;/p&gt;

&lt;p&gt;Select the files from your main project and then before clicking "Add", use the arrow to the right of the button to Add as link:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/nuget-tutorial/AddAsLink.png" alt="The add as link arrow is where the &amp;quot;Add&amp;quot; button is, to the right" /&gt;&lt;/p&gt;

&lt;p&gt;Edits to the linked file will also change the files in the main project so if you need to make changes for compatibility you'll have to create a copy of those files.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/4/nuget-tutorial</guid>
      <pubDate>Tue, 14 Apr 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Entity Framework 6 Enums with String column</title>
      <link>https://eliot-jones.com/2015/3/entity-framework-enum</link>
      <description>

&lt;p&gt;I recently watched Jimmy Bogard's &lt;a href="https://vimeo.com/43598193" title="Jimmy Bogard - Crafting Wicked Domain Models at Norwegian Developers Conference"&gt;excellent NDC presentation on Domain models&lt;/a&gt; to learn about how to implement a real world domain model.&lt;/p&gt;

&lt;p&gt;One of the things Jimmy does in his presentation is to refactor his enum to use a base class allowing far more expressive enums with custom behaviour&lt;/p&gt;

&lt;p&gt;There are a few versions of this custom enum base class around but I'm going to be using &lt;a href="https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/" title="Jimmy Bogard - Custom Enumeration Class"&gt;this one&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Annoyingly Entity Framework (EF) doesn't support mapping database fields to enums &lt;a href="https://msdn.microsoft.com/en-gb/data/hh859576.aspx" title="Enum support in EF5+"&gt;unless you use an int column in your database&lt;/a&gt;. This might be good enough for your implementation however it seems a bit fragile to couple your database to a mystery int defined in code somewhere which could be changed by any user who doesn't realise what they're changing.&lt;/p&gt;

&lt;p&gt;For a marginally less fragile and more domain model friendly enum I used an adapted version of Jimmy's enumeration class:&lt;/p&gt;

&lt;p&gt;The main change is to the &lt;code&gt;DisplayName&lt;/code&gt; property. We add a setter because Entity Framework is only going to bring back the string display name and we need to map to the underlying value field to get the proper enum.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public string DisplayName
{
    get
    {
        return this.displayName;
    }

    // Entity Framework will only retrieve and set the display name.
    // Use this setter to find the corresponding value as defined in the static fields.
    protected set
    {
        this.displayName = value;

        // Get the static fields on the inheriting type.
        foreach (var field in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
        {
            // If the static field is an Enumeration type.
            var enumeration = field.GetValue(this) as Enumeration;
            if (enumeration == null)
            {
                continue;
            }

            // Set the value of this instance to the value of the corresponding static type.
            if (string.Compare(enumeration.DisplayName, value, true) == 0)
            {
                this.value = enumeration.Value;
                break;
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This simply checks the static fields on the instance of the enumeration class and finds the enumeration with the matching name.&lt;/p&gt;

&lt;p&gt;We also change the private &lt;code&gt;displayName&lt;/code&gt; and &lt;code&gt;value&lt;/code&gt; fields to remove the readonly access modifier (and the underscores because I've never been able to adapt to the convention):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private int value;
private string displayName; 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I also overrode the &lt;code&gt;==&lt;/code&gt; reference equals check to make our enumeration class behaves more like a value type:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Override reference equals to provide a value equals since the type is (almost) immutable.
public static bool operator ==(Enumeration a, Enumeration b)
{
    if (object.ReferenceEquals(a, b))
    {
        return true;
    }

    if ((object)a == null || (object)b == null)
    {
        return false;
    }

    var typeMatches = a.GetType().Equals(b.GetType());
    var valueMatches = a.Value.Equals(b.Value);

    return typeMatches &amp;amp;&amp;amp; valueMatches;
}

public static bool operator !=(Enumeration a, Enumeration b)
{
    return !(a == b);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We need an additional step for our model configuration. Imagine we're storing a record of our prized Bonsai tree collection:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class BonsaiTree
{
    public int Id { get; protected set; }

    public string Name { get; protected set; }

    public Genus Genus { get; protected set; }
}

public class Genus : Enumeration
{
    public static readonly Genus Leafy = new Genus(0, "Leafy");

    public static readonly Genus Twiggy = new Genus(1, "Twiggy");

    private Genus() { }

    private Genus(int value, string displayName) : base(value, displayName) { }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where Bonsai tree is our EF entity. We need to tell EF that Genus is a complex type so it will map it to the same table. Additionally we need to ignore the value which we are not storing (if you needed to you could by extending this approach). Finally we need to configure the correct column name for the DisplayName of Genus:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class EnumTestContext : DbContext
{
    public DbSet&amp;lt;BonsaiTree&amp;gt; BonsaiTrees { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.ComplexType&amp;lt;Genus&amp;gt;().Ignore(bt =&amp;gt; bt.Value);
        modelBuilder.Types&amp;lt;BonsaiTree&amp;gt;().Configure(t =&amp;gt; t.Property(bt =&amp;gt; bt.Genus.DisplayName).HasColumnName("Genus"));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I've only used this approach with Code First against an existing database so I'm not sure the migrations would handle it properly and I haven't tested it extensively however in a quick test it seemed to work well. Also the more derived Enum types for proper logic separation as detailed in the &lt;a href="https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/" title="Jimmy Bogard - Custom Enumeration Class"&gt;end of this post&lt;/a&gt; won't work because of how EF handles (or rather doesn't handle) inheritance in its mapping.&lt;/p&gt;

&lt;p&gt;The full code is &lt;a href="http://eliot-jones.com/Code/ef-enum/EnumTest.cs" title="Code file for samples in this post"&gt;here&lt;/a&gt;; sorry about half the namespace disappearing, I was trying desperately to get PHP to stop displaying the Byte Order Mark and instead succeeded in getting it to eat the code.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/3/entity-framework-enum</guid>
      <pubDate>Mon, 23 Mar 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>FakeItEasy Heisenbugs</title>
      <link>https://eliot-jones.com/2015/3/fakeiteasy-tests-randomly-failing</link>
      <description>

&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; the problem has been solved in version 2.0.0 of FakeItEasy.&lt;/p&gt;

&lt;p&gt;I was recently facing an issue where my FakeItEasy tests were sometimes randomly failing. I'm specifying that it was the FakeItEasy tests because I managed to isolate to the failures to 2 tests which were using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var thing = A.Fake&amp;lt;IInterface&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The FakeItEasy fake would sometimes ignore the specified setup, such as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;A.CallTo(() =&amp;gt; thing.Method()).Returns(true);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The fake would return false or null for reference types.&lt;/p&gt;

&lt;p&gt;Analysing the stack trace on the failing test it was due to aggregate Exceptions occurring when running the tests in parallel. There is an &lt;a href="https://github.com/FakeItEasy/FakeItEasy/issues/60" title="GitHub issue for parallel tests"&gt;issue describing this here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We were using xUnit as our testing framework which runs tests in parallel by default. Unfortunately both FakeItEasy and Moq aren't threadsafe and this introduces bugs when tests are run in parallel. It seems like other testing frameworks also experience the same problem.&lt;/p&gt;

&lt;p&gt;To get around this we &lt;a href="https://github.com/xunit/xunit/issues/244"&gt;disabled parallel test execution in xUnit&lt;/a&gt;. This means our tests take longer but are reliable.&lt;/p&gt;

&lt;p&gt;If you've run into this issue before and found a better fix I'd be intrigued to hear it.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/3/fakeiteasy-tests-randomly-failing</guid>
      <pubDate>Tue, 17 Mar 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Dependency Injection Containers - Cheat Sheet</title>
      <link>https://eliot-jones.com/2015/2/dependency-injection-library-syntax</link>
      <description>

&lt;p&gt;There are a lot of articles out there that describe both Dependency Injection and &lt;a href="http://stackoverflow.com/questions/3058/what-is-inversion-of-control" title="StackOverflow Question Discussing Definition of Inversion of Control"&gt;Inversion of Control&lt;/a&gt;. The purpose of this one is to serve as a quick reference for the things I keep forgetting because configuring a DI container is something I do so infrequently. This is a very simple guide showing the easiest scenarios and the simplest syntax.  It walks through the same 3 steps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;1. Create Container
2. Configure Container
3. Retrieve from Container
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the following DI libraries:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Ninject&lt;/li&gt;
&lt;li&gt;Unity&lt;/li&gt;
&lt;li&gt;SimpleInjector&lt;/li&gt;
&lt;li&gt;StructureMap&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Of course it will feature examples tenuously related to animals.&lt;/p&gt;

&lt;h3&gt;Principals&lt;/h3&gt;

&lt;p&gt;A Dependency Injection library makes dependency injection easier by doing the work of wiring up an "object graph" (collection of related objects) for your application to use. This is generally done at the entry point to an application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For console apps this is in the main method of &lt;code&gt;Program.cs&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For MVC and Web API apps this is in &lt;code&gt;Startup.cs&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;For class libraries it is difficult to include dependency injection in the library itself as these have no defined entry point. One approach is to rely on the calling application to wire up the dependencies.&lt;/li&gt;
&lt;li&gt;For WebForms apps &lt;a href="http://stackoverflow.com/questions/8947423/webforms-and-dependency-injection" title="StackOverflow Question On How To Use DI with ASP.NET Webforms"&gt;it is possible&lt;/a&gt; to setup the DI container in the &lt;code&gt;Global.asax&lt;/code&gt; Application_Start method however it's a bit more complicated.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Console App Example&lt;/h3&gt;

&lt;p&gt;In this example we're going to begin building a console app which simulates an ecosystem of toads.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/ioc/toad.jpg" alt="picture of a toad" /&gt;&lt;/p&gt;

&lt;p&gt;The main logic of our simulation will run in the ToadSimulator Class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ToadSimulator
{
    private readonly ILogger logger;
    private readonly SimulationSettingsProvider settingsProvider;
    private ICollection&amp;lt;Toad&amp;gt; simulationToads;

    public ToadSimulator(ILogger logger, SimulationSettingsProvider settingsProvider)
    {
        this.logger = logger;
        this.settingsProvider = settingsProvider;
    }

    public void InitialiseSimulation()
    {
        simulationToads = settingsProvider.RetrieveSimulationToads();

        logger.LogMessage(string.Format("ToadSimulator - Retrieved {0} toads to start the simulation.", 
                            simulationToads.Count));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is written to allow constructor injection of both the logger and the class which provides the settings for the simulation.&lt;/p&gt;

&lt;p&gt;The settings provider also has a dependency on a logger:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class SimulationSettingsProvider
{
    private readonly ILogger logger;

    public SimulationSettingsProvider(ILogger logger)
    {
        this.logger = logger;
    }

    internal virtual ICollection&amp;lt;Toad&amp;gt; RetrieveSimulationToads()
    {
        logger.LogMessage("SimulationSettingsProvider - Retrieving Toads.");

        return Database.RetrieveToads();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We also provide an implementation of the logger interface:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public interface ILogger
{
    void LogMessage(string message);
}

public class ConsoleLogger : ILogger
{
    private string logBuffer;

    public ConsoleLogger()
    {
        logBuffer = string.Format("Logger (Id = {0}):", this.GetHashCode());
    }

    public void LogMessage(string message)
    {
        logBuffer += Environment.NewLine + message;

        Console.WriteLine(logBuffer);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The console logger contains a per instance string so we can see exactly where the logger is getting called from and this will help us to understand the difference between object scopes later. It also records its hashcode (uniquely identifying integer) as an extra tool to understand object scope.&lt;/p&gt;

&lt;p&gt;Finally all this gets invoked from the main method of the program:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main(string[] args)
{
    ToadSimulator toadSimulator = new ToadSimulator(new ConsoleLogger(), 
        new SimulationSettingsProvider(new ConsoleLogger()));

    toadSimulator.InitialiseSimulation();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Apart from the code in the main method the rest of the classes will not change from now on.&lt;/p&gt;

&lt;p&gt;Even with this very simple example we can see that manually creating the dependencies to inject through the code is going to become a lot of work.&lt;/p&gt;

&lt;p&gt;This is why we turn to a dependency injection library.&lt;/p&gt;

&lt;h3&gt;Resolve Using Ninject&lt;/h3&gt;

&lt;p&gt;Ninject can be added to a project through NuGet.:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/ioc/ninject.png" alt="installing ninject from NuGet" /&gt;&lt;/p&gt;

&lt;p&gt;Ninject uses a &lt;strong&gt;kernel&lt;/strong&gt; to store its dependencies, we create one of these in our main method as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IKernel kernel = new StandardKernel();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We now need to bind our logger interface to an implementation. This is done in the configuration of our container. It's useful to have a separate method in another class to configure our container:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;internal class Bootstrapper
{
    public static void ConfigureContainer(IKernel kernel)
    {
        kernel.Bind&amp;lt;ILogger&amp;gt;().To&amp;lt;ConsoleLogger&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once we have resolved the interface we get the kernel to provide us the class we need in our application by using the &lt;code&gt;Get&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main(string[] args)
{
    IKernel kernel = new StandardKernel(); // Create Container

    Bootstrapper.ConfigureContainer(kernel); // Configure Container

    ToadSimulator toadSimulator = kernel.Get&amp;lt;ToadSimulator&amp;gt;(); // Retrieve from Container

    toadSimulator.InitialiseSimulation();

    Console.ReadKey();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The output of this shows us that like in the original version, without the container, the logger is instantiated twice (the hashcodes differ):&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/ioc/consoleoutput1.png" alt="the two loggers have different hashcodes" /&gt;&lt;/p&gt;

&lt;h3&gt;Scope Using Ninject&lt;/h3&gt;

&lt;p&gt;We can change to scope of our logger as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;kernel.Bind&amp;lt;ILogger&amp;gt;().To&amp;lt;ConsoleLogger&amp;gt;().InTransientScope();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the default scope of Ninject bindings and is the same as leaving the &lt;code&gt;InTransientScope&lt;/code&gt; off. An alternative scope is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;kernel.Bind&amp;lt;ILogger&amp;gt;().To&amp;lt;ConsoleLogger&amp;gt;().InSingletonScope();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the output showing the logger is a singleton:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/ioc/consoleoutput2.png" alt="both logs have the same hashcode" /&gt;&lt;/p&gt;

&lt;h3&gt;Convention Binding Using Ninject&lt;/h3&gt;

&lt;p&gt;Where we have lots of interfaces or abstract classes to bind, the binding code can quickly become repetitive. Instead we can use convention based configuration. To do this in Ninject we need to add another reference from NuGet. Install the &lt;code&gt;ninject.extensions.conventions&lt;/code&gt; package. The kernel can now be bound using lambda expressions.&lt;/p&gt;

&lt;p&gt;This example binds interfaces to their only implementing class, obviously this won't work where there are multiple interface implementations:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;kernel.Bind(configure =&amp;gt; configure.FromThisAssembly()
                .SelectAllClasses().BindDefaultInterfaces());
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Using Unity&lt;/h3&gt;

&lt;p&gt;There are a huge range of DI Libraries, I'm just going to record the example above with a few other libraries, I'm getting these from NuGet. Firstly Microsoft's Unity:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main(string[] args)
{
    IUnityContainer container = new UnityContainer(); // Create Container

    Bootstrapper.ConfigureContainer(container); // Configure Container

    ToadSimulator toadSimulator = container.Resolve&amp;lt;ToadSimulator&amp;gt;(); // Retrieve from Container

    toadSimulator.InitialiseSimulation();

    Console.ReadKey();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And the Bootstrapper code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void ConfigureContainer(IUnityContainer container)
{
    container.RegisterType&amp;lt;ILogger, ConsoleLogger&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the scope changed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;container.RegisterType&amp;lt;ILogger, ConsoleLogger&amp;gt;(new ContainerControlledLifetimeManager());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Unity docs &lt;a href="https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx" title="Unity 3 Documentation"&gt;located here&lt;/a&gt; are great and go through using Unity with Convention based configuration and using Unity with WCF, Webforms and other more advanced use cases.&lt;/p&gt;

&lt;h3&gt;Using SimpleInjector&lt;/h3&gt;

&lt;p&gt;Creating a container and retrieving instances:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main(string[] args)
{
    Container container = new Container(); // Create Container

    Bootstrapper.ConfigureContainer(container); // Configure Container

    ToadSimulator toadSimulator = container.GetInstance&amp;lt;ToadSimulator&amp;gt;(); // Retrieve from Container

    toadSimulator.InitialiseSimulation();

    Console.ReadKey();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Bootstrapper code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void ConfigureContainer(Container container)
{
    container.Register&amp;lt;ILogger, ConsoleLogger&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the scope changed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;container.RegisterSingle&amp;lt;ILogger, ConsoleLogger&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The SimpleInjector docs &lt;a href="https://simpleinjector.readthedocs.org/en/2.7/quickstart.html" title="SimpleInjector Documentation"&gt;located here&lt;/a&gt; are very much improved from before and are easy to follow.&lt;/p&gt;

&lt;h3&gt;Using StructureMap&lt;/h3&gt;

&lt;p&gt;Creating a container and retrieving instances:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main(string[] args)
{
    IContainer container = Bootstrapper.ConfigureContainer(); // Configure Container

    ToadSimulator toadSimulator = container.GetInstance&amp;lt;ToadSimulator&amp;gt;(); // Retrieve from Container

    toadSimulator.InitialiseSimulation();

    Console.ReadKey();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Bootstrapper code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static IContainer ConfigureContainer()
{
    return new Container(x =&amp;gt; x.For&amp;lt;ILogger&amp;gt;().Use&amp;lt;ConsoleLogger&amp;gt;()); // Create Container
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This registers the logger as a singleton instance. For a transient scope the below code worked:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;return new Container(x =&amp;gt; x.For&amp;lt;ILogger&amp;gt;().Use&amp;lt;ConsoleLogger&amp;gt;().AlwaysUnique());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The StructureMap documentation &lt;a href="http://structuremap.github.io/" title="StructureMap Documentation"&gt;here&lt;/a&gt; is the easiest to follow.&lt;/p&gt;

&lt;h3&gt;Use with Web API and MVC&lt;/h3&gt;

&lt;p&gt;Most DI libraries provide a github package specifically tailored to setting up DI in MVC and/or Web Api. For example Unity provides the classes required to call the following method from the WebApiConfig:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    UnityWebApiActivator.Start();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Summary&lt;/h3&gt;

&lt;p&gt;This guide shows how the syntax changes between different DI libraries but the concepts remain the same. It does not provide any detail on advanced usage of DI libraries however should hopefully provide a quick start when changing between DI library syntax.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/2/dependency-injection-library-syntax</guid>
      <pubDate>Sun, 01 Feb 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>EF7 Table Mapping Exception</title>
      <link>https://eliot-jones.com/2015/1/entity-framework-7-invalid-object-name</link>
      <description>

&lt;p&gt;&lt;strong&gt;Note: This blog post relates to a library undergoing development and as such the information is likely to become outdated.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Even with Database First through the EDMX gone in Entity Framework 7 it's &lt;a href="http://cpratt.co/entity-framework-code-first-with-existing-database/" title="Chris Pratt on EF7 Code First"&gt;still possible to work with existing databases&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;While trying this out with one of my databases I ran into the following Exception:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;Message&amp;gt;An error has occurred.&amp;lt;/Message&amp;gt;

&amp;lt;ExceptionMessage&amp;gt;Invalid object name 'SomeClass'.&amp;lt;/ExceptionMessage&amp;gt;

&amp;lt;ExceptionType&amp;gt;System.Data.SqlClient.SqlException&amp;lt;/ExceptionType&amp;gt;

&amp;lt;StackTrace&amp;gt;
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)[...]
&amp;lt;/StackTrace&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Entity Framework "Invalid object name [class name]" exception means that the matching table for one of your classes hasn't been found.&lt;/p&gt;

&lt;p&gt;In this case I'm trying to map the SomeClass to the underlying SQL table &lt;code&gt;Map.Test&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Table("Test", Schema="Map")]
public class SomeClass
{
    public int Id { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The current version of EF7 (7.0.0-rc1-11953) does not have support for mapping using attributes in this way. Instead one must use Fluent configuration in the &lt;code&gt;DbContext&lt;/code&gt; as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class MyContext : DbContext
{
    public DbSet&amp;lt;SomeClass&amp;gt; SomeClasses { get; set; }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseSqlServer(ConnectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity&amp;lt;SomeClass&amp;gt;().ForRelational().Table(tableName: "Test", schemaName: "Map");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The mapping is configured fluently in the &lt;code&gt;OnModelCreating&lt;/code&gt; method. For slightly more useful information about setting EF7 up &lt;a href="https://github.com/aspnet/EntityFramework/wiki/Using-EF7-in-Traditional-.NET-Applications" title="Entity Framework 7 Github"&gt;see this link&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I hope this helps!&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2015/1/entity-framework-7-invalid-object-name</guid>
      <pubDate>Thu, 15 Jan 2015 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>C# Async for Slugs</title>
      <link>https://eliot-jones.com/2014/12/async-programming</link>
      <description>

&lt;p&gt;Fun fact for you dear reader, I've not been programming for long, my degree was in Chemistry and though I taught myself a little programming during my degree I was mainly focused on Chemistry. This means I've been programming professionally for less time than C# 5 has been released.&lt;/p&gt;

&lt;p&gt;This is why I've found tutorials so far for the Async/Await features in C# 5 (Net 4.5) to be a little lacking, they generally assume the reader has been writing async programs prior to the release of the features.&lt;/p&gt;

&lt;p&gt;As a solution to this I've endeavoured to write a guide to async for miserable slugs like myself who have not had exposure to async prior to these keywords.&lt;/p&gt;

&lt;h3&gt;Demo Scenario&lt;/h3&gt;

&lt;p&gt;We're going to stick with a very simple console app available &lt;a href="https://github.com/EliotJones/async-test/tree/VS2013Solution/AsyncTutorial"&gt;on GitHub&lt;/a&gt; to make sure all the concepts can be understood by a slug.&lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;Program.cs&lt;/code&gt; main method is shown below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static void Main(string[] args)
{   
    SlugService slugService = new SlugService();
    slugService.GetSlugs(generation: 1);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The GitHub version contains a lot more lines which allow the method calls to be timed with the built in stopwatch.&lt;/p&gt;

&lt;p&gt;The Slug Service is tasked with retrieving the records of some slugs we've stored somewhere. Let's see what it does:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public IList&amp;lt;Slug&amp;gt; GetSlugs(int generation)
{
    Int64 generationalPrime = primeFinder.FindNthPrime(50000 + generation);

    IList&amp;lt;Slug&amp;gt; slugs = slugGetter.GetDataSlugs(generation);

    foreach (var slug in slugs)
    {
        slug.FavouritePrime = generationalPrime;
    }

    return slugs;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again, the GitHub version contains more code related to timing methods with Stopwatch. This method does the following things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Gets the favourite prime for this generation of slugs. (As we all know, slugs are huge prime number fans).&lt;/li&gt;
&lt;li&gt;Get the slugs from our storage medium.&lt;/li&gt;
&lt;li&gt;Set the prime for this generation of slugs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The prime finder gets the &lt;strong&gt;nth&lt;/strong&gt; prime for any n. It's written to be quite inefficient so we can replicate some external call or large calculation that blocks the program.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public Int64 FindNthPrime(int n)
{
    if (n &amp;lt; 1) throw new ArgumentException();

    List&amp;lt;int&amp;gt; primes = new List&amp;lt;int&amp;gt; { 2 };

    bool primeFound = false;
    int index = 3;

    while (!primeFound)
    {
        if (primes.Count &amp;gt;= n)
        {
            primeFound = true;
            break;
        }

        bool currentNumberIsPrime = true;
        foreach (int prime in primes)
        {
            currentNumberIsPrime = index % prime != 0;
            if (!currentNumberIsPrime) break;
        }

        if (currentNumberIsPrime) primes.Add(index);
        index += 2;
    }

    return primes[n-1];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you don't understand the maths just ignore it, suffice to say when you call this method with an input of ~50,000 it takes around 8 seconds to return a result.&lt;/p&gt;

&lt;p&gt;Finally we need to get our slugs from our data storage. I've not actually implemented a persistence medium for this demo so the SlugGetter does this instead:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public IList&amp;lt;Slug&amp;gt; GetDataSlugs(int generation)
{
    List&amp;lt;Slug&amp;gt; slugs = new List&amp;lt;Slug&amp;gt;();

    for (int i = 0; i &amp;lt; 1000; i++)
    {
        slugs.Add(new Slug
        {
            Id = i + 1,
            Name = "Slug" + i.ToString(),
            Generation = generation,
            CabbagesEaten = (i % 2 == 0) ? 1 : 0
        });
        Thread.Sleep(5);
    }
    return slugs;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The thread sleep in this method slows everything down so the program runs on a timescale which can be easily compared between runs.&lt;/p&gt;

&lt;h3&gt;The Problem with Synchronous Execution&lt;/h3&gt;

&lt;p&gt;Running the program with the Stopwatch related lines included gives this output:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/asynctutorial/SyncRun.png" alt="9219 Milliseconds getting prime, 5663 milliseconds getting slugs, 14884 overall" /&gt;&lt;/p&gt;

&lt;p&gt;The total run time is almost entirely due to the time taken to calculate the prime and the time taken to retrieve our slugs. The rest of the program takes about 2 milliseconds to run!&lt;/p&gt;

&lt;p&gt;Unfortunately in the normal synchronous way of calling methods each method is run in turn causing our program to take a long time.&lt;/p&gt;

&lt;p&gt;To visually illustrate the call stack I created this diagram:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/asynctutorial/SyncCallStack.png" alt="The SlugService first waits 9.2 seconds for PrimeFinder then 5.7s for SlugGetter" /&gt;&lt;/p&gt;

&lt;p&gt;By boosting the hardware of our computer we might achieve a more speedy slug retrieval (through a faster primefinder) however there's a limit to scaling up in this way. We need to move execution on to other threads so we're not being blocked by the PrimeFinder.&lt;/p&gt;

&lt;h3&gt;Parallel Execution != Async&lt;/h3&gt;

&lt;p&gt;This is the first conceptual hurdle for people new to C# wanting to learn about async and await. Since all examples of async use methods which return &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; it's easy to assume &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; is related to the async features.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; and related concepts in the &lt;code&gt;System.Threading.Tasks&lt;/code&gt; namespace have actually been features of .NET since .NET 4.0. They form the core of the TPL (&lt;em&gt;Task Parallel Library&lt;/em&gt;). We can therefore rewrite our SlugService with a parallel execution mode.&lt;/p&gt;

&lt;p&gt;It would be nice if we could run the PrimeFinder on one of our cores in a worker task while the main execution ran the SlugGetter.&lt;/p&gt;

&lt;p&gt;To create a Task for our PrimeFinder we can wrap our normal method in a new Task:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public Task&amp;lt;Int64&amp;gt; FindNthPrimeTask(int n)
{
    return Task.Run(() =&amp;gt; FindNthPrime(n));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;Task.Run()&lt;/code&gt; instantiates a new Task object and starts it running, it is a slightly nicer version of the .NET 4 TPL &lt;code&gt;Task.Factory.StartNew()&lt;/code&gt; however you should use &lt;code&gt;Task.Run()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Our method call now returns a Task so in our slug service we need to change the result of the PrimeFinder call to a &lt;code&gt;Task&amp;lt;Int64&amp;gt;&lt;/code&gt; object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public IList&amp;lt;Slug&amp;gt; GetSlugsParallel(int gen)
{
    Task&amp;lt;Int64&amp;gt; generationalPrimeTask = primeFinder.FindNthPrimeTask(50000 + gen);

    IList&amp;lt;Slug&amp;gt; slugs = slugGetter.GetDataSlugs(gen);

    Int64 generationalPrime = generationalPrimeTask.Result;
    foreach (var slug in slugs)
    {
        slug.FavouritePrime = generationalPrime;
    }
    return slugs;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where we call &lt;code&gt;Task.Result&lt;/code&gt; the main thread blocks execution while waiting for the results of the Task. This means we avoid a &lt;strong&gt;Race Condition&lt;/strong&gt; where we use our prime before it has been properly calculated.&lt;/p&gt;

&lt;p&gt;We will run the synchronous single threaded &lt;code&gt;GetSlugs&lt;/code&gt; and then the &lt;code&gt;GetSlugsParallel&lt;/code&gt; method:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/asynctutorial/ParallelRun.png" alt="53 Milliseconds getting prime, 6002 milliseconds getting slugs, 8959 overall for parallel" /&gt;&lt;/p&gt;

&lt;p&gt;As the results show, the run-time was almost entirely due to the time taken to calculate the prime (53 milliseconds was spent calling and returning the task). With the prime calculation taking place on another thread we were able to reduce run time.&lt;/p&gt;

&lt;p&gt;It gets a bit harder to illustrate this call stack. First SlugService is called normally and performs a call to &lt;code&gt;PrimeFinder&lt;/code&gt; as usual. However this returns in 50 milliseconds and the main thread goes on to run the &lt;code&gt;SlugGetter&lt;/code&gt; which takes 6 seconds to return a result. &lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/asynctutorial/ParallelCallStack.png" alt="The SlugService first waits 9.2 seconds for PrimeFinder then 5.7s for SlugGetter" /&gt;&lt;/p&gt;

&lt;p&gt;In the meantime a worker thread (in orange) runs the prime finder which takes about 9 seconds to run. This is running while the main thread is running SlugGetter. Therefore rather than adding runtimes together as we did for synchronous execution we take the highest time (this isn't always the case but works for this example).&lt;/p&gt;

&lt;h3&gt;Time for Async&lt;/h3&gt;

&lt;p&gt;So we've seen how we can use parallel execution without the async/await keywords. Let's introduce them to our program now.&lt;/p&gt;

&lt;p&gt;For our &lt;code&gt;PrimeFinder&lt;/code&gt; we do not need a new method, we should &lt;a href="http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html"&gt;avoid creating asynchronous wrappers over synchronous CPU bound methods&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;SlugService&lt;/code&gt; we create a method with the async keyword in the method declaration. Async methods must return one of the following return types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Task&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;void&lt;/code&gt; (don't return void from an async method due to exception handling)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is achieved by changing the body of the method as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public async Task&amp;lt;IList&amp;lt;Slug&amp;gt;&amp;gt; GetSlugsAsync(int gen)
{
    Int64 generationalPrime = await Task.Run(primeFinder.FindNthPrime(50000 + gen)).ConfigureAwait(false);

    IList&amp;lt;Slug&amp;gt; slugs = slugGetter.GetDataSlugs(gen);

    foreach (var slug in slugs)
    {
        slug.FavouritePrime = generationalPrime;
    }

    return slugs;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a bit confusing, the method is declared to return &lt;code&gt;Task&amp;lt;IList&amp;lt;Slug&amp;gt;&amp;gt;&lt;/code&gt; but the method body returns an &lt;code&gt;IList&amp;lt;Slug&amp;gt;&lt;/code&gt;. This is because the compiler can be thought of as wrapping the method up into a Task behind the scenes.&lt;/p&gt;

&lt;p&gt;We have used &lt;code&gt;await&lt;/code&gt; in the body of the method to tell the async method to wait for the Prime Finder to complete. Also note the use of &lt;code&gt;ConfigureAwait(false)&lt;/code&gt; after the call to &lt;code&gt;FindNthPrime()&lt;/code&gt;, this isn't strictly necessary in a Console App but will help to prevent deadlocks in UI/ASP.NET code by ensuring the completed task doesn't ask for the original thread back. We also call &lt;code&gt;Task.Run()&lt;/code&gt; on the method rather than in the method implementation as recommended &lt;a href="http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Because &lt;a href="http://blog.stephencleary.com/2012/02/async-console-programs.html"&gt;Console Applications cannot have an async main method&lt;/a&gt; we have to 'unwrap' our async call at some point. To do this I created another method in &lt;code&gt;SlugService&lt;/code&gt; that main actually calls to, Stephen Cleary outlines how to do this properly for console apps in the link but I'm using it here to illustrate a point:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public IList&amp;lt;Slug&amp;gt; GetSlugsAsyncCaller(int gen)
{
    var task = GetSlugsAsync(gen);
    Console.WriteLine("Returned from async");
    Thread.Sleep(1000);
    return task.Result;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This time the console output looks like this where async is run first, then synchronous and finally parallel execution:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/asynctutorial/AsyncRun.png" alt="8946 Milliseconds getting prime, 5598 milliseconds getting slugs, 14548 overall for async" /&gt;&lt;/p&gt;

&lt;p&gt;As the results show, the async execution (14.5 seconds) takes just as long as the synchronous execution. But we're dealing with tasks, what gives?&lt;/p&gt;

&lt;p&gt;Async works in a quite different way to parallel execution and async execution is not necessarily parallel. Let's look at a call stack diagram that attempts to explain this (again the blue arrows illustrate the main thread).&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/asynctutorial/AsyncCallStack.png" alt="The SlugService returns when it hits await. It then executes fully for Result" /&gt;&lt;/p&gt;

&lt;p&gt;This is all terribly confusing. Basically at the point the code execution hits &lt;code&gt;await&lt;/code&gt; in &lt;code&gt;GetSlugsAsync&lt;/code&gt; it &lt;strong&gt;returns to the caller&lt;/strong&gt;, in this case &lt;code&gt;GetSlugsAsyncCaller&lt;/code&gt;, this is illustrated with the thicker blue arrow. The execution of that method (GetSlugsAsyncCaller) continues. It is then blocked by the call to &lt;code&gt;task.Result&lt;/code&gt; and the rest of the &lt;code&gt;GetSlugsAsync&lt;/code&gt; method executes in the normal way.&lt;/p&gt;

&lt;p&gt;Let's reiterate that; &lt;code&gt;await&lt;/code&gt; &lt;strong&gt;returns execution to the caller&lt;/strong&gt; and the caller continues to execute normally. Because we started the PrimeFinder task this executes in parallel while we're back in the &lt;code&gt;GetSlugsAsyncCaller&lt;/code&gt; method which is why the &lt;code&gt;Thread.Sleep(1000)&lt;/code&gt; in that method doesn't increase the execution time. However the actual &lt;code&gt;GetSlugsAsync&lt;/code&gt; method isn't parallel with respect to the flow inside its body, the &lt;code&gt;await&lt;/code&gt; is blocking since the PrimeFinder task must return a result at this point.&lt;/p&gt;

&lt;h3&gt;Purpose of Async&lt;/h3&gt;

&lt;p&gt;So the async/await doesn't give us any (parallel) execution time benefit inside the &lt;code&gt;GetSlugsAsync&lt;/code&gt; method itself. It's nice to continue to execute the calling method for a bit but this is of limited use. The calling method generally needs the result of the method called at some point in its body and because waiting for the result is blocking we don't gain much benefit.&lt;/p&gt;

&lt;p&gt;So what's the point?&lt;/p&gt;

&lt;p&gt;Well, the console app example falls down because it is not a good use of async. Async is like a virus that spreads through your code (not in a bad way), it only really works where the full call stack consists of async methods, you generally lose any benefit when you have to call &lt;code&gt;.Wait()&lt;/code&gt; or &lt;code&gt;.Result&lt;/code&gt; on an async method.&lt;/p&gt;

&lt;p&gt;Because you can't have an async main method in your console app (it would return control to the Operating System which would mess everything up / close the app) it's hard to demonstrate the advantages in this type of app.&lt;/p&gt;

&lt;p&gt;It's most obviously useful in WPF and ASP.NET applications. These both allow the methods called to return an async method at the root level to the caller:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In WPF the async method returns control to the UI loop on a call to &lt;code&gt;await&lt;/code&gt; in the code-behind, this means the UI thread continues to be active while the async task is processing.&lt;/li&gt;
&lt;li&gt;In ASP.NET the async controller action returns control to the application pool threads in IIS. This means the server can respond to other requests while the original request waits for its task to complete, generally using async I/O operations such as file I/O. This has a lot to do with &lt;strong&gt;I/O Completion Ports&lt;/strong&gt;. Therefore if we only have 50 threads in our application pool to respond to website requests we're not tying them up dealing with long-running tasks and they can more quickly be used to respond to further requests. This does not mean the &lt;strong&gt;request&lt;/strong&gt; is returned to the client early, just that the thread is returned to the server while the request processes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The actual way in which true async requests are dealt with in WPF and ASP.NET is different to how it was illustrated in this tutorial. In this tutorial an extra thread was used and blocked while the prime was calculated because this was a CPU calculation and not a good candidate for async. True async operations such as file I/O don't use an extra thread.&lt;/p&gt;

&lt;p&gt;See the section titled &lt;strong&gt;"What About the Thread Doing the Asynchronous Work?"&lt;/strong&gt; &lt;a href="http://msdn.microsoft.com/en-us/magazine/dn802603.aspx"&gt;here&lt;/a&gt;. To quote from that:
"[...] no thread is required for true asynchronous work. No CPU time is necessary to actually push the bytes out ".&lt;/p&gt;

&lt;h3&gt;Further Reading&lt;/h3&gt;

&lt;p&gt;This was a very simple introduction trying to clear up a confusing subject. Hopefully with the understanding you may/may not have gained from this tutorial you can go on to read more about async with the concept being slightly clearer.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://stephencleary.com/"&gt;Stephen Cleary&lt;/a&gt; is &lt;em&gt;the&lt;/em&gt; expert on async in C#, therefore it's not surprising he features heavily in the below links and most writing about async/await:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4"&gt;Official Microsoft guide to async in MVC&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/dn802603.aspx"&gt;Stephen's in-depth MSDN article on the benefits of async in ASP.NET&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa365198%28v=vs.85%29.aspx"&gt;Windows article on I/O Completion ports which are important for truly async operations&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.stephencleary.com/2012/02/async-and-await.html"&gt;Stephen's guide to async and await&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/12/async-programming</guid>
      <pubDate>Sun, 07 Dec 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>ASP NET MVC - Model Create With List of Model</title>
      <link>https://eliot-jones.com/2014/11/mvc-ajax-4</link>
      <description>

&lt;p&gt;This post runs through how to create a form for creating a model with a list of child models using MVC 5 and Razor.&lt;/p&gt;

&lt;p&gt;I've been rather quiet on the blogging front lately, I've been working on getting my MVC 5 quiz application up and running on Azure, &lt;a href="http://quiziskra.azurewebsites.net/"&gt;it's here&lt;/a&gt; if anyone wants to give it a go.&lt;/p&gt;

&lt;p&gt;One thing I wanted to do while working on the site was allow for a model to be created along with a list of "sub" models; for example when creating a question it would be nice for a user to also create the answers on the same page.&lt;/p&gt;

&lt;h3&gt;Setup&lt;/h3&gt;

&lt;p&gt;To demo this we need a model which could "own" some collection of other items. I happened on the perfect example today in the Json.NET source:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://raw.githubusercontent.com/JamesNK/Newtonsoft.Json/master/Src/Newtonsoft.Json.Tests/bunny_pancake.jpg" alt="Rabbit with a pancake on its head." /&gt;&lt;/p&gt;

&lt;p&gt;From &lt;a href="https://raw.githubusercontent.com/JamesNK/Newtonsoft.Json/master/Src/Newtonsoft.Json.Tests/bunny_pancake.jpg"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yep, that's a rabbit with a pancake on its head.&lt;/p&gt;

&lt;p&gt;Let's create our simple classes for this scenario:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;namespace SandboxMvc.Pocos
{
    using System;
    using System.Collections.Generic;

    public class Rabbit
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int IrritationLevel { get; set; }
        public IList&amp;lt;Pancake&amp;gt; Pancakes { get; set; }
    }
    public class Pancake
    {
        public int Id { get; set; }
        public int Thickness { get; set; }
        public bool IsCrepe { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Controllers&lt;/h3&gt;

&lt;p&gt;We need two controller actions, first the create action get and post for the rabbit itself and then the partial view action for a pancake.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;namespace SandboxMvc.Controllers
{
    using SandboxMvc.Pocos;
    using System.Collections.Generic;
    using System.Web.Mvc;
    public class RabbitController : Controller
    {
        [HttpGet]
        public ActionResult Create()
        {
            Rabbit rabbity = new Rabbit { Pancakes = new List&amp;lt;Pancake&amp;gt;() };
            return View(rabbity);
        }

        [HttpPost]
        public ActionResult Create(Rabbit model)
        {
            if (!ModelState.IsValid) return View(model);
            Session["Rabbit"] = model;
            return RedirectToAction(actionName: "Create");
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I'm using the session for persistence here because I'm exceedingly lazy.&lt;/p&gt;

&lt;h3&gt;Views&lt;/h3&gt;

&lt;p&gt;Let's get Razor to scaffold our Create view first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model SandboxMvc.Pocos.Rabbit
@{int index = Model.Pancakes.Count;}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    &amp;lt;div class="form-horizontal"&amp;gt;
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        &amp;lt;div class="form-group"&amp;gt;
            @Html.LabelFor(model =&amp;gt; model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            &amp;lt;div class="col-md-10"&amp;gt;
                @Html.EditorFor(model =&amp;gt; model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model =&amp;gt; model.Name, "", new { @class = "text-danger" })
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="form-group"&amp;gt;
            @Html.LabelFor(model =&amp;gt; model.IrritationLevel, htmlAttributes: new { @class = "control-label col-md-2" })
            &amp;lt;div class="col-md-10"&amp;gt;
                @Html.EditorFor(model =&amp;gt; model.IrritationLevel, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model =&amp;gt; model.IrritationLevel, "", new { @class = "text-danger" })
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;!-- PANCAKES! --&amp;gt;
        &amp;lt;div id="pancake-group"&amp;gt;
            &amp;lt;h4&amp;gt;Pancakes&amp;lt;/h4&amp;gt;
        &amp;lt;/div&amp;gt;
        @Ajax.ActionLink(linkText: "+", actionName: "_CreateFields", controllerName: "Pancake", routeValues: new { index = index }, ajaxOptions: new AjaxOptions
        {
            InsertionMode = InsertionMode.InsertAfter,
            UpdateTargetId = "pancake-group",
            OnSuccess = "indexIterate"
        },
        htmlAttributes: new { id = "addPancake", @class = "btn btn-default" })

        &amp;lt;div class="form-group"&amp;gt;
            &amp;lt;div class="col-md-offset-2 col-md-10"&amp;gt;
                &amp;lt;input type="submit" value="Create" class="btn btn-default" /&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The change we've made is where the comment excitably declares &lt;strong&gt;PANCAKES!&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We add a div &lt;code&gt;&amp;lt;div id="pancake-group"&amp;gt;&lt;/code&gt; as an update target for our Ajax.&lt;/p&gt;

&lt;p&gt;We then include the following &lt;code&gt;Ajax.ActionLink&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Ajax.ActionLink(linkText: "+", actionName: "_CreateFields", controllerName: "Pancake", 
routeValues: new { index = index }, 
ajaxOptions: new AjaxOptions
    {
        InsertionMode = InsertionMode.InsertAfter,
        UpdateTargetId = "pancake-group",
        OnSuccess = "indexIterate"
    },
    htmlAttributes: new { id = "addPancake", @class = "btn btn-default" })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This simply calls the &lt;code&gt;_CreateFields&lt;/code&gt; action on our Pancake controller. It passes the index to add as a route value.&lt;/p&gt;

&lt;p&gt;Of particular importance are the &lt;code&gt;OnSuccess&lt;/code&gt; value of the AjaxOptions and the &lt;code&gt;id&lt;/code&gt; of the htmlAttributes. These allow us to use the following Javascript to increment our link target:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var currentIndex = 0;

function indexIterate() {
    var newHref = $("#addPancake").attr("href");
    var newerHref = newHref.replace(/(?:index=)[0-9]+/i, "index=" + ++currentIndex);
    $("#addPancake").attr("href", newerHref);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Also notice the &lt;code&gt;@index&lt;/code&gt; set near the top of the view code!&lt;/p&gt;

&lt;h3&gt;Pancake Controller&lt;/h3&gt;

&lt;p&gt;Now we add our pancake controller action and View:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class PancakeController : Controller
{
    public ActionResult _CreateFields(Rabbit model, int? index)
    {
        ViewBag.Index = index ?? 0;
        return PartialView(model);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This returns the partial view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model SandboxMvc.Pocos.Rabbit
@{
    int i = ViewBag.index ?? 0;
}

&amp;lt;div class="form-group"&amp;gt;
    @Html.LabelFor(model =&amp;gt; model.Pancakes[i].Thickness, htmlAttributes: new { @class = "control-label col-md-2" })
    &amp;lt;div class="col-md-10"&amp;gt;
        @Html.EditorFor(model =&amp;gt; model.Pancakes[i].Thickness, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model =&amp;gt; model.Pancakes[i].Thickness, "", new { @class = "text-danger" })
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div class="form-group"&amp;gt;
    @Html.LabelFor(model =&amp;gt; model.Pancakes[i].IsCrepe, htmlAttributes: new { @class = "control-label col-md-2" })
    &amp;lt;div class="col-md-10"&amp;gt;
        @Html.CheckBoxFor(model =&amp;gt; model.Pancakes[i].IsCrepe, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model =&amp;gt; model.Pancakes[i].IsCrepe, "", new { @class = "text-danger" })
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compile this and run it and you should be able to create all the pancakes you want on your rabbit.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/pancakes.png" alt="shows the rabbit being created" /&gt;&lt;/p&gt;

&lt;h3&gt;Model Validation&lt;/h3&gt;

&lt;p&gt;When you have to use server side validation of your model, your sub items will disappear on validation if the validation fails.&lt;/p&gt;

&lt;p&gt;Resolving this is luckily fairly simple. For your Create view for Rabbit add the following code inside your &lt;code&gt;pancake-group&lt;/code&gt; div:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@for (int i = 0; i &amp;lt; index; i++)
{
    @Html.Action(actionName: "_CreateFields", controllerName: "Pancake", routeValues: new { index = i })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;This tutorial showed how to add a list of models to the create for of another model and have that list submitted on post in addition to server side validation.&lt;/p&gt;

&lt;p&gt;The full code for the files featured can be found as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax-four/Rabbit.cs"&gt;Pocos&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax-four/RabbitController.cs"&gt;RabbitController and PancakeController&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax-four/Create.cshtml"&gt;Rabbit Create View&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=":http://eliot-jones.com/Code/mvc-ajax-four/_CreateFields.cshtml"&gt;Pancake Partial View&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/11/mvc-ajax-4</guid>
      <pubDate>Tue, 25 Nov 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>ASP.NET Identity 2.0 Tutorial - Password Reset and Roles</title>
      <link>https://eliot-jones.com/2014/10/asp-identity-2-0-password-reset</link>
      <description>

&lt;p&gt;Given how much you all enjoyed the previous tutorial, i.e. not at all, I thought I'd write a follow up post. As promised this blog post extends the basic system we created in the &lt;a href="http://eliot-jones.com/2014/10/asp-identity-2-0" title="ASP NET Identity 2.0 Tutorial"&gt;main tutorial&lt;/a&gt; to add roles and a password reset function.&lt;/p&gt;

&lt;p&gt;I won't show how to setup the emails for password reset because I'm too lazy to fill in the form for a free SendGrid account, however plugging emails in should be the easy bit.&lt;/p&gt;

&lt;h3&gt;Password Reset&lt;/h3&gt;

&lt;p&gt;The default template provides the controller actions and views for a full password reset function. The user can enter an email address at &lt;code&gt;/Account/ForgotPassword&lt;/code&gt;. When posted the action below is called:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public async Task&amp;lt;ActionResult&amp;gt; ForgotPassword(ForgotPasswordViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = await UserManager.FindByNameAsync(model.Email);
        if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id.ToString())))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }
        string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id.ToString());
        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);      
        // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking &amp;lt;a href=\"" + callbackUrl + "\"&amp;gt;here&amp;lt;/a&amp;gt;");
        return RedirectToAction("ForgotPasswordConfirmation", "Account");
    }
    return View(model);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have commented out the email sending part for the reasons mentioned above.&lt;/p&gt;

&lt;p&gt;All we need to do is supply our &lt;code&gt;UserManager&lt;/code&gt; with a token provider. From the code for the default UserManager:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Used for generating reset password and confirmation tokens
/// &amp;lt;/summary&amp;gt;
public IUserTokenProvider&amp;lt;TUser, TKey&amp;gt; UserTokenProvider { get; set; }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As usual Microsoft have made everything easy by giving us a nice interface to implement. This also means you can adapt your password reset to function however you like. For instance you could add an expiry date to the reset token or have a token which is a combination of a Guid and number or two Guids.&lt;/p&gt;

&lt;p&gt;For my token provider I'm simply going to generate a new Guid to act as the reset token. This maps onto the nullable reset token field on my user table, I've hidden some stuff here because I don't want you stealing the super secure password hashes ("password" and "password1"):&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/aspidentity2/userTable.png" alt="Screenshot of user table schema." /&gt;&lt;/p&gt;

&lt;p&gt;Now we create a class which implements the required 4 methods for a token provider:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class MyUserTokenProvider&amp;lt;TUser&amp;gt; : IUserTokenProvider&amp;lt;MyUser, string&amp;gt;  where TUser : class, IUser
{
    public Task&amp;lt;string&amp;gt; GenerateAsync(string purpose, UserManager&amp;lt;MyUser, string&amp;gt; manager, MyUser user)
    {
        Guid resetToken = Guid.NewGuid();
        user.PasswordResetToken = resetToken;
        manager.UpdateAsync(user);
        return Task.FromResult&amp;lt;string&amp;gt;(resetToken.ToString());
    }

    public Task&amp;lt;bool&amp;gt; IsValidProviderForUserAsync(UserManager&amp;lt;MyUser, string&amp;gt; manager, MyUser user)
    {
        if (manager == null) throw new ArgumentNullException();
        else {
            return Task.FromResult&amp;lt;bool&amp;gt;(manager.SupportsUserPassword);
        }
    }

    public Task NotifyAsync(string token, UserManager&amp;lt;MyUser, string&amp;gt; manager, MyUser user)
    {
        return Task.FromResult&amp;lt;int&amp;gt;(0);
    }

    public Task&amp;lt;bool&amp;gt; ValidateAsync(string purpose, string token, UserManager&amp;lt;MyUser, string&amp;gt; manager, MyUser user)
    {
        return Task.FromResult&amp;lt;bool&amp;gt;(user.PasswordResetToken.ToString() == token);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
&lt;li&gt;The 0 value returned from &lt;code&gt;NotifyAsync&lt;/code&gt; mirrors the way it's done in the &lt;code&gt;TotpSecurityStampBasedTokenProvider&lt;/code&gt; included in the Identity library. &lt;/li&gt;
&lt;li&gt;I don't call through to the store in the &lt;code&gt;ValidateAsync&lt;/code&gt; method because the user argument will have been retrieved by the manager just before this method call so there's no point duplicating data access.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;IsValidProviderForUserAsync&lt;/code&gt; should probably be implemented differently however this does what I want so why change? :) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last thing we need to do is tell our UserManager about its swanky new token provider. You can either throw it in the overloaded constructor or &lt;code&gt;Create&lt;/code&gt; method. Here I've put it in the constructor:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ApplicationUserManager : UserManager&amp;lt;MyUser&amp;gt;
{
    public ApplicationUserManager(IUserStore&amp;lt;MyUser&amp;gt; store)
        : base(store)
    {
        this.UserValidator = new MyUserValidator&amp;lt;MyUser, string&amp;gt;();
        this.UserTokenProvider = new MyUserTokenProvider&amp;lt;MyUser&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now if you go to the link contained in the &lt;code&gt;callbackUrl&lt;/code&gt; variable in the controller action you can reset a user's password.&lt;/p&gt;

&lt;h4&gt;Summary&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Give your persistence layer some kind of a password reset token.&lt;/li&gt;
&lt;li&gt;Create a class which implements &lt;code&gt;IUserTokenProvider&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Pass that class to your UserManager class as the manager's &lt;code&gt;UserTokenProvider&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;?&lt;/li&gt;
&lt;li&gt;Profit&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;Roles&lt;/h3&gt;

&lt;p&gt;The UserManager class has a set of boolean properties of the form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Returns true if the store is an IUserPasswordStore
/// &amp;lt;/summary&amp;gt;
public virtual bool SupportsUserPassword
{
  get
  {
    return Store is IUserPasswordStore&amp;lt;TUser, TKey&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The booleans check which interfaces your &lt;code&gt;UserStore&lt;/code&gt; implements. These booleans are used to throw descriptive exceptions where your store is lacking the methods the manager depends on. The full list is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;IUserTwoFactorStore&lt;/li&gt;
&lt;li&gt;IUserPasswordStore&lt;/li&gt;
&lt;li&gt;IUserSecurityStampStore&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;IUserRoleStore&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;IUserLoginStore&lt;/li&gt;
&lt;li&gt;IUserEmailStore&lt;/li&gt;
&lt;li&gt;IUserPhoneNumberStore&lt;/li&gt;
&lt;li&gt;IUserClaimStore&lt;/li&gt;
&lt;li&gt;IUserLockoutStore&lt;/li&gt;
&lt;li&gt;IQueryableUserStore&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The IUserStore has to be used by default so isn't included. Whenever we want to use a piece of the manager's functionality generally all we need to do is implement the missing interface on our store.&lt;/p&gt;

&lt;p&gt;This extensibility comes in handy for the role store. With roles defined we can do things like this on our controllers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[Authorize(Roles="Elevated Browser")]
public ActionResult Contact()
{
    return View();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This makes limiting access to certain actions very easy. Additionally because everything uses interfaces with generic parameters no assumptions are made about our persistence layer.&lt;/p&gt;

&lt;p&gt;Let's say users gain points through some mechanism, when they get enough points they unlock certain privileges which can be represented by roles. Because we aren't tied to the Code First models for our store we can have this sort of model for our roles:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/aspidentity2/roleStore.png" alt="Roles table schema featuring Role, UserRole and Users table." /&gt;&lt;/p&gt;

&lt;p&gt;A Role requires a certain number of points and a user has points (which should probably be in a UserPoint table). This is not a brilliant way to implement this model but serves as a warning to future generations (example).&lt;/p&gt;

&lt;p&gt;It would make sense to have a composite primary key of RoleId and UserId in the UserRole table however I've opted for a single column primary key in case UserRole evolves into some kind of business entity.&lt;/p&gt;

&lt;p&gt;Again the fact I'm using Database-First Entity Framework shouldn't matter here because all that you need to worry about is how to implement your own version of the &lt;code&gt;IUserRoleStore&lt;/code&gt; in your store.&lt;/p&gt;

&lt;p&gt;Here's mine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#region RoleStore
public Task AddToRoleAsync(MyUser user, string roleName)
{
    return Task.Factory.StartNew(() =&amp;gt; ChangeRoleMembership(user, roleName, ChangeType.Add));
}

public Task&amp;lt;IList&amp;lt;string&amp;gt;&amp;gt; GetRolesAsync(MyUser user)
{
    using (var db = new EfDbContext())
    {
        User userDb = db.Users.Find(user.Id);

        IEnumerable&amp;lt;int&amp;gt; userRoleIds = userDb.UserRoles.Select(ur =&amp;gt; ur.RoleId);

        IEnumerable&amp;lt;string&amp;gt; roleNames = db.Roles.Where(r =&amp;gt; userRoleIds.Contains(r.Id)).Select(r =&amp;gt; r.Name);

        return Task.FromResult&amp;lt;IList&amp;lt;string&amp;gt;&amp;gt;(roleNames.ToList());
    }
}

public Task&amp;lt;bool&amp;gt; IsInRoleAsync(MyUser user, string roleName)
{
    bool isInRole = false;
    using (var db = new EfDbContext())
    {
        Role roleDb = db.Roles.FirstOrDefault(r =&amp;gt; string.Compare(r.Name, roleName) == 0);
        User userDb = db.Users.Find(user.Id);

        if (roleDb != null &amp;amp;&amp;amp; userDb != null)
        {
            UserRole userRole = userDb.UserRoles.FirstOrDefault(ur =&amp;gt; ur.RoleId == roleDb.Id);
            isInRole = userRole != null;
        }
    }

    return Task.FromResult&amp;lt;bool&amp;gt;(isInRole);
}

public Task RemoveFromRoleAsync(MyUser user, string roleName)
{
    return Task.Factory.StartNew(() =&amp;gt; ChangeRoleMembership(user, roleName, ChangeType.Remove));
}
#endregion
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;ChangeRoleMembership&lt;/code&gt; method and &lt;code&gt;ChangeType&lt;/code&gt; enum are just things I've implemented and can be swapped out for your own methods.&lt;/p&gt;

&lt;p&gt;Without any further changes you should be able to use the roles in your controller attributes.&lt;/p&gt;

&lt;h4&gt;Summary&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Create some Roles feature in your persistence layer.&lt;/li&gt;
&lt;li&gt;Add the &lt;code&gt;IUserRoleStore&lt;/code&gt; interface methods to your user store.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;On A Roll(e)&lt;/h3&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/aspidentity2/breadrolls.jpg" alt="Bread rolls." /&gt;&lt;/p&gt;

&lt;p&gt;Hopefully this tutorial series shows how easy it is to make the Identity 2.0 system do what you want. If nothing else you should now have the information necessary to find out what the UserManager expects and provide classes that comply with its demands.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Roll Image from: http://nl.wikipedia.org/wiki/Bestand:Kaiserbroodjes1151.JPG. Yes I really did scroll through the roll category on Wikimedia... because I care.&lt;/em&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/10/asp-identity-2-0-password-reset</guid>
      <pubDate>Mon, 13 Oct 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>ASP.NET Identity 2.0 Tutorial - EF Free (Post 2)</title>
      <link>https://eliot-jones.com/2014/10/asp-identity-2-0-p2</link>
      <description>

&lt;p&gt;&lt;em&gt;Note: This is the second post in a 2 post tutorial on implementing Identity 2.0 without using EF, for post 1 go &lt;a href="http://eliot-jones.com/2014/10/asp-identity-2-0" title="First Page"&gt;here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now we have our User and UserStore classes we can change the UserManager and SignInManager our application uses. These classes are in the &lt;code&gt;App_Start/IdentityConfig.cs&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;I split the classes out to their own files, &lt;code&gt;ApplicationUserManager.cs&lt;/code&gt; and &lt;code&gt;ApplicationSignInManager.cs&lt;/code&gt; respectively. In their unmodified state these classes inherit from the classes provided by the Identity library.&lt;/p&gt;

&lt;h3&gt;ApplicationUserManager&lt;/h3&gt;

&lt;p&gt;The manager provides many methods to use in our controllers, a few examples are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public virtual Task&amp;lt;IdentityResult&amp;gt; ResetAccessFailedCountAsync(TKey userId);
public virtual Task&amp;lt;IdentityResult&amp;gt; ResetPasswordAsync(TKey userId, string token, string newPassword);
public virtual Task SendEmailAsync(TKey userId, string subject, string body);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The manager mainly delegates to classes it owns such as the user store to run these methods. The default template UserManager is shown below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ApplicationUserManager : UserManager&amp;lt;ApplicationUser&amp;gt;
{
    public ApplicationUserManager(IUserStore&amp;lt;ApplicationUser&amp;gt; store)
        : base(store) { }

    public static ApplicationUserManager Create(IdentityFactoryOptions&amp;lt;ApplicationUserManager&amp;gt; options, 
        IOwinContext context) 
    {
        var manager = new ApplicationUserManager(
            new UserStore&amp;lt;ApplicationUser&amp;gt;(context.Get&amp;lt;ApplicationDbContext&amp;gt;()));

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator&amp;lt;ApplicationUser&amp;gt;(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        [CONTENT REMOVED TO SAVE SPACE...]
        return manager;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because everything takes arguments based on interfaces we've already created our classes for, the rewrite is very simple. Firstly we replace all instances of &lt;code&gt;ApplicationUser&lt;/code&gt; with our class which implements IUser, in our case &lt;code&gt;MyUser&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ApplicationUserManager : UserManager&amp;lt;MyUser&amp;gt;
{
    public ApplicationUserManager(IUserStore&amp;lt;MyUser&amp;gt; store)
        : base(store)
    {
        this.UserValidator = new MyUserValidator&amp;lt;MyUser, string&amp;gt;();
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions&amp;lt;ApplicationUserManager&amp;gt; options, 
        IOwinContext context)
    {
        var manager = new ApplicationUserManager(new MyUserStore&amp;lt;MyUser&amp;gt;());
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator&amp;lt;MyUser&amp;gt;(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 3,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = true,
            RequireUppercase = false
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = false;

        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();

        return manager;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I set the password requirements to be super weak for manual testing because typing secure passwords repeatedly was too much like hard work!&lt;/p&gt;

&lt;p&gt;We also remove the default &lt;code&gt;UserStore&lt;/code&gt; which depends on Entity Framework and insert our own &lt;code&gt;MyUserStore&lt;/code&gt; (which in this tutorial also depends on EF but with no requirement to pass a DbContext to the constructor). Additionally all parts setting up 2 Factor Auth are removed.&lt;/p&gt;

&lt;p&gt;An extra change in the Setup method is required, without it the call to UserManager &lt;code&gt;CreateAsync(user, password)&lt;/code&gt; may fail when it tries to search by an email address which doesn't exist. It may not, it depends on how you implement interface methods in your store.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;CreateAsync&lt;/code&gt; method of UserManager calls the &lt;code&gt;ValidateAsync&lt;/code&gt; method of the UserValidator object created by default (or explicitly in the &lt;code&gt;Create&lt;/code&gt; method). If you decompile the validator you can see it calls the following methods of your store prior to actually creating the record:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;FindByNameAsync&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;FindByEmailAsync&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By default it expects you to return null from your store on these methods where the name or email doesn't exist. To avoid having the validator make assumptions about how you implement your methods you can supply your own class which implements IIdentityValidator as shown below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static ApplicationUserManager Create(
    IdentityFactoryOptions&amp;lt;ApplicationUserManager&amp;gt; options, 
    IOwinContext context)
{
    var manager = new ApplicationUserManager(new MyUserStore&amp;lt;MyUser&amp;gt;());
    manager.UserValidator = new MyUserValidator&amp;lt;MyUser, string&amp;gt;();
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where &lt;code&gt;MyUserValidator : IIdentityValidator&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;SignInManager&lt;/h3&gt;

&lt;p&gt;The sign in manager works with the user manager to validate user logins against the store and provide login information. The default sign in manager is pretty small which makes our change easy, shown below is the default implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ApplicationSignInManager : SignInManager&amp;lt;ApplicationUser, string&amp;gt;
{
    public ApplicationSignInManager(ApplicationUserManager userManager, 
        IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task&amp;lt;ClaimsIdentity&amp;gt; CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions&amp;lt;ApplicationSignInManager&amp;gt; options, 
        IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager&amp;lt;ApplicationUserManager&amp;gt;(), 
            context.Authentication);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can replace this with an almost identical replacement:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ApplicationSignInManager : SignInManager&amp;lt;MyUser, string&amp;gt;
{
    public ApplicationSignInManager(ApplicationUserManager userManager, 
        IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager) { }

    public static ApplicationSignInManager Create(
        IdentityFactoryOptions&amp;lt;ApplicationSignInManager&amp;gt; options, 
        IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager&amp;lt;ApplicationUserManager&amp;gt;(), 
            context.Authentication);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However here I removed the &lt;code&gt;CreateUserIdentityAsync(ApplicationUser user)&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;I removed the method from the user also. This is because it seems odd to have the user take responsibility for creating itself with the manager. You're welcome to implement it if you wish but it just seemed strange to me.&lt;/p&gt;

&lt;p&gt;Removing this breaks things in a couple of places. The most important one is in &lt;code&gt;App_Start/Startup.Auth.cs&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.  
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&amp;lt;ApplicationUserManager, ApplicationUser&amp;gt;(
    validateInterval: TimeSpan.FromMinutes(30),
    regenerateIdentity: (manager, user) =&amp;gt; user.GenerateUserIdentityAsync(manager)
    )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Luckily this method just calls through to the &lt;code&gt;CreateIdentityAsync&lt;/code&gt; method on the UserManager so we can change the above Startup code to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&amp;lt;ApplicationUserManager, MyUser&amp;gt;(
        validateInterval: TimeSpan.FromMinutes(30),
        regenerateIdentity: (m, u) =&amp;gt; 
            m.CreateIdentityAsync(u, DefaultAuthenticationTypes.ApplicationCookie))
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Rounding Up&lt;/h3&gt;

&lt;p&gt;We have implemented a bare-bones system, the code won't compile until you change all references to ApplicationUser to use your User implementation. Additionally many method calls will fail at run-time for things like 2 Factor and Claims-Based Authentication.&lt;/p&gt;

&lt;p&gt;However if you remove enough code from the template controllers you should have a system which allows you to register and login/out. It also validates users based on the &lt;code&gt;[Authorize]&lt;/code&gt; attribute on controllers.&lt;/p&gt;

&lt;p&gt;I hope to write a post about implementing things like Password Reset and Roles but I've put this up now to help anyone who is stuck. &lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;This tutorial showed how to use ASP.NET Identity 2.0 without Entity Framework. It does not use many of the new features of Identity 2.0 but shows how to create a basic login system with Identity 2.0.&lt;/p&gt;

&lt;p&gt;The reliance of Identity 2.0 on EF Code First makes sense when viewed in the context of the &lt;a href="https://www.youtube.com/watch?v=Ie_0k1_9LJ0&amp;amp;list=PL0M0zPgJ3HSftTAAHttA3JQU4vOjXFquF&amp;amp;index=3" title="vNext Community Standup (video)"&gt;retirement of Database/Model First in EF7&lt;/a&gt;. However it makes things difficult for people not using EF (Code First). There are many open source providers for other databases such as MongoDb available on NuGet and this tutorial hopefully explains a bit about how it all fits together.&lt;/p&gt;

&lt;p&gt;In order to extend this simple identity system you'll need a good decompiler to see what's going on under-the-hood in the UserManager class when you run into problems. I can recommend &lt;a href="https://www.jetbrains.com/decompiler/" title="JetBrains dotPeek decompiler"&gt;dotPeek&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I hope this helps you, it aims to be the guide I wish I had when I started writing it. Any problems please leave a comment.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/10/asp-identity-2-0-p2</guid>
      <pubDate>Sun, 12 Oct 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>ASP.NET Identity 2.0 Tutorial - Entity Framework Free</title>
      <link>https://eliot-jones.com/2014/10/asp-identity-2-0</link>
      <description>

&lt;p&gt;So in &lt;a href="http://eliot-jones.com/2014/08/asp-identity-database-first" title="Blog post on my site"&gt;this post&lt;/a&gt; I detailed how to use Asp Identity with Entity Framework Database First. However when I started a new MVC project and tried to follow the steps nothing worked. &lt;a href="http://blogs.msdn.com/b/webdev/archive/2014/03/20/test-announcing-rtm-of-asp-net-identity-2-0-0.aspx" title="Identity 2.0 announcement on MSDN"&gt;ASP Identity 2.0&lt;/a&gt; has ruined everything by introducing many breaking changes. &lt;/p&gt;

&lt;p&gt;This post will guide you on how to setup Identity 2.0 without Entity Framework. The original post was a lot longer but I've tried to cut down a lot of the rambling, for a great step-by-step guide to Identity 2.0 see this &lt;a href="http://www.codeproject.com/Articles/762428/ASP-NET-MVC-and-Identity-Understanding-the-Basics" title="Guide to Identity 2.0"&gt;excellent CodeProject post&lt;/a&gt; by John Atten.&lt;/p&gt;

&lt;h3&gt;Create a New Project&lt;/h3&gt;

&lt;p&gt;Let's create a new MVC project using Individual User Accounts as shown below to see what the template gives us:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/aspidentity2/newProjectScreen.png" alt="The default new project screen." /&gt;&lt;/p&gt;

&lt;p&gt;This gives us a familiar MVC project. At the root level is the partial class &lt;code&gt;Startup.cs&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This makes a call to the other part of this class  &lt;code&gt;Startup.Auth.cs&lt;/code&gt; defined in the App_Start folder. 
This does a lot of things including acting as an IoC container for our &lt;code&gt;ApplicationDbContext&lt;/code&gt;
, &lt;code&gt;ApplicationUserManager&lt;/code&gt; and &lt;code&gt;ApplicationSignInManager&lt;/code&gt; using Owin to create an instance for each web request. Additionally it sets up two-factor authentication for SMS verification of log-ins which is a new feature in Identity 2.0.&lt;/p&gt;

&lt;p&gt;To remove the dependence on Entity Framework we need to implement everything without the Microsoft.AspNet.Identity.EntityFramework library.&lt;/p&gt;

&lt;h3&gt;A Case of Mistaken Identity&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;ApplicationUserManager&lt;/code&gt; and &lt;code&gt;ApplicationSignInManager&lt;/code&gt; mentioned are in the file &lt;code&gt;IdentityConfig.cs&lt;/code&gt;. This file contains the following 4 classes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;EmailService&lt;/li&gt;
&lt;li&gt;SmsService&lt;/li&gt;
&lt;li&gt;ApplicationUserManager&lt;/li&gt;
&lt;li&gt;ApplicationSignInManager&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For now we can ignore the EmailService and SmsService. This is where you'd integrate something like &lt;a href="http://sendgrid.com/" title="SendGrid email service"&gt;SendGrid&lt;/a&gt; or your own SMTP server to send emails.&lt;/p&gt;

&lt;h3&gt;Back to Basics&lt;/h3&gt;

&lt;p&gt;The layout of classes and what relies on what is actually fairly simple, it just takes a bit of thinking about. This image outlines what we're talking about:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/aspidentity2/basicDiagram.png" style="border:1px solid #AAA" alt="Diagram outlining 4 main classes." /&gt;&lt;/p&gt;

&lt;p&gt;We have 4 main classes to worry about:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;User&lt;/strong&gt; - it's up to us to implement this using the IUser interface. The EF version uses the IdentityUser class but we can't use this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;UserStore&lt;/strong&gt; - the user store handles saving and retrieving data from our storage medium. This could be anything you can think of. In this tutorial I'm using EF Database First but it won't affect the EF-free nature of this tutorial.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;UserManager&lt;/strong&gt; - this is implemented for us by the Microsoft.AspNet.Identity.Core library, it's up to us to provide it with a suitable user and user store implementation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SignInManager&lt;/strong&gt; - this is implemented for us by the Identity.Owin library, we must provide it a suitable user manager and user implementation. &lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;User&lt;/h3&gt;

&lt;p&gt;So Identity 2.0 deals with a user implementation. In the new MVC project template it uses the IdentityUser class. This is in the &lt;code&gt;IdentityModels.cs&lt;/code&gt; file. This file contains 2 classes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ApplicationUser&lt;/li&gt;
&lt;li&gt;ApplicationDbContext&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Any hope we have of easily separating our project from a dependency on EntityFramework is dashed here because IdentityUser is an EF specific class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ApplicationUser : IdentityUser
{
    public async Task&amp;lt;ClaimsIdentity&amp;gt; GenerateUserIdentityAsync(UserManager&amp;lt;ApplicationUser&amp;gt; manager)
    {
        var userIdentity = 
            await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By moving everything back onto Core we only have to implement an IUser&amp;lt;TKey&amp;gt; class where TKey is the type of the primary key (e.g. int, Guid, etc).&lt;/p&gt;

&lt;p&gt;I implemented the class &lt;code&gt;MyUser&lt;/code&gt; as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;namespace TutorialIdentity.Identity
{
    using Microsoft.AspNet.Identity;
    using System;
    public class MyUser : IUser&amp;lt;int&amp;gt;, IUser
    {
        public int Id { get; set; }
        string IUser&amp;lt;string&amp;gt;.Id{ get { return Id.ToString(); } }

        public string UserName { get; set; }
        public string Email { get; set; }

        public string PasswordHash { get; set; }
        public string SecurityStamp { get; set; }
        public Guid? PasswordResetToken { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This class is then mapped onto an underlying class in the EF Db First model but could be stored in anything.&lt;/p&gt;

&lt;p&gt;I use both the IUser&amp;lt;int&amp;gt; and IUser (equivalent to IUser&amp;lt;string&amp;gt;) interface in order to make life easier when integrating with the existing classes and interfaces.&lt;/p&gt;

&lt;h3&gt;UserStore&lt;/h3&gt;

&lt;p&gt;The user store is required to implement several interfaces. Firstly it must implement the IUserStore&lt;TUser, TKey&gt; interface. From the code for the UserManager class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Persistence abstraction that the UserManager operates against
/// 
/// &amp;lt;/summary&amp;gt;
protected internal IUserStore&amp;lt;TUser, TKey&amp;gt; Store { get; set; }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The UserManager takes the store in its constructor.&lt;/p&gt;

&lt;p&gt;I created a class &lt;code&gt;MyUserStore&lt;/code&gt; as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class MyUserStore&amp;lt;TUser&amp;gt; : IUserStore&amp;lt;MyUser&amp;gt; where TUser : IUser
{
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;IUserStore&lt;/h4&gt;

&lt;p&gt;In &lt;code&gt;MyUserStore&lt;/code&gt; this interface is implemented as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public Task CreateAsync(MyUser user)
{
    User userDb = ToUser(user);
    return Task.Factory.StartNew(() =&amp;gt;
    {
        SaveUser(userDb);
    });
}

public Task DeleteAsync(MyUser user)
{
    throw new System.NotImplementedException();
}

public Task&amp;lt;MyUser&amp;gt; FindByIdAsync(string userId)
{
    return Task.Factory.StartNew&amp;lt;MyUser&amp;gt;(() =&amp;gt; FindUser(userId, FindKeyType.Id));
}

public Task&amp;lt;MyUser&amp;gt; FindByNameAsync(string userName)
{
    return Task.Factory.StartNew&amp;lt;MyUser&amp;gt;(() =&amp;gt; FindUser(userName, FindKeyType.Name));
}

public Task UpdateAsync(MyUser user)
{
    return Task.Factory.StartNew(() =&amp;gt;
    {
        using (var db = new EfDbContext())
        {
            User userDbOrig = db.Users.Find(user.Id);
            userDbOrig.UserName = user.UserName;
            userDbOrig.PasswordHash = user.PasswordHash;
            userDbOrig.Email = user.Email;
            db.Entry(userDbOrig).State = EntityState.Modified;
            db.SaveChanges();
        }
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I haven't finished writing UpdateAsync and DeleteAsync methods since &lt;strong&gt;this is just a throwaway tutorial store&lt;/strong&gt;. These methods call other methods which use the EF DbContext. However they could just as easily call a webservice or MongoDb or a text file storage mechanism (which would be really weird but I give the example to show that the world is your oyster).&lt;/p&gt;

&lt;p&gt;In its current state our UserStore will be accepted by the UserManager at compile time however we can do nothing useful with it at runtime. To get to the point where logins are working we need some more interfaces on our store.&lt;/p&gt;

&lt;p&gt;The full list to get to the point where logging in / registering works is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;IUserPasswordStore&amp;lt;MyUser&amp;gt;&lt;/li&gt;
&lt;li&gt;IUserEmailStore&amp;lt;MyUser&amp;gt;&lt;/li&gt;
&lt;li&gt;IUserLockoutStore&lt;MyUser, string&gt;&lt;/li&gt;
&lt;li&gt;IUserTwoFactorStore&lt;MyUser, string&gt;&lt;/li&gt;
&lt;li&gt;IUserSecurityStampStore&amp;lt;MyUser&amp;gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note that I just chucked in TKey of string where it was required. When you're writing your store you should take time to make sure your TKey is being passed around properly.  All interfaces in the Identity library have &lt;code&gt;IInterface&amp;lt;TUser&amp;gt; : IInterface&amp;lt;TUser, string&amp;gt;&lt;/code&gt; and &lt;code&gt;IInterface&amp;lt;TUser, TKey&amp;gt;&lt;/code&gt; versions.&lt;/p&gt;

&lt;h4&gt;IUserPasswordStore&lt;/h4&gt;

&lt;p&gt;This requires you to implement the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#region PasswordStore
public Task&amp;lt;string&amp;gt; GetPasswordHashAsync(MyUser user)
{
    return Task.Factory.StartNew&amp;lt;string&amp;gt;(() =&amp;gt;
    {
        using (var db = new EfDbContext())
        {
            return FindUser(user.Id.ToString(), FindKeyType.Id).PasswordHash;
        }
    });
}

public Task&amp;lt;bool&amp;gt; HasPasswordAsync(MyUser user)
{
    return Task.Factory.StartNew&amp;lt;bool&amp;gt;(() =&amp;gt;
    {
        using (var db = new EfDbContext())
        {
            return !string.IsNullOrEmpty(db.Users.Find(user.Id).PasswordHash);
        }
    });
}

public Task SetPasswordHashAsync(MyUser user, string passwordHash)
{
    return Task.Factory.StartNew(() =&amp;gt;
    {
        user.PasswordHash = passwordHash;
    });
}
#endregion
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again these are awful store methods just written to get something working. &lt;strong&gt;Don't Use These!&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;IUserEmailStore&lt;/h3&gt;

&lt;p&gt;Implementing the following methods:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#region EmailStore
public Task&amp;lt;MyUser&amp;gt; FindByEmailAsync(string email)
{
    return Task&amp;lt;MyUser&amp;gt;.Factory.StartNew(() =&amp;gt;
    {
        using (var db = new EfDbContext())
        {
            User userDb = db.Users.First(u =&amp;gt; u.Email == email);
            return ToMyUser(userDb);
        }
    });
}

public Task&amp;lt;string&amp;gt; GetEmailAsync(MyUser user)
{
    return Task&amp;lt;string&amp;gt;.Factory.StartNew(() =&amp;gt; return user.Email);
}

public Task&amp;lt;bool&amp;gt; GetEmailConfirmedAsync(MyUser user)
{
    return Task&amp;lt;bool&amp;gt;.Factory.StartNew(() =&amp;gt; return true);
}

public Task SetEmailAsync(MyUser user, string email)
{
    return Task.Factory.StartNew(() =&amp;gt; user.Email = email);
}

public Task SetEmailConfirmedAsync(MyUser user, bool confirmed)
{
    throw new NotImplementedException();
}
#endregion
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This doesn't implement email confirmation properly but this is where you'd do so if your site is using it.&lt;/p&gt;

&lt;p&gt;I won't show full implementations for all the interfaces here, because the way they're implemented is rubbish and you can get Visual Studio to tell you what you should be implementing (anyone could write better methods than these!).&lt;/p&gt;

&lt;p&gt;The full code for my (&lt;strong&gt;really, really bad&lt;/strong&gt;) user store &lt;a href="http://eliot-jones.com/Code/asp-identity/MyUserStore.cs" title="Code file on my site"&gt;is here&lt;/a&gt;. As you can see most of it is not implemented yet since a lot of these methods are not used if you remove 2 factor / claims-based auth.&lt;/p&gt;

&lt;p&gt;The following 2 interfaces:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;IUserLockoutStore&amp;lt;MyUser, string&amp;gt;,
IUserTwoFactorStore&amp;lt;MyUser, string&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Must be implemented even if you're not using lockouts (you should) or 2 factor auth. You can just use the method returning &lt;code&gt;bool&lt;/code&gt; to tell the user/sign-in manager they're not enabled, like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public Task&amp;lt;bool&amp;gt; GetTwoFactorEnabledAsync(MyUser user)
{
    return Task.Factory.StartNew&amp;lt;bool&amp;gt;(() =&amp;gt; false);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Next Post&lt;/h3&gt;

&lt;p&gt;This post couldn't grow much longer and still be readable so the next two classes are discussed in the &lt;a href="http://eliot-jones.com/2014/10/asp-identity-2-0-p2" title="Next Page"&gt;next post&lt;/a&gt;. Once you've implemented all the interfaces on your store to your satisfaction &lt;a href="http://eliot-jones.com/2014/10/asp-identity-2-0-p2" title="Next Page"&gt;continue reading&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/10/asp-identity-2-0</guid>
      <pubDate>Sat, 11 Oct 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Minify Json using JSON.NET</title>
      <link>https://eliot-jones.com/2014/9/minify-json-net</link>
      <description>

&lt;p&gt;In my current project I'm using Json stored in the SQL Server database to replicate the storage capability of the browser Session but allowing the data to persist on the user reloading/leaving the page.&lt;/p&gt;

&lt;p&gt;One of the challenges is to store the serialized object in as few characters as possible while preserving meaning. &lt;/p&gt;

&lt;p&gt;Without touching the settings, Json.Net stores the strings without extraneous whitespace, but even serializing a fairly small aggregate object can use a lot of characters.This post details a couple of the features I've used to minimise the number of characters.&lt;/p&gt;

&lt;h3&gt;Store Booleans as Integers in Json&lt;/h3&gt;

&lt;p&gt;JSON.NET supports custom conversions using a class which inherits from JsonConverter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class BooleanConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(bool).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer,
        object value, JsonSerializer serializer)
    {
        bool? source = value as bool?;
        if (source == null) { return; }

        int valueAsInt = ((bool)source) ? 1 : 0;

        writer.WriteValue(valueAsInt);
    }

    public override object ReadJson(JsonReader reader, Type objectType,
        object existingValue, JsonSerializer serializer)
    {
        bool returnValue = (Convert.ToInt32(reader.Value) == 1);

        return returnValue;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This converter will store booleans as 1 and 0 rather than true and false; this saves 3 and 4 characters respectively.&lt;/p&gt;

&lt;h3&gt;Shorten Field and Property Names&lt;/h3&gt;

&lt;p&gt;By using the built in &lt;code&gt;[JsonProperty("Name")]&lt;/code&gt; we can save space in the serialized object. If we define one letter aliases for our properties we save a lot of space, especially when serializing an array of objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[JsonProperty("b")]
public bool IsAThing { get; set; } 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the full object has &lt;code&gt;IsAThing = false&lt;/code&gt; the string representing the serialized object stores this as &lt;code&gt;"b":0&lt;/code&gt; which is the shortest representation possible (unless you set the default value to false and only serialize where the boolean value is true).&lt;/p&gt;

&lt;h3&gt;Serializing an HtmlString&lt;/h3&gt;

&lt;p&gt;This isn't a space saving tip but where you need &lt;code&gt;HtmlString&lt;/code&gt;s to be serialized and deserialized you can use the converter below:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class HtmlStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(IHtmlString).IsAssignableFrom(objectType);
    }

    public override void WriteJson(JsonWriter writer, 
        object value, JsonSerializer serializer)
    {
        IHtmlString source = value as IHtmlString;
        if (source == null) { return; }            
        writer.WriteValue(source.ToString());
    }

    public override object ReadJson(JsonReader reader, Type objectType, 
        object existingValue, JsonSerializer serializer)
    {
        return new HtmlString((string)reader.Value);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With thanks to this &lt;a href="http://stackoverflow.com/questions/11350392/how-do-i-serialize-ihtmlstring-to-json-with-json-net" title="StackOverflow answer for serializing HtmlString"&gt;StackOverflow answer&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/9/minify-json-net</guid>
      <pubDate>Thu, 25 Sep 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Simple Introduction to MVC Ajax (Post 3)</title>
      <link>https://eliot-jones.com/2014/9/mvc-ajax-3</link>
      <description>

&lt;p&gt;Now we have partial views loading forms using Ajax and we can call controller methods using Ajax it's time to put everything together.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/Cat.jpg" alt="A picture of a cat." /&gt;&lt;/p&gt;

&lt;p&gt;We're going to start with a blank scenario to make it easier to follow. This makes this a very long post but it puts together everything we learned.&lt;/p&gt;

&lt;h3&gt;Code files&lt;/h3&gt;

&lt;p&gt;I managed to coerce PHP into creating a new route on my website. You can see the full code for the classes/views in this demo as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/Cat.cs"&gt;Cat.cs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/CatController.cs"&gt;CatController.cs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/Grudge.cs"&gt;Grudge.cs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/GrudgeController.cs"&gt;GrudgeController.cs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/Details.cshtml"&gt;Details.cshtml&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/_Create.cshtml"&gt;_Create.cshtml&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://eliot-jones.com/Code/mvc-ajax/_GrudgesForCat.cshtml"&gt;_GrudgesForCat.cshtml&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Setting up the test environment&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://meowgifs.com/wp-content/uploads/2013/10/boom-kitten.gif" title="Obligatory cat gif"&gt;Cats&lt;/a&gt; are spiteful creatures, full of barely concealed malice. It's one of their most loveable qualities, let's make a view to show the details of our cat and the grudges it holds.&lt;/p&gt;

&lt;p&gt;Let's add a class to represent our cat (Pocos/Cat.cs):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Cat
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int AngerLevel { get; set; }
    public DateTime BirthDate { get; set; }

    public List&amp;lt;Grudge&amp;gt; Grudges { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where the Grudge class is represented by the following (Pocos/Grudge.cs):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Grudge
{
    public int Id { get; set; }
    public string TargetName { get; set; }
    public string Reason { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To view the details of our cat we need a controller. In this demo I'm using the Session as our backing data store. This is terrible and should never be done, however this isn't about how to data bind. Add the controller (Controllers/CatController.cs):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ActionResult Details()
{
    Cat cat = new Cat
    {
        Id = 1,
        BirthDate = new DateTime(2005, 10, 3),
        Name = "Mr. Tibbles",
        AngerLevel = 100,
        Grudges = new List&amp;lt;Grudge&amp;gt; { 
            new Grudge 
            { 
                Id = 25, 
                TargetName = "All Humans" , 
                Reason =  "Opposable thumbs" 
            } 
        }
    };
    Session["Cat"] = cat;

    return View(cat);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally a view for our cat, unfortunately the syntax highlighter mangles this code. We won't worry about showing Grudges here (Views/Cat/Details.cshtml):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model SandboxMvc.Pocos.Cat
&amp;lt;h2&amp;gt;Cat&amp;lt;/h2&amp;gt;&amp;lt;div&amp;gt;
    &amp;lt;dl class="dl-horizontal"&amp;gt;
        &amp;lt;dt&amp;gt;@Html.DisplayNameFor(model =&amp;gt; model.Name)&amp;lt;/dt&amp;gt;
        &amp;lt;dd&amp;gt;@Html.DisplayFor(model =&amp;gt; model.Name)&amp;lt;/dd&amp;gt;
        &amp;lt;dt&amp;gt;@Html.DisplayNameFor(model =&amp;gt; model.AngerLevel)&amp;lt;/dt&amp;gt;
        &amp;lt;dd&amp;gt;@Html.DisplayFor(model =&amp;gt; model.AngerLevel)&amp;lt;/dd&amp;gt;
        &amp;lt;dt&amp;gt;@Html.DisplayNameFor(model =&amp;gt; model.BirthDate)&amp;lt;/dt&amp;gt;
        &amp;lt;dd&amp;gt;@Html.DisplayFor(model =&amp;gt; model.BirthDate)&amp;lt;/dd&amp;gt;
&amp;lt;/dl&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;The Book of Grudges&lt;/h3&gt;

&lt;p&gt;We need a partial view to display our cat's grudges. &lt;/p&gt;

&lt;p&gt;We're going to include an &lt;code&gt;Html.Action&lt;/code&gt; in our view so we need a method in the Controller (Controllers/GrudgeController.cs) to call:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public PartialViewResult _GrudgesForCat(int id)
{
    List&amp;lt;Grudge&amp;gt; grudges = ((Cat)Session["Cat"]).Grudges;
    return PartialView(grudges);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We also need to include the Partial View in our Details view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div id="BookOfGrudges"&amp;gt;
    @Html.Action(actionName: "_GrudgesForCat", 
    controllerName: "Grudge", 
    routeValues: new { id = Model.Id })
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And finally we need a PartialView for this action (Views/Grudge/_GrudgesForCat.cshtml):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model List&amp;lt;SandboxMvc.Pocos.Grudge&amp;gt;
@for (int i = 0; i &amp;lt; Model.Count; i++)
{
    @Html.DisplayFor(m =&amp;gt; m[i].TargetName) &amp;lt;br/&amp;gt;
    @Html.DisplayFor(m =&amp;gt; m[i].Reason) &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When you run this you should be able to see a representation of the Cat we created, with associated Grudge(s).&lt;/p&gt;

&lt;h3&gt;The list grows&lt;/h3&gt;

&lt;p&gt;It would be nice to create new grudges (if you're a cat). We'd like to do that without leaving our page.&lt;/p&gt;

&lt;p&gt;We're going to include a partial view of a form to create new grudges. Modify the Details view to add the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div id="AddToGrudgeList"&amp;gt;
    @Html.Action(actionName: "_Create",
    controllerName: "Grudge",
    routeValues: new { id = Model.Id });
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We then need the backing Action on our Grudge controller for both Get and Post:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public PartialViewResult _Create (int id) 
{
    return PartialView();
}

[HttpPost]
public ActionResult _Create(Grudge model)
{
    ((Cat)Session["Cat"]).Grudges.Add(model);
    return RedirectToAction(actionName: "_GrudgesForCat", routeValues: new { id = 9 });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The create view is a fairly long form but look a bit like this. It's important that you &lt;strong&gt;specify the action name and controller&lt;/strong&gt; (Views/Grudge/_Create.cshtml):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model SandboxMvc.Pocos.Grudge
@using (Html.BeginForm(actionName: "_Create", controllerName: "Grudge"))
{
    @Html.AntiForgeryToken()
    &amp;lt;div class="form-horizontal"&amp;gt;
        &amp;lt;h4&amp;gt;Grudge&amp;lt;/h4&amp;gt;
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        &amp;lt;div class="form-group"&amp;gt;
            [FORM INPUTS]
        &amp;lt;/div&amp;gt;

        &amp;lt;input type="submit" value="Create" class="btn btn-default" /&amp;gt;
    &amp;lt;/div&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we click to create a grudge the action "_Create" is called and the Grudge is added to the list. However the result opens in a new page rather than updating our Book of Grudges.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/postback.png" alt="The Create button opens a new blank page" /&gt;&lt;/p&gt;

&lt;h3&gt;Make it more... Ajax&lt;/h3&gt;

&lt;p&gt;Everything we've seen so far has been normal MVC using HTML only. All actions are called on the server by performing a full post/get.&lt;/p&gt;

&lt;p&gt;Make sure you have Ajax installed in your project (see post 1).&lt;/p&gt;

&lt;p&gt;In order to dynamically update our Book of Grudges using Ajax we need to make one change, change the &lt;code&gt;@Html.BeginForm&lt;/code&gt; to &lt;code&gt;@Ajax.BeginForm&lt;/code&gt; (Views/Grudges/_Create.cshtml):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model SandboxMvc.Pocos.Grudge
@using (Ajax.BeginForm(actionName: "_Create", 
    controllerName: "Grudge", 
    ajaxOptions: new AjaxOptions { UpdateTargetId = "BookOfGrudges" }))
{
    @Html.AntiForgeryToken()
    &amp;lt;div class="form-horizontal"&amp;gt;
        [FORM]  
        &amp;lt;input type="submit" value="Create" class="btn btn-default" /&amp;gt;
    &amp;lt;/div&amp;gt;
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That's it, now your Book of Grudges is updated using partial page updates.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/fulltimeinternet.png" alt="The Create button updates the same page" /&gt;&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Over the past 3 posts I've walked through how to get started with Ajax in MVC 5. This series addresses some of the main pain points involved in getting this working with Partial Views and forms.&lt;/p&gt;

&lt;p&gt;The Ajax included in MVC makes it possible to have a fully featured Ajax application without having to touch a line of Javascript, a positive because js is a language only people with a true passion for ducks could love.&lt;/p&gt;

&lt;p&gt;If you have any questions or tips please add a comment; I'd be interested to hear the many, many things I got wrong in this series.&lt;/p&gt;

&lt;p&gt;The solution view of the finished project is shown here:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/solutionview.png" alt="The full project layout"/&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Cat picture from &lt;a href="http://en.wikipedia.org/wiki/Cat#mediaviewer/File:Large_Siamese_cat_tosses_a_mouse.jpg"&gt;Wikipedia&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/9/mvc-ajax-3</guid>
      <pubDate>Tue, 16 Sep 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Simple Introduction to MVC Ajax (ASP.NET MVC 5)</title>
      <link>https://eliot-jones.com/2014/9/mvc-ajax</link>
      <description>

&lt;p&gt;The jQuery Ajax built into ASP.NET MVC is very powerful but it's hard to know exactly where to start. This tutorial is a result of a few hours investigation so it's written from the point of view of a beginner.&lt;/p&gt;

&lt;p&gt;I intend to upload code samples at some point but I need to add a code hosting feature to my website.&lt;/p&gt;

&lt;h3&gt;Setting up our test environment&lt;/h3&gt;

&lt;p&gt;We're going to use a very simple example to work with only the details we need. As always we're using a dog class, here's a &lt;a href="http://en.wikipedia.org/wiki/Chow_Chow#mediaviewer/File:03_Bokeh_the_Chow.jpg" title="Dog picture from Wikipedia"&gt;picture of a dog&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/chowchow.jpg" alt="A picture of a dog." /&gt;&lt;/p&gt;

&lt;p&gt;The first thing we need to do is set our project up with Ajax. Right click your project and open the Nuget Package Manager. Search for "Ajax" and install the Microsoft jQuery Unobtrusive Ajax package.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/installajax.png" alt="Install the Microsoft jQuery Unobtrusive Ajax package" /&gt;&lt;/p&gt;

&lt;p&gt;This adds the &lt;code&gt;jquery.unobtrusive-ajax.min.js&lt;/code&gt; file to our Scripts folder. We need to include this in our webpage. The easiest way to do this is to add it to our BundleConfig class (in the App_Start folder):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
           "~/Scripts/jquery-{version}.js", 
           "~/Scripts/CustomScripts/StickyFooter.js",
           "~/Scripts/jquery.unobtrusive-ajax.min.js"));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This should be included in your master _Layout page using &lt;code&gt;@Scripts.Render("~/bundles/jquery")&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Creating a test page&lt;/h3&gt;

&lt;p&gt;With the following dog class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Dog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And the following controller method (DogController.cs):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ActionResult Details()
{
    Dog dog = new Dog{Id = 7, Name = "Lord woofington",
        BirthDate = new DateTime(year: 2005, month: 06, day: 27)};
    return View(dog);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can quickly get a view to work with. Before we can navigate to the action we need a view. This is the view the Wizard created for the Dog class in &lt;code&gt;Views/Dog/Details.cshtml&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model JunkCode.Dog
&amp;lt;h2&amp;gt;Dog Details&amp;lt;/h2&amp;gt;
&amp;lt;div&amp;gt;
    &amp;lt;dl class="dl-horizontal"&amp;gt;
        &amp;lt;dt&amp;gt;@Html.DisplayNameFor(model =&amp;gt; model.Name)&amp;lt;/dt&amp;gt;
        &amp;lt;dd&amp;gt;@Html.DisplayFor(model =&amp;gt; model.Name)&amp;lt;/dd&amp;gt;
        &amp;lt;dt&amp;gt;@Html.DisplayNameFor(model =&amp;gt; model.BirthDate)&amp;lt;/dt&amp;gt;
        &amp;lt;dd&amp;gt;@Html.DisplayFor(model =&amp;gt; model.BirthDate)&amp;lt;/dd&amp;gt;
    &amp;lt;/dl&amp;gt;
&amp;lt;/div&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Our first simple Ajax call&lt;/h3&gt;

&lt;p&gt;The simplest thing we can do is call a controller method using an ActionLink. We add the following code to our view:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Ajax.ActionLink(linkText: "Call An Action", 
                    actionName: "Bark", 
                    ajaxOptions: new AjaxOptions { UpdateTargetId = "ajaxtarget", 
                                                    InsertionMode = InsertionMode.InsertAfter })

&amp;lt;div id="ajaxtarget"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some points:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-gb/library/dd264739.aspx" title="MSDN on Named Arguments"&gt;Named parameters&lt;/a&gt; using &lt;code&gt;[text]:&lt;/code&gt; have been a feature of Visual Studio since 2010 and are a nifty little feature to make your code more readable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This ActionLink presents a link with the given linkText and when clicked calls the Action (given by actionName) on the Dog Controller.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions(v=vs.118).aspx" title="MSDN on AjaxOptions"&gt;AjaxOptions&lt;/a&gt; allow you to modify the exact behaviour of the Ajax call.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We then need an Action on our Controller for our link to actually call:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public string Bark(){ 
    return "Woof!"; 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we click this the text "Woof!" is added to our &lt;code&gt;ajaxtarget&lt;/code&gt; div. Clicking repeatedly appends the text to our div.&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/actionlinkresult.png" alt="Calling the Action repeatedly results in 'Woof!Woof!Woof!' written to screen" /&gt;&lt;/p&gt;

&lt;h3&gt;Next Post&lt;/h3&gt;

&lt;p&gt;This is pretty nifty, but what else can we do?&lt;/p&gt;

&lt;p&gt;Go to the &lt;a href="/2014/09/mvc-ajax-2" title="Page 2"&gt;Next Post&lt;/a&gt; to find out about using PartialViews and Ajax Forms.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/9/mvc-ajax</guid>
      <pubDate>Sun, 14 Sep 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Simple Introduction to MVC Ajax (Post 2)</title>
      <link>https://eliot-jones.com/2014/9/mvc-ajax-2</link>
      <description>

&lt;p&gt;So far we have seen how to add a very simple ActionLink and attach actions. Now let's load a PartialView using Ajax. Also we want to load a partial view with a different model into our page.&lt;/p&gt;

&lt;h3&gt;Getting a Partial View using ActionLink&lt;/h3&gt;

&lt;p&gt;We're going to deal with an object a Dog could "own", so we create a collar class. Let's accessorize our dog with some fabulous collars / add an ActionLink to the &lt;code&gt;Dog/Details&lt;/code&gt; view &lt;strong&gt;(Details.cshtml)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Ajax.ActionLink(linkText: "Call An Action Returning a partial view",
    actionName: "GetCollarCreate",
    routeValues: new { id = @Model.Id },
    ajaxOptions: new AjaxOptions
    {
        UpdateTargetId = "ajaxpartialtarget",
        InsertionMode = InsertionMode.Replace
    })
&amp;lt;div id="ajaxpartialtarget"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can pass the Id of the dog in using RouteValues as normal. The InsertionMode.Replace is default so doesn't need to be defined explicitly, I'm just doing it because it doesn't hurt to be reminded. This ActionLink calls the following method on the Dog Controller &lt;strong&gt;(DogController.cs)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public ActionResult GetCollarCreate(int id){
    return RedirectToAction(actionName: "_Create", 
        controllerName: "Collar", 
        routeValues: new { id });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This then directs us to an action on our Collar Controller class &lt;strong&gt;(CollarController.cs)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[HttpGet]
public PartialViewResult _Create(int id){
    Collar collar = new Collar { DogId = id };
    return PartialView(viewName: "_Create", model: collar);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where our collar is a simple view model:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Collar
{
    public int DogId { get; set; }

    public string Color { get; set; }

    public bool HasTag { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We will create a more detailed view in the next part but for now we have this simple view &lt;strong&gt;(Create.cshtml)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model JunkCode.Collar
&amp;lt;div&amp;gt; Loaded the partial view for dog with Id = @Model.DogId &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we build and run this we get the result we want, the view is loaded using an Ajax request, the dog woofs for joy:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/partialviewresult.png" alt="The partial view loads in the div" /&gt;&lt;/p&gt;

&lt;h3&gt;Hiding the PartialView again&lt;/h3&gt;

&lt;p&gt;It would be nice to remove the partial view if we change our mind about whatever Action we're calling, I added this link in our &lt;code&gt;Collar/Create&lt;/code&gt; view &lt;strong&gt;(Create.cshtml)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Ajax.ActionLink(linkText: "Hide",
    actionName: "_HideCreate",
    ajaxOptions: new AjaxOptions
    { UpdateTargetId = "ajaxpartialtarget" })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This calls the Controller method &lt;strong&gt;(CollarControler.cs)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[HttpGet]
public void _HideCreate() { ; }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The coding of the UpdateTargetId into another view is kinda crappy, but I'm sure you can think of a way to improve it if it makes you incandescent with rage.&lt;/p&gt;

&lt;h3&gt;Loading a form in our PartialView&lt;/h3&gt;

&lt;p&gt;We modify the "GetCollarCreate" method in our Dog controller to return the results of our new Collar controller method &lt;strong&gt;(DogController.cs)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;return RedirectToAction(actionName: "_Create2",
        controllerName: "Collar",
        routeValues: new { id });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The _Create2 method returns a PartialView &lt;strong&gt;(CollarController.cs)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[HttpGet]
public PartialViewResult _Create2(int id)
{
    Collar collar = new Collar { DogId = id };
    return PartialView(viewName: "_Create2", model: collar);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;em&gt;Create2 view was created by the Scaffolding tool but looks a bit like this &lt;strong&gt;(&lt;/em&gt;Create2.cshtml)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@model Questions.JunkCode.Collar
@using(Html.BeginForm("_Create2", "Collar", new {}))
{
    @Html.AntiForgeryToken()

    &amp;lt;div class="form-horizontal"&amp;gt;
        @Html.ValidationSummary(true)
        &amp;lt;div class="form-group"&amp;gt;
            [MORE STUFF HERE...]
        &amp;lt;/div&amp;gt;

        &amp;lt;div class="form-group"&amp;gt;
        &amp;lt;div class="col-md-offset-2 col-md-10"&amp;gt;
            &amp;lt;input type="submit" value="Create" class="btn btn-default" /&amp;gt;
        &amp;lt;/div&amp;gt;

    &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
}
&amp;lt;div id="statusMessage"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can then define the _Create2 post method in our Collar Controller &lt;strong&gt;(CollarController.cs)&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[HttpPost]
public string _Create2(int id, Collar model)
{
    // Call some repository method to create the collar
    return "Collar Created!";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we load this controller we get the following result:&lt;/p&gt;

&lt;p&gt;&lt;img src="https://eliot-jones.com/images/mvcajax/partialform.png" alt="The partial view loads a form" /&gt;&lt;/p&gt;

&lt;h3&gt;Next Post&lt;/h3&gt;

&lt;p&gt;So far we've used an Ajax ActionLink and loaded an HTML form into our page using Ajax, how about getting the form to submit using Ajax? This is the tricky bit to get right and is the topic of the &lt;a href="http://eliot-jones.com/2014/09/mvc-ajax-3"&gt;next post&lt;/a&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/9/mvc-ajax-2</guid>
      <pubDate>Sun, 14 Sep 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Error Creating a DACPAC in Visual Studio 2013 from SQL Server 2014</title>
      <link>https://eliot-jones.com/2014/8/dacpac-error-visual-studio-2013</link>
      <description>

&lt;p&gt;Working on projects in your spare time is great because you're free to pursue every little diversion; it means you make no real progress with your actual project but you learn a lot.&lt;/p&gt;

&lt;p&gt;When I had to add a column to one of my database tables I decided to investigate creating a &lt;a href="http://sqlblog.com/blogs/jamie_thomson/archive/2014/01/18/dacpac-braindump.aspx" title="Everything You Need to Know about DacPacs"&gt;DACPAC&lt;/a&gt;(1). A DACPAC allows you to turn your existing database into a database project in Visual Studio which means your schema can be placed under source control. Changes can then be pushed to your database in a friendly wizard format.&lt;/p&gt;

&lt;p&gt;To create a DACPAC you right click on your existing database and choose &lt;em&gt;Extract Data Tier Application&lt;/em&gt; under tasks:&lt;/p&gt;

&lt;p&gt;&lt;img src="/images/dacpac/ExtractDacpac.png" alt="Right click Database, choose tasks." /&gt;&lt;/p&gt;

&lt;p&gt;The wizard then runs through the steps to create the DACPAC.&lt;/p&gt;

&lt;p&gt;Next create a new SQL Server Database project in your Visual Studio solution:&lt;/p&gt;

&lt;p&gt;&lt;img src="/images/dacpac/CreateDatabaseProject.png" alt="Screenshot of creating new Database Project"/&gt;&lt;/p&gt;

&lt;p&gt;Then right click the project and choose &lt;em&gt;Import -&gt; Data-Tier Application&lt;/em&gt;. Choose the dacpac you extracted from SQL Server and then click &lt;em&gt;Start&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;If everything goes according to plan you should successfully import the dacpac. If this is the case, &lt;a href="http://sqlblog.com/blogs/jamie_thomson/archive/2014/01/18/dacpac-braindump.aspx" title="Everything You Need to Know about DacPacs"&gt;use this post&lt;/a&gt; to learn what you can do with your dacpac.&lt;/p&gt;

&lt;p&gt;However I got the following error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Internal Error. The database platform service with type Microsoft.Data.Tools.
Schema.Sql.Sql120DatabaseSchemaProvider is not valid. You must make sure the
service is loaded, or you must provide the full type name of a valid database
platform service.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I'm using Visual Studio 2013 Express with SQL Server 2014 Express (I'm poor :) ), after a bit of searching I found the problem was an outdated version of the Data Tools. To fix this do the following, click &lt;em&gt;Tools -&gt; Extensions and Updates&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;img src="/images/dacpac/UpdateVisualStudio.png" alt="Screenshot of updating Visual Studio"/&gt;&lt;/p&gt;

&lt;p&gt;Then choose &lt;em&gt;Updates&lt;/em&gt; from the window. You should see an update with a name similar to SQL Server Data Tools in &lt;em&gt;Product Updates&lt;/em&gt; (I've already updated mine so it's not shown):&lt;/p&gt;

&lt;p&gt;&lt;img src="/images/dacpac/UpdateVisualStudioDataTools.png" alt="Screenshot of updating Visual Studio 2013 data tools"/&gt;&lt;/p&gt;

&lt;p&gt;Hopefully this fixes your issue.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Thanks to Steve Wade for telling me about dacpacs.&lt;/li&gt;
&lt;/ol&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/dacpac-error-visual-studio-2013</guid>
      <pubDate>Sun, 31 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>ASP.NET Identity 1.0 - Database First</title>
      <link>https://eliot-jones.com/2014/8/asp-identity-database-first</link>
      <description>

&lt;p&gt;&lt;em&gt;Note: This tutorial applies to Identity 1.0 which is the previous version of ASP.NET Identity. I have a newer post on the same subject&lt;/em&gt; &lt;a href="http://eliot-jones.com/2014/10/asp-identity-2-0" title="New Tutorial"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you've read my previous posts you probably know I'm working on some EF Database first stuff, this seems to be the least popular way to use EF but to me seems like a common business use-case for it.&lt;/p&gt;

&lt;p&gt;The MVC template in Visual Studio comes with the new Asp.NET Identity system built in, but it's designed to be used with Code First. This leads to people asking &lt;a href="http://stackoverflow.com/questions/20668328/using-asp-net-identity-database-first-approch" title="StackOverflow Question"&gt;how to use Identity with Database First?&lt;/a&gt; The suggested soultion is to use the table structure provided when you use Code First and port it to your pre-existing database.&lt;/p&gt;

&lt;p&gt;This seemed like an unpleasant approach to me (and a lot of work), especially because I think the database layout for those tables is kinda sucky. This is when it occurred to me that we're basically trying to implement Identity without using what the documentation thinks of as Entity Framework.&lt;/p&gt;

&lt;p&gt;When you Google how to do that, you get &lt;a href="http://blog.markjohnson.io/exorcising-entity-framework-from-asp-net-identity/"&gt;this great post&lt;/a&gt; from Mark Johnson. You can follow his approach and just substitute his use of Dapper for use of Entity Framework. for instance:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public Task CreateAsync(User user)
{
    if (user == null)
    {
        throw new ArgumentNullException("user was null");
    }

    return Task.Factory.StartNew(() =&amp;gt;
        {
            db.Users.Add(user);
            db.SaveChanges();
        });
}

public Task DeleteAsync(User user)
{
    User checkUser = db.Users.Find(user.Id);

    if (user == null || checkUser == null)
    {
        throw new ArgumentNullException("user was null");
    }

    return Task.Factory.StartNew(() =&amp;gt;
    {
        db.Users.Remove(user);
        db.SaveChanges();
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where &lt;code&gt;db&lt;/code&gt; is your DbContext. Hopefully this helps you as much as it helped me, it's a far nicer solution than rolling your own Auth system.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/asp-identity-database-first</guid>
      <pubDate>Sat, 16 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>AOB (1)</title>
      <link>https://eliot-jones.com/2014/8/weird-csharp-equality</link>
      <description>

&lt;p&gt;AOB here is used to mean 'any other business' rather than the Swedish pop group Ace of Base or the Accessory olfactory bulb.&lt;/p&gt;

&lt;p&gt;This a blog post to summarise a few things which don't make a whole blog post in their own right.&lt;/p&gt;

&lt;h3&gt;MarkdownPad 2&lt;/h3&gt;

&lt;hr /&gt;

&lt;p&gt;For those of you who don't know, &lt;a href="http://daringfireball.net/projects/markdown/" title="John Gruber Markdown"&gt;markdown&lt;/a&gt; is readable HTML syntax so you can write properly structured HTML in a human friendly way.&lt;/p&gt;

&lt;p&gt;The conversion to HTML is then performed by the markdown library in your language of choice using a mega-regex.&lt;/p&gt;

&lt;p&gt;The format is used by sites like StackOverflow and GitHub for comments/text and I also use it for my blog posts.&lt;/p&gt;

&lt;p&gt;So after Scott Hanselmann mentioned it in his blog I downloaded &lt;a href="https://markdownpad.com/" title="Official Download Site"&gt;MarkdownPad 2&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Beforehand I was using Notepad++ to write Markdown and it was horribly long winded due to the poor choice of application. Now writing Markdown is about as easy as using Word (so go download it if you use markdown).&lt;/p&gt;

&lt;h3&gt;Ceci n'est pas une pipe (trans. C# Equality is Weird)&lt;/h3&gt;

&lt;hr /&gt;

&lt;p&gt;I was trying to write a method to find where properties had been set back to their default value on an object. Reflection seemed like an obvious choice since I wanted a one-size fits all method.&lt;/p&gt;

&lt;p&gt;I ran into a very odd problem where C# was convinced that &lt;code&gt;0 == 0&lt;/code&gt; is false, or so I thought. The problem was based on my lack of understanding of how the equality operator actually works, but provided a good learning experience.&lt;/p&gt;

&lt;p&gt;The actual comparison that troubled me could be simplified to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;int num = 0;
object num1 = num;
object num2 = num;
num1 == num2 //false
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;See &lt;a href="http://stackoverflow.com/questions/20642202/why-is-object0-object0-different-from-object0-equalsobject0" title="Question"&gt;this StackOverflow question&lt;/a&gt; for the answer. Basically for the &lt;code&gt;object&lt;/code&gt; type, &lt;code&gt;==&lt;/code&gt; checks that both objects occupy the same location in memory (ReferenceEquals).&lt;/p&gt;

&lt;p&gt;For the example above the integer is boxed (converted to the reference type &lt;code&gt;object&lt;/code&gt;) in two different locations so &lt;code&gt;==&lt;/code&gt; returns false since they occupy different locations in memory.&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;Equals(num1, num2)&lt;/code&gt; is used instead, the method returns true.&lt;/p&gt;

&lt;p&gt;This lead to the even more interesting problem posed by Eric Lippert in the comment on the question. Why does the following occur (this is output from Immediate Window in Visual Studio)?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;short myshort = 0;
0
int myint = 0;
0

myshort.Equals(myint)
false
myint.Equals(myshort)
true
myint == myshort
true
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the full explanation see &lt;a href="http://blog.coverity.com/2014/01/13/inconsistent-equality/#.U-dYYfldXQg" title="Eric Lippert on inconsistent equality"&gt;his post on Coverity&lt;/a&gt; which explains what's going on in detail. There's also this &lt;a href="http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx" title="MSDN Blog Post by Jon skeet"&gt;post by Jon Skeet&lt;/a&gt; for further reading.&lt;/p&gt;

&lt;h3&gt;ActionLink MVC&lt;/h3&gt;

&lt;hr /&gt;

&lt;p&gt;Just for future reference here's an ActionLink from MVC4:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Html.ActionLink("Edit", "Edit", "ControllerName", 
    routeValues: new { first="duck", @Model.Id, other = "rgs", thing = @Model.Id}, 
    htmlAttributes: new { @class = "cssclass" })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first parameter is link text, second is Action Method and third is controller name.&lt;/p&gt;

&lt;p&gt;Route values are added as an anonymous type. They are compared against the defaults in RouteConfig.cs and any that do not match the pattern will be added in the querystring. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Will map 'other', 'first' and 'thing' into the querystring, whereas the unnamed value will be the id.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{more url here}/Edit/-2147483647?first=duck&amp;amp;other=rgs&amp;amp;thing=-2147483647
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Sea Kayaking&lt;/h3&gt;

&lt;hr /&gt;

&lt;p&gt;Just in case concerned readers were thinking I spent my entire time coding, I've uploaded a couple of pictures from my recent kayaking trip to Old Harry Rocks. I've got a sit on-top kayak &lt;a href="http://www.gosea.co.uk/kayaks/#.U-dvu_ldXQg" title="GoSea Kayaks"&gt;from GoSea&lt;/a&gt; which is great for exploring the coast but heavy-going once the wind picks up. &lt;/p&gt;

&lt;p&gt;&lt;img src="/images/aob/setting-sail.JPG" alt="Setting Off For Old Harry Rocks" /&gt;&lt;/p&gt;

&lt;p&gt;In total the distance was about 7km there and back, you can see Old Harry &lt;a href="/images/aob/old-harry-rocks.JPG"&gt;in the background here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I've also recently taken it to Lulworth and paddled along to Durdle Door which was great and highly recommended if you get a chance.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/weird-csharp-equality</guid>
      <pubDate>Sun, 10 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Metadata For Entity Framework MVC - Database First</title>
      <link>https://eliot-jones.com/2014/8/metadata-ef-database-first</link>
      <description>

&lt;p&gt;The model validation in MVC is brilliant but for best usage requires Attributes to be added to your model.&lt;/p&gt;

&lt;p&gt;If you use Entity Framework to generate your model you are given classes which will be overwritten when you regenerate the model as seen in the warning automatically appended to your file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;//------------------------------------------------------------------------------
// &amp;lt;auto-generated&amp;gt;
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// &amp;lt;/auto-generated&amp;gt;
//------------------------------------------------------------------------------
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The way around this is to use a Metadata Class. Because an Entity Framework model class is defined as a partial class you can extend it. &lt;/p&gt;

&lt;p&gt;For the following model class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;namespace Project.EntityFramework
{
    using System;
    using System.Collections.Generic;

    public partial class Dog
    {
        public Dog()
        {
            this.Collars = new HashSet&amp;lt;Collar&amp;gt;();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection&amp;lt;Collar&amp;gt; Collars { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can extend the partial class as long as your class is &lt;strong&gt;in the same namespace&lt;/strong&gt;. The specific metadata file is shown:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.ComponentModel.DataAnnotations;

namespace Project.EntityFramework
{
    [MetadataType(typeof(Dog.DogMetadata))]
    public partial class Dog
    {
        internal sealed class DogMetadata
        {
            #pragma warning disable 0649
            private DogMetadata() { }

            [Editable(false)]
            public object Id { get; set; }

            [Display(Name = "Woofy Name")]
            [Required(ErrorMessage = "Name Is Required", AllowEmptyStrings = false)]
            [MinLength(10)]
            public object Name;

            [Editable(false)]
            public object Collars { get; set; }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This Metadata file &lt;code&gt;Dog.Metadata.cs&lt;/code&gt; is in the same folder and namespace (&lt;em&gt;folder is not always equal to namespace but by default in visual studio&lt;/em&gt;) as the model &lt;code&gt;DatabaseModel.edmx&lt;/code&gt;. Metadata files have &lt;code&gt;.metadata&lt;/code&gt; in the name by convention.&lt;/p&gt;

&lt;p&gt;The fact metadata is being used is declared with the attribute:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[MetadataType(typeof(Dog.DogMetadata))]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Where the type is the metadata class you're using. Therefore it is possible to define the metadata class separately in another file but it's best to keep everything together.&lt;/p&gt;

&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx" title="MSDN Documentation"&gt;standard MVC data annotations&lt;/a&gt; may used as usual on your metadata class.&lt;/p&gt;

&lt;p&gt;Notes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The constructor for the internal metadata file is private.&lt;/li&gt;
&lt;li&gt;The data type of the metadata property or field doesn't matter, you can use &lt;code&gt;object&lt;/code&gt; regardless of the underlying type.&lt;/li&gt;
&lt;li&gt;It doesn't matter if the target property is defined as a property or field, only the name matters. We've used a property for Id and a field for Name.&lt;/li&gt;
&lt;li&gt;If you use fields in your metadata class (for example Name) you will get compiler warnings for the field never being assigned to. You can disable these with &lt;code&gt;#pragma warning disable 0649&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/metadata-ef-database-first</guid>
      <pubDate>Sat, 09 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>jQuery Fit Footer To Window Height</title>
      <link>https://eliot-jones.com/2014/8/jQuery-Screen-Height</link>
      <description>

&lt;p&gt;Sometimes your content just doesn't fit the window height, for exampling when you're styling a page with placeholder content. Or, for a short post like this. &lt;/p&gt;

&lt;p&gt;That's why I use the script below for making sure my footer appears at the bottom of pages where the content is shorter than the window:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function AdjustWindowHeight()
{
    var requiredHeight = $(window).height() - $("#footer").height();
    $('#wrap').css('min-height', requiredHeight);
}

$(window).on("resize", AdjustWindowHeight);

$(function () {
    AdjustWindowHeight();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or the minified version:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function F(){var a=$(window).height()-$("#footer").height(); $("#wrap").css("min-height",a)}$(window).on("resize",F);$(function(){F()});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All you need is a div containing all your footer content and and wrap div containing all other content:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;body&amp;gt;
&amp;lt;div id="wrap"&amp;gt;Content&amp;lt;/div&amp;gt;
&amp;lt;div id="footer"&amp;gt;Footer :)&amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/jQuery-Screen-Height</guid>
      <pubDate>Fri, 08 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>JSON.NET</title>
      <link>https://eliot-jones.com/2014/8/json-net-tutorial</link>
      <description>

&lt;p&gt;&lt;a href="http://james.newtonking.com/json" title="JSON.NET official page"&gt;JSON.NET&lt;/a&gt; by James Newton-King is &lt;em&gt;the&lt;/em&gt;  library for working with JSON in .NET. The following is a small guide for using JSON.NET. It is in no way a substitute for the &lt;a href="http://james.newtonking.com/json/help/index.html" title="Official JSON.Net Documentation"&gt;full documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To follow along obtain the JSON.NET package using NuGet and the &lt;strong&gt;Newtonsoft.Json&lt;/strong&gt; dll will be added to your project's references. Alternatively download from the official website and add the reference manually.&lt;/p&gt;

&lt;h3&gt;Serialize An Object And De-serialize&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Serialization is the process of translating data structures or object state into a format that can be stored&lt;/em&gt; - Wikipedia.&lt;/p&gt;

&lt;p&gt;We will start our investigation with a very simple C# object and continue from there. As always, we are using the Dog class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Dog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Breed { get; set; }
    public DateTime Birthday { get; set; }

    public int CalculateAgeInDays()
    {
        return (DateTime.Now - Birthday).Days;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is very simple class but might mirror something you need to serialize.&lt;/p&gt;

&lt;p&gt;To start, let's create a dog and convert it to a string of Json (which I'll stop capitalising because it's a pain to type).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Dog dog = new Dog
{
    Id = 4,
    Breed = "Labradoodle",
    Name = "Baron Von Lassie",
    Birthday = Convert.ToDateTime("2013-01-07"),
};
string json = JsonConvert.SerializeObject(dog);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The string that we obtain is 'minified':&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{"Id":4,"Name":"Baron Von Lassie","Breed":"Labradoodle","Birthday":"2013-01-07T00:00:00"}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see all extraneous whitespace and extra line-breaks have been removed. This is ideal for data transfer objects such as a response from a Web Service, however if we're trying to present our data in a human readable way it's nicer to set &lt;code&gt;Formatting.Indented&lt;/code&gt; like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;string json = JsonConvert.SerializeObject(dog, Formatting.Indented);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This gives the neater response:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  "Id": 4,
  "Name": "Baron Von Lassie",
  "Breed": "Labradoodle",
  "Birthday": "2013-01-07T00:00:00"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This reveals that more complex datatypes like DateTime are stored as strings in Json. Json.NET uses the &lt;a href="http://en.wikipedia.org/wiki/ISO_8601" title="ISO 8601 on Wikipedia"&gt;ISO standard 8601&lt;/a&gt; for dates, you can read more about why on &lt;a href="http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx" title="Scott Hanselman on JSON dates"&gt;Scott Hanselman's blog&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We can get our dog back again using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Dog lassie = JsonConvert.DeserializeObject&amp;lt;Dog&amp;gt;(json);
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Serialize A More Complex Object And Serializing To A File&lt;/h3&gt;

&lt;p&gt;We can now create and retrieve a Json representation of our dog, but how about persisting it somewhere on our hard-drive? &lt;/p&gt;

&lt;p&gt;First let's add a list of collars to our Dog object, this will show an object with an object array in Json:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Collar
{
    public int Id { get; set; }
    public string Color { get; set; }
    public bool HasTag { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The collars list property is added to the dog class and the dog now has 2 collars using nice collection initialization:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;List&amp;lt;Collar&amp;gt; collars = new List&amp;lt;Collar&amp;gt;
{
    new Collar { Id = 1, Color = "Red", HasTag = true },
    new Collar { Id = 2, Color = "Pink", HasTag = false }
};
dog.Collars = collars;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;JsonConvert from the previous example provides a simple way to write and read to/from a string. This provides a wrapper to &lt;code&gt;JsonSerializer&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The simplest way to serialize to a file is shown:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;string folder = "C:\\Test\\";
using (StreamWriter file = File.CreateText(folder + "dog.json"))
{
    JsonSerializer serializer = new JsonSerializer();

    serializer.Formatting = Formatting.Indented;

    serializer.Serialize(file, dog);
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The text file then contains our dog object, preserved forever(!):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  "Id": 4,
  "Name": "Baron Von Lassie",
  "Breed": "Labradoodle",
  "Collars": [
    {
      "Id": 1,
      "Color": "Red",
      "HasTag": true
    },
    {
      "Id": 2,
      "Color": "Pink",
      "HasTag": false
    }
  ],
  "Birthday": "2013-01-07T00:00:00"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The dog can be retrieved from the file as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using (StreamReader file = File.OpenText(folder + "dog.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    Dog lassie = (Dog)serializer.Deserialize(file, typeof(Dog));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Serialization and deserialization can be thought of as hydration/dehydration, dehydrate your dog to store it and stop it rotting, then rehydrate it to play in the park with.&lt;/p&gt;

&lt;h3&gt;Json Settings&lt;/h3&gt;

&lt;p&gt;We've already seen one serialization setting, &lt;code&gt;Formatting.Indented&lt;/code&gt; in the examples above. There are many more serialization options for which &lt;a href="http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm" title="Serialization Settings"&gt;the documentation&lt;/a&gt; should be your first port of call.&lt;/p&gt;

&lt;p&gt;For the simple Json serializer (JsonConvert) settings are stored in the JsonSerializerSettings object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;JsonSerializerSettings settings = new JsonSerializerSettings
{
    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
    Culture = CultureInfo.CurrentCulture,
    Formatting = Formatting.Indented,
    MissingMemberHandling = MissingMemberHandling.Error
};
string json = JsonConvert.SerializeObject(dog, settings);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Just out of interest I serialized the JsonSerializerSettings object from above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  "ReferenceLoopHandling": 0,
  "MissingMemberHandling": 1,
  "ObjectCreationHandling": 0,
  "NullValueHandling": 0,
  "DefaultValueHandling": 0,
  "Converters": [],
  "PreserveReferencesHandling": 0,
  "TypeNameHandling": 0,
  "TypeNameAssemblyFormat": 0,
  "ConstructorHandling": 1,
  "ContractResolver": null,
  "ReferenceResolver": null,
  "TraceWriter": null,
  "Binder": null,
  "Error": null,
  "Context": {
    "Context": null,
    "State": 0
  },
  "DateFormatString": "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK",
  "MaxDepth": null,
  "Formatting": 1,
  "DateFormatHandling": 0,
  "DateTimeZoneHandling": 3,
  "DateParseHandling": 1,
  "FloatFormatHandling": 0,
  "FloatParseHandling": 0,
  "StringEscapeHandling": 0,
  "Culture": "en-GB",
  "CheckAdditionalContent": false
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here you can see something else to note, by default Enums are serialized using their integer value, rather than string. For instance Formatting has the value 1 rather than "Indented".&lt;/p&gt;

&lt;p&gt;By adding a Converter from &lt;code&gt;Newtonsoft.Json.Converters&lt;/code&gt; the string value of an enum can be serialized:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;serializer.Converters.Add(new StringEnumConverter());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the JsonSerializer the settings are properties of the object itself. JsonSerializerSettings can be mapped to a JsonSerializer on initialization &lt;code&gt;JsonSerializer serializer = JsonSerializer.Create(settings);&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;One important setting for deserialization is &lt;code&gt;MissingMemberHandling&lt;/code&gt;, this controls what happens when an additional property is present in the Json that isn't a property on the target object. If the value is set to &lt;code&gt;MissingMemberHandling.Error&lt;/code&gt; a JsonSerializationException is thrown when an extra value in the Json is encountered.&lt;/p&gt;

&lt;p&gt;The name for this is slightly confusing since actual missing members (e.g. a property is present on the object but not in the Json) aren't dealt with, the default value of the property (0 for int, false for boolean, etc.) is used.&lt;/p&gt;

&lt;h3&gt;Json Attributes&lt;/h3&gt;

&lt;p&gt;A higher level of control over serialization can be achieved by adding attributes to classes. For example, if you only want some properties to be serialized you can add the &lt;strong&gt;JsonObject&lt;/strong&gt; attribute to the class then &lt;strong&gt;JsonProperty&lt;/strong&gt; to each property to include.&lt;/p&gt;

&lt;p&gt;For more on this see &lt;a href="http://james.newtonking.com/json/help/index.html?topic=html/SerializationAttributes.htm" title="Serialization Attributes"&gt;this page of the documentation&lt;/a&gt;.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/json-net-tutorial</guid>
      <pubDate>Tue, 05 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>What Is JSON?</title>
      <link>https://eliot-jones.com/2014/8/json-tutorial</link>
      <description>

&lt;p&gt;This is intended as a simple guide to JSON.&lt;/p&gt;

&lt;p&gt;The more programming you do the more you hear about the data format "JSON".&lt;/p&gt;

&lt;p&gt;However I've never actually used it until the changes to ASP.NET in vNext encouraged me to use it, basically the old XML format of the Web.Config is out and JSON is in (though you can swap back if I recall correctly).&lt;/p&gt;

&lt;h3&gt;What's In A Name?&lt;/h3&gt;

&lt;p&gt;JSON stands for &lt;strong&gt;"JavaScript Object Notation"&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;JavaScript Objects&lt;/h3&gt;

&lt;p&gt;The origin for this name is clear when you consider JavaScript objects. JavaScript objects are effectively dictionaries of key value pairs.&lt;/p&gt;

&lt;p&gt;For those of you not familiar with a dictionary, the concept of JavaScript objects is as follows. &lt;/p&gt;

&lt;p&gt;Let's describe your house:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var yourHouse = {
    number : 25,
    numberOfWindows : 20,
    name : "Honeysuckle Cottage",
    dog : new Dog(),
    openDoor : function() {
        alert("Hello!");
        }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now this isn't &lt;a href="http://stackoverflow.com/questions/504803/how-do-you-create-a-method-for-a-custom-object-in-javascript" title="StackOverflow"&gt;the best way to express&lt;/a&gt; a JavaScript Object with methods (or at all for that matter) but it expresses that JS objects are just collections of names for things and their values.&lt;/p&gt;

&lt;p&gt;If I ask, what's the name of your house &lt;code&gt;yourHouse["name"]&lt;/code&gt; or &lt;code&gt;yourHouse.name&lt;/code&gt; you will give me the string value &lt;code&gt;"HoneySuckle Cottage"&lt;/code&gt;. If I ask your house number &lt;code&gt;yourHouse["number"]&lt;/code&gt; you would give me the integer response 25.&lt;/p&gt;

&lt;p&gt;If I open the door to your house &lt;code&gt;yourHouse.openDoor()&lt;/code&gt; you will say "Hello!", or more likely, chase me away with a knife.&lt;/p&gt;

&lt;p&gt;Similarly if I ask to meet your dog &lt;code&gt;yourHouse["dog"]&lt;/code&gt; you wouldn't give me a string response, rather you'd show me the dog object.&lt;/p&gt;

&lt;h3&gt;Back To JSON&lt;/h3&gt;

&lt;p&gt;JSON &lt;a href="http://en.wikipedia.org/wiki/Json" title="Wikipedia Article on JSON"&gt;originated from JavaScript&lt;/a&gt; objects but has no dependence on JavaScript anymore.&lt;/p&gt;

&lt;p&gt;Rather it's a format to express/store/exchange data. &lt;/p&gt;

&lt;p&gt;For example the NoSql database &lt;a href="http://www.mongodb.org/" title="MongoDb home Page"&gt;MongoDb&lt;/a&gt; uses binary JSON (BSON) to store its data.&lt;/p&gt;

&lt;h3&gt;JSON Syntax Advantages&lt;/h3&gt;

&lt;p&gt;JSON syntax has similarities with other syntaxes used to store data in a way that both a computer and a person can read, chiefly these are &lt;a href="http://en.wikipedia.org/wiki/YAML" title="Wikipedia Article on YAML"&gt;YAML&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/XML" title="Wikipedia Article on XML"&gt;XML&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;One advantage is that it's lighter weight (expresses the same information in fewer characters) than XML, so is increasingly used for Data Transfer Objects from Web Services. The reason for this is if I ask your library web service for all 10, 000 books in the library you want to save every possible byte of your bandwidth.&lt;/p&gt;

&lt;p&gt;The other major advantage (or perhaps the main one) is compatibility with JavaScript ("the assembly language of the web"). JSON can be converted to a JavaScript object using &lt;code&gt;eval()&lt;/code&gt;, &lt;strong&gt;don't do this, due to security&lt;/strong&gt;, or with a built in JSON parser.&lt;/p&gt;

&lt;p&gt;Obviously there are disadvantages as well, have a quick Google to get a more balanced view.&lt;/p&gt;

&lt;h3&gt;Our House, In The Middle Of Our JSON&lt;/h3&gt;

&lt;p&gt;Enough talk, time to see some JSON:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
  "number" : "25",
  "numberOfWindows" : 20,
  "name" : "HoneySuckle Cottage"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That's the object representing your house from earlier in JSON. The first thing to notice is your dog is gone, we'll get to that in a moment.&lt;/p&gt;

&lt;p&gt;Also concerning, perhaps more concerning depending on how much you like dogs, is that we can no longer open your door. This is because we cannot store functions in JSON, not even JavaScript functions, which are just JS objects. If you can get over the loss of your door, let's get back to your missing dog.&lt;/p&gt;

&lt;p&gt;I didn't include your dog because I wanted to show the simplest JSON syntax first, objects can be nested within other objects like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
    "number" : "25",
    "numberOfWindows" : 20,
    "name" : "HoneySuckle Cottage",
    "dog" : {
        "age" : 5,
        "name" : "Baron Von Lassie"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this way complex object containers can be built and stored in an easily readable way.&lt;/p&gt;

&lt;h3&gt;Syntax Overview&lt;/h3&gt;

&lt;p&gt;Let's define this a little more formally.&lt;/p&gt;

&lt;h5&gt;Object&lt;/h5&gt;

&lt;p&gt;Any object in JSON starts and ends with curly braces '{ }'&lt;/p&gt;

&lt;p&gt;An object contains "key" : value pairs where the key is a string identifier for the property of the object.&lt;/p&gt;

&lt;h5&gt;Value&lt;/h5&gt;

&lt;p&gt;JSON supports the following Data Types for values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Number (int, float, double etc all in the same DataType)&lt;/li&gt;
&lt;li&gt;String ("see &lt;a href="http://json.org/" title="Official JSON Site"&gt;me&lt;/a&gt; for more string and syntax rules")&lt;/li&gt;
&lt;li&gt;Boolean (true or false unquoted)&lt;/li&gt;
&lt;li&gt;null&lt;/li&gt;
&lt;li&gt;Array&lt;/li&gt;
&lt;li&gt;Object&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;Array&lt;/h5&gt;

&lt;p&gt;An array can contain objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;"LightSources": [
    {
      "Id": 1,
      "Name": "candle"
    },
    {
      "Id": 2,
      "Name": "torch"
    }
  ]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or other DataTypes, e.g. numbers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;"Times": [
    10.2345,
    15.0
  ]
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;JSON.NET&lt;/h3&gt;

&lt;p&gt;"Hmm", you say, "these JSON objects sure look like a good fit for C# objects!".&lt;/p&gt;

&lt;p&gt;Well I'm glad you mentioned it, because in the next post we will look at some JSON.NET&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/8/json-tutorial</guid>
      <pubDate>Mon, 04 Aug 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>POCOs from DataTable</title>
      <link>https://eliot-jones.com/2014/7/dataset-to-poco</link>
      <description>

&lt;p&gt;&lt;em&gt;Edit: There were a few code errors in the original post, these have now been fixed.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For those of us still using Stored Procedures to retrieve information from a database it's useful to have a quick way to pass the resulting DataSet to a collection of POCOs (Plain Old CLR Objects).&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/pocos/DataSet.png" alt = "A dataset in Visual Studio debugger"/&gt;&lt;/p&gt;

&lt;p&gt;The problem is manual mappings are a pain and if they're spread around your data access logic lead to a maintenance headache. That's why &lt;strong&gt;&lt;a href="http://sharpdevpt.blogspot.co.uk/2010/05/convert-datatable-into-poco-using.html" title="Original POCO mapper post"&gt;this approach&lt;/a&gt;&lt;/strong&gt; by &lt;strong&gt;Ricardo Rodrigues&lt;/strong&gt; is so appealing. As soon as I came across it I decided to use it for all future data access logic on the application I maintain. &lt;/p&gt;

&lt;p&gt;The database for this application is a sprawling nightmare of non-existent constraints, mixed naming conventions and bad data-type choices so his approach was a natural fit.&lt;/p&gt;

&lt;h3&gt;Original Method&lt;/h3&gt;

&lt;p&gt;To outline the approach (this is mostly a copy of what's on his site but with a few changes relevant to this post), you use a ColumnMapping attribute:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class ColumnMapping : Attribute
{
    public string FieldName { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This attribute is then placed above the properties on a POCO to map the column names of the dataset to the property:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class Dog
{
    [ColumnMapping(FieldName="Dog_Id")]
    public int Id { get; set; }

    [ColumnMapping(FieldName = "NumLegs")]
    public int NumberOfLegs { get; set; }

    [ColumnMapping(FieldName = "Description")]
    public string Name { get; set; }

    [ColumnMapping(FieldName = "Owner")]
    public bool HasOwner { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This allows you to compensate for poor life choices on the part of the original db developer by having your POCO properties nicely named.&lt;/p&gt;

&lt;p&gt;The mapping is then performed as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class DbUtil
{
    public List&amp;lt;T&amp;gt; ToObjectList&amp;lt;T&amp;gt;(DataTable dataTable) where T : new()
    {
        List&amp;lt;T&amp;gt; returnList = new List&amp;lt;T&amp;gt;();
        for (int rowIndex = 0; rowIndex &amp;lt; dataTable.Rows.Count; rowIndex++)
        {
            T returnObject = new T();

            for (int colIndex = 0; colIndex &amp;lt; dataTable.Columns.Count; colIndex++)
            {
                DataColumn column = dataTable.Columns[colIndex];

                foreach (PropertyInfo property in returnObject.GetType().GetProperties())
                {
                    String fieldName = ((ColumnMapping)property.GetCustomAttributes(
                                            typeof(ColumnMapping), false)[0]).FieldName;
                    if (fieldName.ToLower() == column.ColumnName.ToLower())
                    {
                        property.SetValue(returnObject,
                            FieldToObject(dataTable.Rows[rowIndex][colIndex], property.PropertyType),
                            null);
                        break;
                    }
                }
            }
            returnList.Add(returnObject);
        }
        return returnList;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The FieldToObject method is just a quick and nasty method I chucked together for this demo. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private object FieldToObject(object obj, Type type)
{
    if (type == typeof(int))
    {
        int output = 0;
        int.TryParse(obj.ToString(), out output);
        return output;
    }
    else if (type == typeof(bool))
    {
        try
        {
            return Convert.ToBoolean(obj);
        }
        catch { return false; }
    }
    else
    {
        return obj;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I use something similar for the application, it allows you to sanitise your data as you map, for instance some fields which should have a data type of Bit for boolean such as "IsValid" actually have int.&lt;br /&gt;
This means you're trying to cast values -1, 0, 1, 2, 3, etc to bool and you need a way to specify the expected behaviour in these cases.&lt;/p&gt;

&lt;h3&gt;Fine Tuning&lt;/h3&gt;

&lt;p&gt;Having thought some more about this recently it seems like there's room for performance improvements. So I've put together a thoroughly unscientific test. The DataTable is seeded as follows, trying to match the original database's randomness:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DataTable dataTable = new DataTable("DogsDataTable");
dataTable.Columns.Add("Dog_Id");
dataTable.Columns.Add("NumLegs");
dataTable.Columns.Add("Description");
dataTable.Columns.Add("Owner");

Random rnd = new Random();
for (int i = 0; i &amp;lt; 1000; i++)
{
    DataRow tempRow = dataTable.NewRow();

    bool? owner = true;
    if(i % 3 == 0) owner = false;
    else if (i % 11 == 0) owner = null;

    tempRow["Dog_Id"] = i + 1;
    tempRow["NumLegs"] = rnd.Next(1, 5);
    tempRow["Description"] = "Dog" + i.ToString();
    tempRow["Owner"] = owner;

    dataTable.Rows.Add(tempRow);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The DataTable is then parsed using a variety of methods and the time for 500 passes recorded using &lt;a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx" title="MSDN Stopwatch"&gt;Stopwatch&lt;/a&gt; to measure C# runtime as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DbUtil dbUtil = new DbUtil();
long elapsedMilliseconds = 0;
int passes = 500;
for (int t = 0; t &amp;lt; passes; t++)
{
    Stopwatch stopWatch = Stopwatch.StartNew();
    List&amp;lt;Dog&amp;gt; dogs = dbUtil.ToObjectList&amp;lt;Dog&amp;gt;(dataTable); // This method is swapped.
    stopWatch.Stop();
    elapsedMilliseconds += stopWatch.ElapsedMilliseconds;
}
Console.WriteLine("average milliseconds = " + (elapsedMilliseconds / passes).ToString() 
    + " passes = " + passes.ToString()
    + " total milliseconds = " + elapsedMilliseconds.ToString());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(Note the program is run rather than debugged, debugging adds an extra 320 ms roughly to the runtime)&lt;br /&gt;
For Ricardo's method the average time is: &lt;strong&gt;46 ms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is a manual mapping, using my same rubbishy casting method to keep it fair.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public List&amp;lt;Dog&amp;gt; ToDogList(DataTable dataTable)
{
    List&amp;lt;Dog&amp;gt; returnList = new List&amp;lt;Dog&amp;gt;();

    for (int rowIndex = 0; rowIndex &amp;lt; dataTable.Rows.Count; rowIndex++)
    {
        returnList.Add(new Dog
        {
            Id = (int)FieldToObject(dataTable.Rows[rowIndex]["Dog_Id"], typeof(int)),
            Name = (string)FieldToObject(dataTable.Rows[rowIndex]["Description"], typeof(string)),
            NumberOfLegs = (int)FieldToObject(dataTable.Rows[rowIndex]["NumLegs"], typeof(int)),
            HasOwner = (bool)FieldToObject(dataTable.Rows[rowIndex]["Owner"], typeof(bool))
        });
    }

    return returnList;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method runs in: &lt;strong&gt;3 ms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now we take Ricardo's method and try to take advantage of manual mapping using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.datacolumncollection.contains(v=vs.85).aspx" title="MSDN Contains"&gt;Contains method&lt;/a&gt; to find if a column exists in the DataTable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public List&amp;lt;T&amp;gt; ToObjectList2&amp;lt;T&amp;gt;(DataTable dataTable) where T : new()
{
    List&amp;lt;T&amp;gt; returnList = new List&amp;lt;T&amp;gt;();
    for (int rowIndex = 0; rowIndex &amp;lt; dataTable.Rows.Count; rowIndex++)
    {
        T returnObject = new T();
        foreach (PropertyInfo property in returnObject.GetType().GetProperties())
        {
            string fieldName = ((ColumnMapping)property.GetCustomAttributes(typeof(ColumnMapping), false)[0]).FieldName;
            if(dataTable.Columns.Contains(fieldName))
            {
                property.SetValue(returnObject,
                    FieldToObject(dataTable.Rows[rowIndex][fieldName], property.PropertyType),
                    null);
            }
        }
        returnList.Add(returnObject);
    }
    return returnList;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This runs in: &lt;strong&gt;24 ms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That's pretty good but is it possible to squeeze more performance out?&lt;/p&gt;

&lt;p&gt;There's a slight performance benefit (~500 ticks) to declaring the capacity of the object list up-front (as expected due to not needing to grow the list). This is a surprisingly small benefit and shows just how well C# handles list lengths changing.&lt;/p&gt;

&lt;h3&gt;Final Result&lt;/h3&gt;

&lt;p&gt;The run-time can be reduced to &lt;strong&gt;4 ms&lt;/strong&gt; by making the changes below:&lt;/p&gt;

&lt;p&gt;A new class is declared inside DbUtil:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private class ExtendedPropertyInfo
{
    public PropertyInfo property { get; set; }
    public string fieldName { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The method then looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public List&amp;lt;T&amp;gt; ToObjectList3&amp;lt;T&amp;gt;(DataTable dataTable) where T : new()
{
    List&amp;lt;T&amp;gt; returnList = new List&amp;lt;T&amp;gt;(dataTable.Rows.Count);
    List&amp;lt;ExtendedPropertyInfo&amp;gt; accessibleProperties = new List&amp;lt;ExtendedPropertyInfo&amp;gt;();

    foreach (PropertyInfo property in new T().GetType().GetProperties())
    {
        string fieldName = ((ColumnMapping)property.GetCustomAttributes(typeof(ColumnMapping), false)[0]).FieldName;
        if (dataTable.Columns.Contains(fieldName))
        {
            accessibleProperties.Add(new ExtendedPropertyInfo{
                    fieldName = fieldName,
                    property = property
                });
        }
    }
    for (int rowIndex = 0; rowIndex &amp;lt; dataTable.Rows.Count; rowIndex++)
    {
        T returnObject = new T();
        foreach (ExtendedPropertyInfo eproperty in accessibleProperties)
        {
            eproperty.property.SetValue(returnObject,
                    FieldToObject(dataTable.Rows[rowIndex][eproperty.fieldName], eproperty.property.PropertyType),
                    null);
        }
        returnList.Add(returnObject);
    }
    return returnList;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works by only checking for the existence of columns once, rather than every row and saving a few reflection calls by putting them at the start of the method.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;The original method is fast enough that performance benefits here aren't really worth the time taken to investigate, however it's an interesting intellectual exercise.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/7/dataset-to-poco</guid>
      <pubDate>Wed, 30 Jul 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Create Table SQL Server</title>
      <link>https://eliot-jones.com/2014/7/create-table-sql-server</link>
      <description>

&lt;p&gt;Most guides on the SQL 'Create Table' command seem to only include the most basic arguments necessary to create a table with a few columns.&lt;/p&gt;

&lt;p&gt;They don't go on to detail how to name constraints, create indexes and add foreign keys or similar.&lt;/p&gt;

&lt;p&gt;If you're one of the (seemingly very few) people not using code/model-first Entity Framework I've posted this small snippet to help you. It includes how to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create and name a primary key.&lt;/li&gt;
&lt;li&gt;Create and name a foreign key.&lt;/li&gt;
&lt;li&gt;Create and name a default constraint.&lt;/li&gt;
&lt;li&gt;Create and name a non-clustered index.&lt;/li&gt;
&lt;li&gt;Cascade delete.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It does not detail how to create a composite non-clustered index (a non-clustered index on multiple columns).&lt;/p&gt;

&lt;p&gt;So, the whole statement is here (note that having a column with the same name as the table will cause problems in EF database-first, the Question property will be renamed Question1):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE TABLE Dog
        (
                Id              INT IDENTITY(-2147483648, 1) CONSTRAINT PK_Dog_Id PRIMARY KEY NOT NULL,
                Title           NVARCHAR(MAX) NULL,
                Name            NVARCHAR(MAX) NOT NULL,
                OwnerId         INT INDEX IX_Dog_Owner NONCLUSTERED 
                CONSTRAINT  FK_Dog_Owner FOREIGN KEY REFERENCES dbo.Owner(Id) 
                ON DELETE CASCADE,
                UserId          INT NOT NULL INDEX IX_Dog_User NONCLUSTERED 
                CONSTRAINT FK_Users_Dog FOREIGN KEY REFERENCES dbo.AspNetUsers(Id),
                CreatedDate     DATETIME2(0) NOT NULL CONSTRAINT DF_Dog_CreatedDate DEFAULT GETDATE(),
                ModifiedDate    DATETIME2(0) NOT NULL CONSTRAINT DF_Dog_ModifiedDate DEFAULT GETDATE(),
                RowVersion      ROWVERSION
        )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To run through a few things to note:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;INT IDENTITY(-2147483648, 1)&lt;/code&gt;&lt;br /&gt;
There's an &lt;a href="http://blog.codinghorror.com/primary-keys-ids-versus-guids/" title="Jef Atwood on int vs guid"&gt;interesting debate&lt;/a&gt; about whether to use a GUID or integer for a primary key, I've gone with integer since to me it's more readable, but a quick Google will provide more than enough reading to the interested coder.
I've seeded this primary key with  the minimum value for INT, this means values from -2147483648 to 1 aren't wasted.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NVARCHAR(MAX)&lt;/code&gt;&lt;br /&gt;
NVARCHAR should &lt;del&gt;generally&lt;/del&gt; always be used for text columns because it supports Unicode. VARCHAR supports ASCII.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;INDEX IX_Question_QuestionSet NONCLUSTERED&lt;/code&gt;&lt;br /&gt;
Create non-clustered index on column.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CONSTRAINT FK_QuestionSet_Question FOREIGN KEY REFERENCES dbo.QuestionSet(Id)&lt;/code&gt;&lt;br /&gt;
Create foreign key on a column.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ON DELETE CASCADE&lt;/code&gt;&lt;br /&gt;
Further to the foreign key constraint, when you delete a record in the parent table (QuestionSet) specifies that columns referencing this record should also be deleted. The alternative is to error if linked records are present.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DATETIME2(0)&lt;/code&gt;&lt;br /&gt;
The &lt;a href="http://msdn.microsoft.com/en-gb/library/bb677335.aspx" title="MSDN on DateTime2 Data Type"&gt;new DateTime data type&lt;/a&gt; replacing deprecated DATETIME (from SQL Server 2008 up). The number in brackets is the 'fractional seconds precision', a fancy sounding way of saying the number of decimal points after the second.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CONSTRAINT DF_Question_ModifiedDate DEFAULT GETDATE()&lt;/code&gt;&lt;br /&gt;
Named Default Constraint.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;RowVersion       ROWVERSION NOT NULL&lt;/code&gt;&lt;br /&gt;
The row version replaces TimeStamp for SQL Server 2008 onwards,  &lt;code&gt;NOT NULL&lt;/code&gt; is not explicitly required and the column will be Not Nullable. &lt;a href="http://geekswithblogs.net/TimothyK/archive/2014/01/14/introduction-to-rowversion.aspx" title="RowVersion guide on a blog"&gt;Read all about it&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;That's all of it, there's &lt;a href="http://msdn.microsoft.com/en-gb/library/ms174979.aspx" title="MSDN on Create Table"&gt;much more&lt;/a&gt; that can be done with the CREATE TABLE statement and what I have may not follow best practices but it's a helpful reminder of how everything can be combined in one statement. For instance, who knew about &lt;a href="http://msdn.microsoft.com/en-gb/library/cc280604.aspx" title="MSD on sparse columns"&gt;sparse columns&lt;/a&gt;?&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/7/create-table-sql-server</guid>
      <pubDate>Tue, 29 Jul 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>You sank my battleship</title>
      <link>https://eliot-jones.com/2014/7/battleship-debugging</link>
      <description>

&lt;p&gt;&lt;img src = "/images/battleship/battleshipDebugging.png" alt = "The Board Game Battleship"/&gt;&lt;/p&gt;

&lt;p&gt;So this is probably one of those things that everyone else but me knows and I'm just going to reveal my ignorance, but as a note to myself for future and for those who don't know, here's how you
remove the need for battleship debugging (scatter the code with breakpoints and hope you hit something) in Visual Studio. &lt;/p&gt;

&lt;p&gt;This is the same as 'Pause On Exceptions' in a Javascript debugger such as that in Google Chrome and other debuggers, but if you are new to debugging and debuggers, it's not immediately obvious. &lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/battleship/chromeDebugger.png" alt = "Break on all Javascript Exceptions"/&gt;&lt;/p&gt;

&lt;p&gt;This means the code automatically breaks when any Exception is thrown and allows you to see the exact moment a problem occurs and the nature of the exception at this point.&lt;/p&gt;

&lt;h2&gt;How to enable&lt;/h2&gt;

&lt;p&gt;The following screenshots are from the VS2014 CTP however the steps are the same for most earlier versions, if you can't find the Exceptions window, try &lt;code&gt;ctrl + d, ctrl + e&lt;/code&gt; (yes, it's Ctrl + Alt + E in the image but I don't think this is the case for pre-VS13 versions).&lt;/p&gt;

&lt;p&gt;So first open the debug menu and find the 'Exceptions' option:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/battleship/debugMenu.png" alt = "The Debug Menu"/&gt;&lt;/p&gt;

&lt;p&gt;Then make sure Common Language Runtime Errors are set to 'Thrown':&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/battleship/exceptions.png" alt = "Break on All Exceptions by ticking the box"/&gt;&lt;/p&gt;

&lt;p&gt;And that's it, no more guessing exactly where an error occurred based on a vague stack trace which may be obfuscated by poorly implemented error handling in the creaking old legacy application you're maintaining.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/7/battleship-debugging</guid>
      <pubDate>Wed, 02 Jul 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>vNext Setup</title>
      <link>https://eliot-jones.com/2014/6/vNext-Setup</link>
      <description>

&lt;p&gt;ASP.NET vNext is coming and despite the lack of fanfare around the announcement, it's a challenge to describe it without resorting to meaningless buzzwords like 'paradigm-shift'. 
While it's hard to pick which of the awesome features of vNext to celebrate most, to me the top features are definitely:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Code changes without compile (courtesy of the, also hugely exciting, new compiler Roslyn).&lt;/li&gt;
&lt;li&gt;Cross platform ASP.NET in collaboration with Mono.&lt;/li&gt;
&lt;li&gt;Open Source, the entire vNext project is open source.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;While I love code changes without compile as much as the next developer I think points 2 and 3 are the most exciting in terms of how Microsoft develop and release software in the future. The unprecedented level of transparency around these projects finally puts to bed the
Microsoft vs. Open Source community disputes. &lt;/p&gt;

&lt;p&gt;One of the best server side languages (ok, I use it for a job so I'm biased) is now available for all developers on all platforms, though this might lose Microsoft some licensing costs for Server OSes
and Visual Studio licenses it also opens up the majority of servers (which are not running MS OSes) to ASP.NET (not to mention, who on earth chooses not to use Visual Studio if it's available).
Scott Hanselman definitely describes all the new features better than I ever could, so head on over to &lt;a href="http://www.hanselman.com/blog/IntroducingASPNETVNext.aspx"&gt;his site&lt;/a&gt; to read more.&lt;/p&gt;

&lt;p&gt;That's enough about why vNext is great. How do we actually get it up and running? The instructions on the &lt;a href="http://msysgit.github.io/"&gt;Git Repository&lt;/a&gt; are probably the best on how to install.&lt;/p&gt;

&lt;h2&gt;Install Git&lt;/h2&gt;

&lt;p&gt;The vNext project is available as a &lt;a href="https://github.com/aspnet/Home"&gt;Git repo&lt;/a&gt;, so in order to get it you need to have Git installed. Installing Git for Windows is extremely easy, thanks to &lt;a href="http://msysgit.github.io/"&gt;these guys&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Once you have it installed, navigate to the appropriate directory (use 'cd' to change directory, just like command line) and type
&lt;code&gt;git clone https://github.com/aspnet/Home.git&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This should clone the repo to the correct directory, in my case I didn't change directory before clone and it copied to &lt;code&gt;C:\Users\[Username]\Home&lt;/code&gt;&lt;/p&gt;

&lt;h2&gt;Install the KPM&lt;/h2&gt;

&lt;p&gt;KPM is used to manage and install the nuget packages for vNext. Inside the Home folder you should see 'kvminstall.ps1'. This is a Powershell script, Powershell is 
effectively the Windows command line but better. &lt;/p&gt;

&lt;p&gt;Run Powershell, which for me can be found by typing 'Powershell' in the Windows 8 start
menu. If you cannot find it the .exe's are in &lt;code&gt;C:\Windows\System32\WindowsPowerShell\v1.0&lt;/code&gt; (for 32 bit) or &lt;code&gt;C:\Windows\SysWOW64\WindowsPowerShell\v1.0&lt;/code&gt;
(for 64 bit), I used the 32 bit version. Remember to right click and 'Run As Administrator'.&lt;/p&gt;

&lt;p&gt;Once Powershell has started you need to set your execution policy in order for the downloaded kvminstall script to run. To find out what
your current Execution Policy is type &lt;code&gt;get-executionpolicy&lt;/code&gt;. If it's 'Signed' set it to 'RemoteSigned' by typing &lt;code&gt;set-executionpolicy RemoteSigned&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once this is done, double-click on the kvminstall.ps1 file and this will run the script. The script creates a new folder in &lt;code&gt;C:\Users\[Username]\.kre&lt;/code&gt; containing the
'bin' folder with kvm.cmd and kvm.ps1 in (thus it's fairly simple to set up yourself if you have trouble with kvminstall). It also adds &lt;code&gt;C:\Users\Eliot\.kre\bin&lt;/code&gt;
to the path.&lt;/p&gt;

&lt;p&gt;To add something to the Path go to &lt;code&gt;control panel -&amp;gt; system -&amp;gt; advanced system settings -&amp;gt; environment variables&lt;/code&gt; and add 
&lt;code&gt;C:\Users\Eliot\.kre\bin;&lt;/code&gt; to the &lt;code&gt;User Variables -&amp;gt; Path&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once installed either through the script or manually, open a new Powershell Window or Command Line (as administrator) and type
&lt;code&gt;kvm list&lt;/code&gt; to make sure 'kvm' is a recognised command. Now you can retrieve the latest version by running &lt;code&gt;kvm upgrade&lt;/code&gt; or retrieve a specific
version by typing &lt;code&gt;kvm install 0.1-alpha-build-0519&lt;/code&gt; (which was latest at time of writing). This installs files to the .kre\packages folder.&lt;/p&gt;

&lt;p&gt;Having installed a version typing &lt;code&gt;kvm list&lt;/code&gt; should show some installed versions as shown in this picture:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/vNext/kvmList.png" alt = "List kvm versions and change the active version"/&gt;&lt;/p&gt;

&lt;p&gt;Type &lt;code&gt;kvm use [version]&lt;/code&gt; as shown to swap versions.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note&lt;/em&gt; -
I was using BitDefender anti-virus and it stubbornly refused to allow kvm to install some versions, I disabled it when working with kvm and kpm.&lt;/p&gt;

&lt;h2&gt;Run the KPM and KRE&lt;/h2&gt;

&lt;p&gt;In the command line or Powershell navigate to &lt;code&gt;C:\Users\[Username]\Home\samples\ConsoleApp&lt;/code&gt; and run &lt;code&gt;kpm restore&lt;/code&gt; as shown below:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/vNext/kpmRestore.png" alt = "Get necessary dll's using kpm restore."/&gt;&lt;/p&gt;

&lt;p&gt;Once this has executed successfully you can now type &lt;code&gt;k run&lt;/code&gt; and the Console will log 'Hello World' to screen.&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/vNext/kRun.png" alt = "Get necessary dll's using kpm restore."/&gt;&lt;/p&gt;

&lt;p&gt;The magic of vNext/Roslyn can be seen here, if you now open Program.cs from &lt;code&gt;C:\Users\[Username]\Home\samples\ConsoleApp&lt;/code&gt; and
add a new line, for example &lt;code&gt;Console.WriteLine("Hello vNext");&lt;/code&gt; then type &lt;code&gt;k run&lt;/code&gt; the change happens straight away, without the
need to 'Build' in Visual Studio or any other compile steps.&lt;/p&gt;

&lt;p&gt;Happy vNext-ing.&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/6/vNext-Setup</guid>
      <pubDate>Sat, 14 Jun 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>New Site</title>
      <link>https://eliot-jones.com/2014/6/under-construction</link>
      <description>

&lt;p&gt;I have changed the entire site to use url routing, but haven't quite finished yet so there's a lot less content than the old site.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;hello world&lt;/code&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2014/6/under-construction</guid>
      <pubDate>Sat, 07 Jun 2014 00:00:00 GMT</pubDate>
    </item>
    <item>
      <title>Python Development On Windows</title>
      <link>https://eliot-jones.com/2013/6/python-on-windows</link>
      <description>

&lt;p&gt;For absolute beginners setting up Python on Windows can be a bit daunting. There used to be a great guide for setting
up a development environment on the Sad Phaeton Blog which is sadly now defunct. I will try to emulate the brilliance of that guide
but if you want another guide there's one &lt;a href="http://varunpant.com/posts/how-to-setup-easy_install-on-windows" title="Blog on how to use easy_install on Windows"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Installing Python&lt;/h2&gt;

&lt;p&gt;There are currently 2 main releases of Python, Python 2.7 and Python 3.3. There are some differences in the language between the 
two and the support for external libraries is better in 2.7 just by virtue of it being older. We'll use Python 2.7 in this tutorial.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.python.org/download/" title="Python Download Page"&gt;Download it here&lt;/a&gt;, I use 32 bit Python (Python 2.7.5 Windows Installer) because the installers provided for third-party libraries tend
to look for the 32 bit version. You can trick these installers into using the 64 bit version by editing the Registry but unless you're going to be using huge datasets 
32 bit should do for you.&lt;/p&gt;

&lt;p&gt;Run the installer using the default settings. I tend to install to the directory (C:/Python27). If we open the Windows command prompt (run "cmd")
and type "python" we get the following response.&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/python-not-recognized.png" alt = "Command Prompt does not recognize Python"/&gt;&lt;/p&gt;

&lt;p&gt;This tells us that Windows has no idea what a "python" is. To educate it we need to change the environment variables and path.&lt;/p&gt;

&lt;h2&gt;PATH Environment Variable&lt;/h2&gt;

&lt;p&gt;So what is the &lt;a href="http://en.wikipedia.org/wiki/PATH_(variable)" title="Wikipedia article on Path variable"&gt;Path&lt;/a&gt;? Basically it tells Windows where to look for programs that need to be executed from the command window. The Path is a special type of 
environment variable.&lt;/p&gt;

&lt;p&gt;To find out what's in your path type "echo %PATH%" into the command prompt.&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/path-echo.png" alt = "Command Prompt echos the path"/&gt;&lt;/p&gt;

&lt;p&gt;The % signs mark out an environment variable. This type of variable is just a name for some text, so the %PATH% variable
refers to a semicolon (;) delimited list of directories on the Windows system. The reason Windows doesn't know what python is
is because it's not in the path and it can't find it.&lt;/p&gt;

&lt;p&gt;Now we come to the fun part! Setting up your own environment variables (disclaimer: no fun will be had). To find your environment
variables go to:&lt;/p&gt;

&lt;p&gt;control panel -&gt; system -&gt; advanced system settings -&gt; environment variables&lt;/p&gt;

&lt;p&gt;As shown here:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/environment-variable-window.png" alt = "The environment variable dialog box"/&gt;&lt;/p&gt;

&lt;h2&gt;Python Environment Variable&lt;/h2&gt;

&lt;p&gt;The first thing we're going to do to make life easier is give the location of Python an environment variable. Why do this?
When we add Python to the Path text if we hardcode the location and then change that location in the future we'll have to edit the path carefully.
By using an environment variable if we change version (to Python 3.3) in future we can just change the environment variable and the system will still work.&lt;/p&gt;

&lt;p&gt;To add the environment variable:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/new-py27.png" alt = "Add new environment variable"/&gt;&lt;/p&gt;

&lt;p&gt;Add a new system variable (not user variable though you can if you want) called PY27 (or whatever name you want really but I'm using PY27) with the value being
the location of the Python folder "C:\Python27".&lt;/p&gt;

&lt;p&gt;After adding this open a NEW cmd window and type "echo %PY27%" (or whichever name you chose) and you should see the name of the directory displayed.
You can also move the command prompt into the Python folder by typing "cd %PY27%:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/py27-echo.png" alt = "Command prompt echos new environment variable"/&gt;&lt;/p&gt;

&lt;h2&gt;Edit the Path&lt;/h2&gt;

&lt;p&gt;We still can't access Python by typing "python" in the command prompt, so what have we achieved? Well, nothing yet!&lt;/p&gt;

&lt;p&gt;We need to add the new Python Environment Variable (PY27) to the Path. To do so find the Path System Variable and edit it.
Add %PY27% after a semicolon ';' separating it from the previous entry.&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/edit-path.png" alt = "Add %PY27% to the Path"/&gt;&lt;/p&gt;

&lt;p&gt;Now if we type "python" into the command prompt (open a NEW command prompt each time you edit an environment variable) we should start the python shell:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/python-cmd.png" alt = "Running python in command prompt"/&gt;&lt;/p&gt;

&lt;p&gt;So, we've added an environment variable for the location of Python and added that to our path.&lt;/p&gt;

&lt;p&gt;Now to setup easy_install.&lt;/p&gt;

&lt;h2&gt;easy_install&lt;/h2&gt;

&lt;p&gt;easy_install is a way to easily install (surprisingly) libraries (bits of code other people have written to make our lives easier).&lt;/p&gt;

&lt;p&gt;Download and run the easy_install python script according to &lt;a href="https://pypi.python.org/pypi/setuptools/1.1#windows" title="Windows installation of setup tools"&gt;these&lt;/a&gt; instructions. Check it installed correctly by looking in your
Python directory (C:/Python27 for me) at the "Scripts" folder for "easy-install.exe". If you have trouble getting it by this method, the wonderful
Christoph Gohlke provides an &lt;a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools" title="Setuptools installer for Windows"&gt;exe installer&lt;/a&gt; for specific versions of Python.&lt;/p&gt;

&lt;h2&gt;Add easy_install to Path&lt;/h2&gt;

&lt;p&gt;Assuming you have easy_install.exe in your scripts folder let's add it so we can invoke it from command prompt. Reopen your environment variables and edit the
path again to add "%PY27%\Scripts" to the Path variable:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/edit-path-2.png" alt = "Edit Path Variable"/&gt;&lt;/p&gt;

&lt;p&gt;Remember to open a new command prompt after making these changes. Type "easy_install" and you should get an error message:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/easy-install-error.png" alt = "Run easy_install in command prompt"/&gt;&lt;/p&gt;

&lt;p&gt;This occurs because we provided no library name for the program to install. &lt;/p&gt;

&lt;p&gt;I realise I've guided you through setting up easy_install but nowadays we tend to prefer 'pip' the Python package manager. So let's install that using easy_install. Type
"easy_install pip" and you should see:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/easy-pip.png" alt = "easy_install pip in command prompt"/&gt;&lt;/p&gt;

&lt;p&gt;You can now install packages using "pip install PACKAGE_NAME" in the command prompt, eg the unit testing library Nose:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/pip-install-nose.png" alt = "pip install nose"/&gt;&lt;/p&gt;

&lt;p&gt;Now, the main issue with Python on Windows is that Python libraries tend to have extensions written in the language 'C'. Most operating systems come with a 
C compiler included. Windows, for no good reason, lacks a C compiler which causes all sorts of errors with our lovely new system, eg for numpy:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/vcvarsall.png" alt = "pip install fails due to vcvarsall.bat"/&gt;&lt;/p&gt;

&lt;p&gt;I still haven't got to the bottom of this error and it seems to have &lt;a href="http://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat" title="People having the same problem"&gt;many suggested fixes&lt;/a&gt;. I've so far tried using MinGW but will try Visual Studio when I need to, but for 
most purposes using &lt;a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" title="Windows installers for Python Libraries"&gt;the Windows installers (absolute lifesavers)&lt;/a&gt; or some combination of easy_install and pip will work. Here "easy_install numpy" works fine:&lt;/p&gt;

&lt;p&gt;&lt;img src = "/images/Python-Environment/numpy-install.png" alt = "successful numpy install"/&gt;&lt;/p&gt;
</description>
      <author>Eliot (Eliot Jones)</author>
      <guid>https://eliot-jones.com/2013/6/python-on-windows</guid>
      <pubDate>Sat, 08 Jun 2013 00:00:00 GMT</pubDate>
    </item>
  </channel>
</rss>