<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Xoltar</title>
	<atom:link href="http://www.xoltar.org/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.xoltar.org</link>
	<description>A blog by Bryn Keller about simplicity and clarity in software and in life</description>
	<lastBuildDate>Thu, 16 May 2013 17:19:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Hot Towel SPA Is a Great Starter</title>
		<link>http://www.xoltar.org/?p=127</link>
		<comments>http://www.xoltar.org/?p=127#comments</comments>
		<pubDate>Thu, 16 May 2013 10:30:00 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=127</guid>
		<description><![CDATA[A few months ago, John Papa released a Visual Studio template called Hot Towel SPA, which Scott Hanselman kindly pointed out to me. SPA, as all the hip kids will tell you, stands for Single Page Application. That is, the kind of application that you start by visiting a web page, and you stay on [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago, <a href="http://www.johnpapa.net/">John Papa</a> released a Visual Studio template called <a href="http://www.johnpapa.net/hottowel/">Hot Towel SPA</a>, which <a href="http://www.hanselman.com/">Scott Hanselman</a> kindly pointed out to me. SPA, as all the hip kids will tell you, stands for Single Page Application. That is, the kind of application that you start by visiting a web page, and you stay on that same page for as long as you use the application. As opposed to most web applications, where you skip from page to page as you interact with the site.</p>
<p>People have been doing this for a long time, of course,  but the Hot Towel SPA starter really is a nice introduction to the style. In a SPA, you really  need to think of the browser as “the client,” a standalone entity that communicates with your server via (web) API calls. Once you get used to it, it’s really rather refreshing, and it allows you to take advantage of all the computing power on the client machine in a way that can be quite liberating.</p>
<p>Hot Towel uses a JavaScript application framework called <a href="http://durandaljs.com/">Durandal</a> to structure the client side code. It divides the world up into services (JavaScript modules, basically), views, and view models. All of this is just for the JavaScript side of things, remember – you may also have views and view models and so on on the server side, but that’s a different thing – you’ll interact with those via AJAX calls, usually using JSON to encode the data.</p>
<p>Hot Towel uses HTML for the views and lets <a href="http://knockoutjs.com/">Knockout</a> do the view composition and data binding, which makes it a good source of examples for learning Knockout as well.</p>
<p>The JavaScript code is nicely modular, in the style of <a href="http://requirejs.org/">require.js</a>. If you’ve not seen this style, it’s worth checking out. Basically, you declare all your dependencies for your JavaScript module, and the framework asynchronously loads them as necessary, as passes them to your module. It’s great documentation, great for structuring the code so you don’t get circular dependencies, and makes for easier unit testing too, since can easily supply alternative (mock) implementations of your module’s dependencies.</p>
<p>On the server, the MVC code is well organized as well, and it’s straightforward to plug in your new Web API controllers and start coding.</p>
<p>I’ve been playing with this starter for a while, working on a proof of concept for a new series of articles on my blog. I found Hot Towel to be a great starting point, and it opened my eyes to some interesting new techniques on the client side. Give Hot Towel a try for your next project, it’ll be fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=127</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building an Azure Web Site Application, Part 2: Diagnostics and Logging</title>
		<link>http://www.xoltar.org/?p=125</link>
		<comments>http://www.xoltar.org/?p=125#comments</comments>
		<pubDate>Mon, 24 Dec 2012 18:00:00 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[azure]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=125</guid>
		<description><![CDATA[In the previous article, we created a very simple starter web application and published it to Windows Azure. In this post, we&#8217;ll look at how to diagnose problems with that application. Since we&#8217;re deploying our application to Azure , we don&#8217;t have access to the Windows event log, or to log files that we might&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.xoltar.org/?p=109">previous article</a>, we created a very simple starter web application and published it to Windows Azure. In this post, we&#8217;ll look at how to diagnose problems with that application.</p>
<p>Since we&#8217;re deploying our application to Azure , we don&#8217;t have access to the Windows event log, or to log files that we might&#160; generate, in the way we would if we were hosting in a more traditional environment (or in a <a href="https://www.windowsazure.com/en-us/home/features/virtual-machines/">Windows Azure virtual machine</a> for that matter). Fortunately, we do have other tools available.</p>
<p>Let&#8217;s look at some tools we can use to diagnose a problem that we already have with our simple application. If we navigate to /account/login on a locally running version of the site, it comes up without any problems. Visit the same URL on the Azure version, and instead you get an error page. The page is intentionally vague about the cause of the error.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb9.png" width="360" height="50" /></a> </p>
<p>At this point, you are probably wanting to turn off the custom error messages so you can see the exception. Let&#8217;s return to the <a href="https://manage.windowsazure.com">management portal</a> to do that. Click on the Websites side-tab, select your site, then click the Configure link. Scroll down a bit to the Diagnostics section.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image10.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb10.png" width="378" height="274" /></a> </p>
<p>Turn on all three of the diagnostic options. Don’t forget to scroll down and click the Save button.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image11.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb11.png" width="389" height="302" /></a> </p>
<p>Then try your application again. It will take a little while to respond – essentially, you’ve just changed the web.config, so it’s restarting. Now you’ll get <em>detailed error messages</em>. That doesn’t mean you’ll see the yellow screen of death. The end-user experience is the same. What you get with the detailed error messages is the ability to see those error messages in the management portal. The detailed error messages and logs get written to an FTP site, which you can access once you’ve configured a user name. You’ll find the link for that on the Dashboard page of the portal, on the right side and down a bit:</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image12.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb12.png" width="235" height="226" /></a> </p>
<p>After you do that, your username and FTP URL will both show up in the section below the “quick glance.” Click on the FTP URL and you can view the detailed errors, one html file per error. The full IIS logs for your site are there as well, so you can download and analyze them at your leisure.</p>
<p>The detailed error message for this problem isn’t very helpful, though:</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image13.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb13.png" width="435" height="300" /></a>&#160; </p>
<p>If only there were a way to see the stack trace… </p>
<h2></h2>
</p>
</p>
<h2>ELMAH To The Rescue</h2>
<p>There’s a great package called <a href="http://code.google.com/p/elmah/">Elmah</a> that provides handlers that you can install into your web application. These handlers record exceptions that your application encounters, logs them, and also makes them available for your review <em>directly within your web site</em>. This is not an Azure-specific package, but it will work just fine with your Azure web site.</p>
<p>Go ahead and install the Elmah NuGet package. Since we’re using an MVC site, you can install the Elmah.MVC package, which will automatically install the base Elmah package as well. You can either use the “Manage NuGet Packages” option you get when right-clicking the project in Visual Studio Solution Explorer, or you can do “Install-Package Elmah.MVC” in the Package Manager Console.</p>
<p>Once that’s done, you can republish you application to Azure. If you visit your /account/login URL again, it will still fail. Then you can visit /elmah on your site. This will tell you “You do not have permission to view this directory or page.” This is good – you don’t want random Internet users to be able to read your error logs! To enable you to read the errors right now, though, let’s change the web.config. At the end, just before the &lt;/configuration&gt; end tag, add a section like this:</p>
<pre class="brush: xml;">  &lt;elmah&gt;
      &lt;security allowRemoteAccess=&quot;1&quot; /&gt;
  &lt;/elmah&gt;</pre>
<p>Now you can republish to Azure. Once you’ve done that, you should be able to go to yourappname.azurewebsites.com/elmah, and see something like this:</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image14.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb14.png" width="218" height="130" /></a> </p>
<p>Try /account/login again, then go back to /elmah. Now you’ll see an entry for the exception you just experienced. Click on it, and you’ll see that yellow screen of death you’ve been missing!</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image15.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb15.png" width="444" height="193" /></a> </p>
<p>When we scroll over to the right a bit, we finally see the problem: <code>System.InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see <a href="http://go.microsoft.com/fwlink/?LinkId=256588">http://go.microsoft.com/fwlink/?LinkId=256588</a> </code></p>
<p><code>---&gt; System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ---&gt; System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. </code></p>
<p><code>---&gt; System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.) </code></p>
<p><code>---&gt; System.ComponentModel.Win32Exception: The system cannot find the file specified</code></p>
<p>So, the reason we cannot access the login page is because we have not yet set up a database in which to store the login information! In the next episode, we’ll fix this problem and start actually building our application.</p>
<h2>Important:</h2>
<p>Right now, your web application will let anybody view your error information via the /elmah URL! Be sure to remove or comment out that &lt;security allowRemoteAccess=&quot;1&quot; /&gt; . Once we have login working, we can configure it so that only administrators have access to that URL, but for now, it needs to be disabled!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=125</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building an Azure Web Site Application, Part I</title>
		<link>http://www.xoltar.org/?p=109</link>
		<comments>http://www.xoltar.org/?p=109#comments</comments>
		<pubDate>Fri, 23 Nov 2012 17:00:00 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[azure]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=109</guid>
		<description><![CDATA[In this series, I’ll be discussing the process of building a simple, but complete, .Net 4.5 web application, and how to host and manage it in Windows Azure. We won’t be skipping anything in this series – this will be a real application that will be live on the web, so it will have to [...]]]></description>
			<content:encoded><![CDATA[<p>In this series, I’ll be discussing the process of building a simple, but complete, .Net 4.5 web application, and how to host and manage it in Windows Azure. We won’t be skipping anything in this series – this will be a real application that will be live on the web, so it will have to take things like security and exception handling seriously. It will eventually be performing a service that is hopefully useful to people, it’s not only an Azure demo. I’ll be covering things in detail, but may skip some steps – if you’ve never made a .Net web application at all before, you’d probably be better off starting with one of the tutorials on <a href="http://www.asp.net">www.asp.net</a>.</p>
<h2>Creating the Project</h2>
<p>I’ll be using <a href="http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-for-web">Visual Studio Express 2012 for Web</a>. The easiest way to install this with the Azure tools is probably using <a href="http://go.microsoft.com/fwlink/?LinkID=254364&amp;clcid=0x409">this package from the Windows Azure site</a>. Create a new project, and choose C#, then Web, and pick the ASP.NET MVC 4 Web Application.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb.png" alt="image" width="505" height="209" border="0" /></a></p>
<p>Next, I install Twitter Bootstrap, because I like it. You can use the default stuff instead, or install some other framework if you prefer.</p>
<p>In the Package Manager Console (that’s View –&gt; Other Windows –&gt; Package Manager Console, by the way), do:</p>
<pre>install-package twitter.bootstrap.mvc4
install-package twitter.bootstrap.mvc4.sample</pre>
<p>&nbsp;</p>
<p>I see a couple of error messages in Visual Studio at this point, but the Readme advises me to close and restart Visual Studio, and so I do. After that, it&#8217;s fine.</p>
<p>&nbsp;</p>
<p>I also make a small change to Views\Shared\_BootstrapLayout.cshtml, to let it render a section called “featured” that’s included in the default Index.cshtml – without making that change or a similar one, we would get an error.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image1.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb1.png" alt="image" width="515" height="245" border="0" /></a></p>
<p>After this, we can do Ctrl-F5 and we’ve got a running site.</p>
<h2>Setting up the Azure Web Site</h2>
<p>Now that we’ve got our web application running, we need to publish it to Azure. I’ll assume you’ve already signed up for Azure – if not, why not start with the <a href="https://www.windowsazure.com/en-us/pricing/free-trial/">free trial</a>? To create the web site is really simple – just go to your <a href="https://manage.windowsazure.com/">management portal</a>, click on the Web Sites side-tab.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image2.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb2.png" alt="image" width="208" height="270" border="0" /></a></p>
<p>Then click the big “New” button at the bottom of the page:</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image3.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb3.png" alt="image" width="244" height="113" border="0" /></a></p>
<p>Choose the “Quick Create” option – this will let you get a site up after just specifying a name.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image4.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb4.png" alt="image" width="622" height="191" border="0" /></a></p>
<p>Then just enter a name for your site, pick a region near you, and click on “Create web site.”</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image5.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb5.png" alt="image" width="246" height="315" border="0" /></a></p>
<p>When the creation process finishes, your site will automatically be available on the web at whatever_name_you_picked.azurewebsites.net.</p>
<h2></h2>
<h2>Publishing</h2>
<p>In Visual Studio 2012, you can now easily publish your existing web application directly to the Azure Web Site you just set up. Just right-click on the project and choose Publish.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image6.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb6.png" alt="image" width="302" height="163" border="0" /></a></p>
<p>This leads to a dialog where you can choose a deployment profile. Deployment profiles are files that tell Visual Studio what it needs to know to publish to the correct location. Fortunately, Azure can provide you with a deployment profile automatically. Go back to the Azure management portal, click on the Web Sites side-tab, then click on the name of the web site you just set up. This brings you to the dashboard for your site. Under the bandwidth/usage chart and off to the right (you may have to scroll down a bit) there is a “quick glance” section. In that section is a link to “Download publish profile,” which is what you want. Click that and you’ll download the profile for your site.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image7.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb7.png" alt="image" width="244" height="242" border="0" /></a></p>
<p>Now switch back to Visual Studio, and bring up the Publish dialog again. Click the Import button to import your new profile.</p>
<p><a href="http://www.xoltar.org/blog/wp-content/uploads/image8.png"><img style="display: inline; border: 0px;" title="image" src="http://www.xoltar.org/blog/wp-content/uploads/image_thumb8.png" alt="image" width="314" height="91" border="0" /></a></p>
<p>Once you’ve got your profile installed and selected, you can click Next to see what it’s imported, or just click Publish to do the publishing. Once the deployment process has completed, it will open your application in the browser – your web application has now been published, and you can republish at any time without having to import the profile again, it’s now part of your project.</p>
<h2>Next Steps</h2>
<p>In the next installment, we’ll talk about error handling and diagnostics!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=109</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Transactional Objects</title>
		<link>http://www.xoltar.org/?p=87</link>
		<comments>http://www.xoltar.org/?p=87#comments</comments>
		<pubDate>Mon, 05 Nov 2012 07:47:58 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[transaction]]></category>
		<category><![CDATA[xoltar#]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=87</guid>
		<description><![CDATA[Every now and then, developers run into a situation where they need an in-memory object to participate in a transaction, and do all the things that transactional things do. One example of a situation that calls for transactional objects is caching. Suppose you’re in a transaction, inserting, updating, deleting things in a database. After making [...]]]></description>
			<content:encoded><![CDATA[<p>Every now and then, developers run into a situation where they need an in-memory object to participate in a transaction, and do all the things that transactional things do. One example of a situation that calls for transactional objects is caching. Suppose you’re in a transaction, inserting, updating, deleting things in a database. After making each of these changes, you update your cache as well.</p>
<p>Then something goes wrong. The transaction rolls back. The database is restored to a pristine state, just as it was at the beginning of your transaction. Your cache, on the other hand, is tainted. There are data in your cache that aren’t in your database.</p>
<p>You may come up with a strategy for delaying cache updates until after the transaction has completed. That’s fine, except that you rely on your cache being up-to-date – if you have changes in the database that aren’t reflected in the cache, you’ve got a different kind of tainting. All sorts of unreliability and special casing begin to creep in. So in the end, you either have to cache only things that will never change, or you have to make your cache transaction-aware.</p>
<p>This is an important use-case, however it’s surprisingly rarely discussed. Haskell has Software Transactional Memory (STM), but there’s nothing like that in .Net. On the other hand, the .Net framework offers an interface, <code>IEnlistmentNotification</code>, that you can implement in classes that need to react to transaction events like commit and rollback. It’s actually fairly easy to implement, but there are some tricky areas that I’ll point out. With <code>IEnlistmentNotification</code> in hand, we can create our transactional cache.</p>
<h2></h2>
<h2>Planning</h2>
<p>Let’s first agree on what we’re trying to build. To simplify the problem a little, we’ll leave out caches for the moment, and just ask: What would it take to make a transactional <em>dictionary</em>? Such a dictionary would have to support the sorts of guarantees that people expect of transactions. These guarantees are known as ACID – Atomicity, Consistency, Isolation, and Durability.</p>
<h3>Atomicity</h3>
<p>This means that the transaction succeeds or fails as a single unit. If anything goes wrong in a transaction, <em>all </em>of the work done in that transaction must be undone, as if it never happened.</p>
<h3>Consistency</h3>
<p>The system moves from one consistent state to another. At no point can the system be inconsistent.</p>
<h3>Isolation</h3>
<p>The changes that one transaction makes are undetectable to code that’s running in a different transaction, until the transaction commits. Once the transaction is complete, its results are visible throughout the system.</p>
<h3>Durability</h3>
<p>Once a transaction has been committed, it remains so – it cannot be undone, nor can it be lost due to power failure or other catastrophe. In our case, we’re talking about a volatile resource, a dictionary residing in memory, so we’re not really concerned with durability in the same sense that a database management system would be.</p>
<h3>The Approach</h3>
<p>The transactional dictionary we’re going to build will have the following properties:</p>
<ul>
<li>Changes made to the dictionary within a transaction will not be visible outside of that transaction, until the transaction completes.</li>
<li>If the transaction rolls back, there will be no changes made to the dictionary.</li>
<li>If the transaction commits, the dictionary will be permanently updated with the changes executed during the transaction</li>
<li>Unlike a database, we’re not going to concern ourselves with locking or trying to manage the order of transaction execution, we simply want to make sure that failed transactions don’t leave stale data in the dictionary. However, we will lock the dictionary while each transaction is committing.</li>
</ul>
<h1></h1>
<h2>The Implementation</h2>
<p>We know that we need to implement <code>IEnlistmentNotification</code> to participate in a transaction. We also need to <em>enlist</em> in the transaction in order to get the notifications. Enlisting is easy enough, and looks like this:</p>
<pre class="brush: fsharp;">txn.EnlistVolatile(this, EnlistmentOptions.None)</pre>
<p>Where <code>txn</code> is a reference to a <code>Transaction</code>, usually obtained via <code>Transaction.Current</code>. The “this” argument needs to be a class that implements <code>IEnlistmentNotification</code>.</p>
<p>The implementation of <code>IEnlistmentNotification </code>is also fairly straightforward. Suppose that we have a dictionary that represents the consistent state of our transactional dictionary. We’ll call this the “backing store.” While things are happening during a transaction, the backing store doesn’t change, instead we store those changes in a different location that we’ll call the “transactional values.” When the transaction commits, we need to update the backing store with the results of transaction, i.e. the contents of the transactional values.</p>
<h4>A Word on F#</h4>
<p>I’m implementing this in F#, rather than C#. This is not because this problem is particularly well suited to functional programming or immutable data structures – in fact, this problem is mostly about state and mutability. I do favor a functional approach in general, but I’m using F# here mostly because it’s shorter and clearer than C#, which means it takes me less time to read, write, and debug. Since I’m doing this on my own time and have no other constraints that dictate what language I should use, I choose what I perceive as the best general-purpose language available for .Net, F#. Your mileage may vary, use what makes you happy.</p>
<p>One additional note: I’ve used generic classes based on built-in framework interfaces, and type variable names in the style of the <a href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756">Framework Design Guidelines</a> (<code>'TKey</code> instead of <code>'k</code>, for instance) to encourage reuse from other .Net languages. This is not intended to be an F#-specific library.</p>
<h3>The Tricky Bits</h3>
<p>The first tricky bit is that when the transaction notifies your code that the transaction is done, either via calling <code>Commit</code> or <code>Rollback</code>, <code>Transaction.Current</code> is <strong>null</strong>, and there’s no <code>Transaction</code> property on the <code>enlistment</code> object that is passed by the transaction manager. This means that the class that gets the notification must know what transaction it’s being notified about already, meaning it must only be working with one and only one transaction. This forces our design to be one in which we create a new instance of a class for each transaction, and assign the management of that transaction to the new instance, rather than handling it in the transactional dictionary itself.</p>
<p>The second tricky bit is that we need to track both the addition of new keys as well as the removal of keys. That means we need a data structure that will track both. We’ll deal with this by storing an F# <code>Option&lt;'T&gt;</code> type instead of the raw value – values that are present in the dictionary will be represented by (Some value) and values that have been removed will be represented by None.</p>
<p>The third tricky bit is that our transactional dictionary needs to keep track of which of its transactional values helpers should receive each particular call, depending on the transaction of the current thread, but it also needs to remove its references to each transactional values helper when the transaction associated with that helper completes. Even if we enlisted the transactional dictionary in the transaction directly, it still wouldn’t know which transaction had committed, so it wouldn’t know which one to remove. So the helper has to be empowered to clean itself up. We’ll do this by passing a function to the helper that it can call to let the transactional dictionary know it’s ready to be cleaned up.</p>
<p>Working with transactions can be full of little surprises, which leads us to the fourth tricky bit. As <a href="http://ayende.com/blog/4528/who-stole-my-transaction">reported by Ayende</a> a couple of years ago (and <a href="http://go4answers.webhost4life.com/Example/sure-ienlistmentnotificationcommits-39328.aspx">other places as well</a>), it is actually possible for a <code>use </code>(C#: <code>using</code>) statement to end <em>before</em> your transaction commits, or rather, before your enlistment’s <code>Commit</code> method returns. The <code>Prepare</code>, <code>Commit</code>, and other methods on <code>IEnlistmentNotification</code> are called in a different thread from the one that creates and disposes the <code>TransactionScope</code>, so we&#8217;ll have to take appropriate steps (i.e. locking) to make sure that things work the user of our transactional dictionary would expect.</p>
<p>With those in mind, let’s dive into the implementation.</p>
<h3>TransactionalDictionary</h3>
<p>The transactional dictionary doesn’t reinvent the actual storage of the data – we have perfectly good data structures for that already. It takes a dictionary (the “backing store” we mentioned earlier) as a constructor argument. This is the “one source of truth” for our data, like a table in a database. We may overlay that data with changes, but we will never actually update the backing store until it comes time to commit the transaction.</p>
<pre class="brush: fsharp;">type TransactionalDictionary&lt;'TKey, 'TValue
        when 'TKey:equality
         and 'TValue: equality&gt;
            (backingStore:IDictionary&lt;'TKey,'TValue&gt;) = 

    //A mapping from transaction to our TransactionValues helper class</pre>
<pre class="brush: fsharp;">    let transactions = new Dictionary&lt;Transaction,TransactionValues&lt;'TKey, 'TValue&gt;&gt;()</pre>
<pre class="brush: fsharp;">    //A synchronization object for locking</pre>
<pre class="brush: fsharp;">    let sync = obj()</pre>
<pre class="brush: fsharp;">    //The lock that we use during the transaction commit process</pre>
<pre class="brush: fsharp;">    let transactionLock = new TransactionLock()</pre>
<pre class="brush: fsharp;"></pre>
<p>Since this is F#, we don’t have to explicitly store the backingStore parameter, it’s automatically available to all the methods of the type. We create a dictionary to map from transactions to a transaction-specific helper class that we’ll rely on heavily for most of the implementation of <code>TransactionalDictionary</code>. Then we create two synchronization objects – one, “sync” that we’ll use to control access to the transactions dictionary, and one, “transactionLock,” that will ensure that transactions don’t try to commit simultaneously. We do not require the backing store to be thread safe, so we have to provide the locking to ensure only one thread commits at a time.</p>
<h3>The IDictionary&lt;&#8217;TKey,&#8217;TValue&gt; Implementation</h3>
<p>The implementation of the dictionary operations themselves is almost trivial – they all involve calling a function called <code>getTxnValues</code> that returns the <code>TransactionValues</code> helper that we have stored for the current transaction, and then delegating the method call to the method of the same name on the <code>TransactionValues</code> helper. Here’s a sample, the implementation of the indexer:</p>
<pre class="brush: fsharp;">        member this.Item
                with get key = let tv = getTxnValues()
                               tv.[key]
                and  set key value = let tv = getTxnValues()
                                     tv.[key] &lt;- value</pre>
<h3>The getTxnValues Function</h3>
<p>This function is critical to the operation of the dictionary – it checks <code>Transaction.Current</code> to find out which transaction the code is participating in, and returns (via the <code>getValues</code> function) the <code>TransactionValues</code> helper instance associated with that transaction. If there is no instance assigned yet assigned to the current thread, and the thread is in a transaction, it creates one. If the thread is not in a transaction, then it can access the backing store directly.</p>
<pre class="brush: fsharp;">let getValues txn : IDictionary&lt;'TKey, 'TValue&gt; =
        if txn = null then
            backingStore
        else
            let dict = lock sync (fun () -&gt;
                                    let (containsKey,value) = transactions.TryGetValue txn
                                    match (containsKey,value) with
                                    | true, v -&gt; v
                                    | false, _ -&gt;
                                        let v = TransactionValues&lt;'TKey, 'TValue&gt;(
                                                            backingStore,
                                                            (fun () -&gt; transactionLock.Lock(txn)),
                                                            (fun () -&gt; transactionLock.Unlock |&gt; ignore
                                                                       lock sync (fun () -&gt; transactions.Remove txn |&gt; ignore)))
                                        transactions.[txn] &lt;- v
                                        v)
            dict :&gt; IDictionary&lt;'TKey,'TValue&gt;
    let getTxnValues () = getValues (Transaction.Current)</pre>
<p>First, we lock the synchronization object for the dictionary. After that, we’re free to read or modify our <code>Transaction</code>-to-<code>TransactionValues</code> dictionary as we like. If needed, we create a new <code>TransactionValues</code> helper instance, passing it the backing store for the <code>TransactionalDictionary</code>, and two functions. The first function is the one that <code>TransactionValues</code> will call when it’s ready to begin committing its changes to the backing store, and the second function will be called when it has completed its work, either by committing, or rolling back.</p>
<h3>The TransactionValues Helper</h3>
<p><code>TransactionValues</code> is really the type that does the greatest part of the work. Each <code>TransactionValues</code> instance manages the changes that have been executed in the context of a single transaction. It stores the changes in a dictionary of its own. While <code>TransactionalDictionary&lt;'TKey, 'TValue&gt;</code> maps <code>'TKey</code> to <code>'TValue</code>, <code>TransactionValues</code> maps <code>'TKey</code> to <code>Option&lt;'TValue&gt;</code>. Storing a value of <code>None</code> means that in the current transaction, that key was removed. Storing a value of <code>(Some v)</code> for a key means that in the current transaction, that key was set to a the value of v. Keys that are not present in the <code>TransactionValues</code> dictionary have to be looked up from the backing store.</p>
<p>We create this dictionary of changes in the constructor:</p>
<pre class="brush: fsharp;">    let transactionValues =
        if backingStore.IsReadOnly then
            raise (System.ArgumentException("Source dictionary is ReadOnly"))
        new Dictionary&lt;'TKey, 'TValue option&gt;()</pre>
<p>&nbsp;</p>
<p>Another important task for the constructor is to fix the knowledge of the transaction to which this instance is bound. It is at this point that we actually enlist in the transaction:</p>
<p>&nbsp;</p>
<pre class="brush: fsharp;">    let transaction =
        let txn = System.Transactions.Transaction.Current
        if txn = null then
            let msg = "TransactionValues can only be created in the context of an open transaction"
            raise (System.InvalidOperationException(msg))
        txn.EnlistVolatile(this, EnlistmentOptions.None) |&gt; ignore
        txn</pre>
<p>&nbsp;</p>
<p>Let’s look at the implementation of the indexer for <code>TransactionValues</code>:</p>
<pre class="brush: fsharp;">member this.Item
        with get key = getOrFail key
        and  set key value = transactionValues.[key] &lt;- Some value</pre>
<p>&nbsp;</p>
<p>Clearly, we need to see <code>getOrFail</code> as well! Here it is:</p>
<pre class="brush: fsharp;">    let get key =
        let (succ, value) = transactionValues.TryGetValue(key)
        match (succ, value) with
        | true, ((Some _) as v) -&gt; v
        | true, None -&gt; None
        | false, _ -&gt; match backingStore.TryGetValue(key) with
                      | true, v -&gt; Some v
                      | false, _ -&gt; None

    let getOrFail key = match get key with
                        | None -&gt; raise (KeyNotFoundException())
                        | Some v -&gt; v</pre>
<p>&nbsp;</p>
<p>You can see now how <code>TransactionalDictionary</code> delegates to the <code>TransactionValues</code> instance for the current transaction, and <code>TransactionValues</code> stores changes in a separate dictionary that it uses as an overlay over the original backing store.</p>
<h3>Commit, or Don’t</h3>
<p>So far, the code we have can store different changes for different transactions, and those transactions won’t be able to see each other’s changes. At some point, however, we’ll  want to actually commit or roll back the transaction. To do this, we implement the <code>IEnlistmentNotification</code> interface in the <code>TransactionValues</code> type. Here is the implementation, along with a few relevant functions:</p>
<pre class="brush: fsharp;">//The undo data needed to undo changes if a rollback happens during
//a 2-phase commit. Generated during the IEnlistmentNotification.Prepare method.
let mutable undo:seq&lt;'TKey * 'TValue option&gt; = Seq.empty

//Tracks whether the Prepare method has been run or not. Under some circumstances,
//Commit can be called without calling Prepare first, so Commit has to be be
//able to do the work of Prepare as well.
let mutable prepared = false

let updateWithPair (dictionary:IDictionary&lt;'a,'b&gt;) (kv:'a * 'b option) =
    let (k,value) = kv
    match value with
    | Some v -&gt;
        dictionary.[k] &lt;- v
    | None -&gt;
        dictionary.Remove k |&gt; ignore

let update (dictionary:IDictionary&lt;'TKey,'TValue&gt;) : seq&lt;'TKey*'TValue option&gt; =
    let undo = seq {
                    for kv in transactionValues do
                        let (has,old) = dictionary.TryGetValue(kv.Key)
                        updateWithPair dictionary (kv.Key, kv.Value)
                        yield kv.Key, (if has then Some old else None)
                        } |&gt; List.ofSeq :&gt; seq&lt;'TKey *'TValue option&gt;
    undo

let prep() = lockStore()
             undo &lt;- update backingStore
             prepared &lt;- true</pre>
<pre class="brush: fsharp;">interface System.Transactions.IEnlistmentNotification
        with
        member this.Commit(enlistment) =
            if not prepared then
                prep()
            finished()
            enlistment.Done()
        member this.InDoubt(enlistment) =
            enlistment.Done()
        member this.Prepare(enlistment) =
            try
                prep()
                enlistment.Prepared()
            with e -&gt; enlistment.ForceRollback(e)
        member this.Rollback(enlistment) =
            for kv in undo do
                updateWithPair backingStore kv
            undo &lt;- Seq.empty
            finished()
            enlistment.Done()</pre>
<p>Notice the calls to <code>finished()</code> and <code>lockStore()</code>. These are the functions that were passed by the <code>TransactionalDictionary</code> to the <code>TransactionValues</code> instance in the constructor. The <code>lockStore</code> function locks the dictionary while it’s being updated, so no other transaction can update it at the same time. Then we replay all the changes that have been made over the course of the transaction, updating and deleting keys in the backing store. As we go, we keep a record of the changes that we made. If something goes wrong and the transaction has to be rolled back, we undo the changes we just made using the undo information.<strong> </strong></p>
<p>When the transaction either commits or rolls back, then <code>finished()</code> is called to release the lock on the dictionary so that other transactions can update it.</p>
<p>The normal course of events is that the <code>Completed</code> method is called on the <code>TransactionScope</code> before it is disposed, then the transaction manager will call <code>Prepare</code> on each <code>IEnlistmentNotification</code>. If each of them replies with a call to <code>Prepared</code> on the enlistment object, then the transaction manager calls <code>Commit</code> on each <code>IEnlistmentNotification</code>.</p>
<p>Note that <code>Commit</code> is never supposed to fail – you’re expected to have already done the work you needed to do in <code>Prepare</code>, and <code>Commit</code> is just letting you know that this transaction is officially done. If something goes wrong in <code>Prepare</code>, you call the <code>ForceRollback</code> method on the enlistment, and this causes the transaction to roll back.</p>
<p>The documentation says that the methods may not necessarily be called in this order, however, which is why the <code>Commit</code> implementation above is built to also do the work of <code>Prepare</code> if the <code>Prepare</code> method was never called.</p>
<h2>The Result</h2>
<p>Now we have a fully transaction-aware dictionary. The same kind of logic can be extended to your cache, or to other kinds of transaction-aware objects you may need. I hope you find it useful. Please let me know if you have any comments, questions, or suggestions.</p>
<h2>Get The Code</h2>
<p>All the code for this article and more is available on GitHub as part of the <a href="https://github.com/xoltar/xoltar-sharp">xoltar-sharp</a> repository. The xoltar-sharp repository is a (currently very small) collection of utilities to simplify the development of complex applications. The transactional dictionary discussed in this article is the first of hopefully many tools that will be added to the xoltar-sharp package over time. I’ll also be releasing it as a NuGet package when it’s ready.</p>
<h2>References and Acknowledgements</h2>
<p>Thanks to F# guru <a href="http://trelford.com/blog/">Phil Trelford</a> for graciously reviewing the transactional dictionary code!</p>
<p>Thanks to Microsoft for making <a href="http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-for-web">a version of Visual Studio</a> that <a href="http://www.microsoft.com/en-us/download/details.aspx?id=34675">supports F#</a> available for free!</p>
<p>By far the most useful article I read while researching this one was Juval Lowy’s article, <a href="http://msdn.microsoft.com/en-us/magazine/cc163688.aspx">Volatile Resource Managers in .Net Bring Transactions to the Common Type</a>, on MSDN. The TransactionLock type in xoltar-sharp (mentioned in this article, but not examined) is almost entirely based on on Lowy’s C# TransactionLock</p>
<p>&nbsp;</p>
<p>Others that were useful include:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ckawh9ct(v=vs.85).aspx">Committing a Transaction in Single-Phase and Multi-Phase</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms172153.aspx">Enlisting Resources as Participants in a Transaction</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/b3b0471d.aspx">IEnlistmentNotification Interface</a></li>
<li><a href="http://ayende.com/blog/4528/who-stole-my-transaction">Who stole my transaction?</a></li>
<li><a href="http://blogs.msdn.com/b/natemoch/archive/2005/08/29/457580.aspx">How do I create a transacted resource?</a></li>
<li><a href="http://blog.jordanterrell.com/post/IEnlistmentNotification-Implementation-Nuances.aspx">IEnlistmentNotification: Implementation Nuances</a></li>
<li><a href="http://go4answers.webhost4life.com/Example/sure-ienlistmentnotificationcommits-39328.aspx">How to be sure that all IEnlistmentNotification.Commits are called?</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=87</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>My F# Wish List</title>
		<link>http://www.xoltar.org/?p=84</link>
		<comments>http://www.xoltar.org/?p=84#comments</comments>
		<pubDate>Thu, 23 Aug 2012 16:13:25 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[f#]]></category>
		<category><![CDATA[wish list]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=84</guid>
		<description><![CDATA[F# is a lovely language. I’m really glad it exists, and I love working with it. However, there is some room for improvement! I’ve gathered a list of all the things that I think are “missing” from F# today. A few of these I’ve found on UserVoice since I started compiling this list, and I’ll [...]]]></description>
			<content:encoded><![CDATA[<p>F# is a lovely language. I’m really glad it exists, and I love working with it. However, there is some room for improvement! I’ve gathered a list of all the things that I think are “missing” from F# today. A few of these I’ve found on <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/category/30935-languages-f-">UserVoice</a> since I started compiling this list, and I’ll soon be adding the ones that aren’t there already. I’ll also update this post as I think of more.</p>
<h1></h1>
<h3></h3>
<h3>1. Named Constraints</h3>
<p>I have lots of constraints in my code, things like: </p>
<pre class="brush: fsharp;">type Thing =
    abstract member Foo : int

let foo&lt;'a, 'b
            when 'a &lt;: Thing
             and 'b : comparison&gt; () =
    failwith &quot;not implemented&quot;

let bar&lt;'a, 'b
            when 'a &lt;: Foo
             and 'b : comparison&gt; () =
    failwith &quot;not implemented&quot;</pre>
<p>Repeating those constraints over and over again is <em>so</em> not DRY. I wish I could define that constraint once and just reference it where needed.</p>
<h3>2. <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2313123-implement-compiler-as-a-service-for-f-">Compiler as a service</a></h3>
<p>Aside from the fact that C# and VB are getting compiler as a service, there’s the additional justification provided by F# quotations. When you have something as useful as F# quotations, why not provide a method to <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2314016-compiling-quotations">compile them to good quality code</a>?</p>
<h3>3. Type classes</h3>
<p>F# doesn’t support <a href="http://en.wikipedia.org/wiki/Type_class">type classes</a>, which means that lots of useful things from Haskell don’t port easily. For instance, if you want to use map, you have to specify List.map, Seq.map, SomeOtherThing.map, etc., but with type classes, we could have a single “map” function that would find the right implementation depending on the (static) types it’s called on. There are <a href="http://code.google.com/p/fsharp-typeclasses/">workarounds</a>, but they’re not the real thing. We need the real thing.</p>
<h3>4. Parameterized Modules</h3>
<p>One thing I tried to make my constraints DRY was to mention them at the module level:</p>
<pre class="brush: fsharp;">type Thing =
    abstract member Foo : int

module ThingMod&lt;'a, 'b
            when 'a &lt;: Thing
             and 'b : comparison&gt; =

    let foo () =
        //code that mentions 'a or 'b
        failwith &quot;not implemented&quot;

    let bar () =
        //code that mentions 'a or 'b
        failwith &quot;not implemented&quot;</pre>
<p>Of course this isn&#8217;t supported at all, but I can&#8217;t see a reason why it shouldn&#8217;t be.</p>
<p>For that matter, it’s a shame that the full ML module system isn’t supported. I really wish we could have either ML modules or type classes. Don’t need both, but do need one or the other.</p>
<h3>5. Better syntax for anonymous functions</h3>
<p>I know it’s traditional, but (fun x –&gt; expr) is too clunky when C# is doing x&#160; =&gt; expr. </p>
<h3>6. Macros, campl4 style or otherwise</h3>
<p>Not having macros is limiting. You don’t need macro support often, but when you need it, you need it.</p>
<h3>7. Better Intellisense</h3>
<p>Intellisense for F# in VS 2012 is worlds better than in 2010, but it’s nowhere near as good as the C# support. Needs to work as well for F# as it does for C#.</p>
<h3>8. <a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2213611-provide-refactoring-support-for-f-code-">Refactoring support</a></h3>
<p>This is required in today’s world. <a href="http://youtrack.jetbrains.com/issue/RSRP-178987">ReSharper, I’m looking at you, too.</a>&#160;</p>
<h3>9. Folder Creation in Solution Explorer</h3>
<p>I can <em>have</em> folders in my F# project, I just can’t create them in Visual Studio. Disappointing. I can work around by editing the fsproj file, but I shouldn’t have to.</p>
<h3>10. More F# Developers at Microsoft!</h3>
<p>Come on, Microsoft! Your F# developers are doing great work, but you need more of them! It’s unacceptable that some Visual Studio features don’t work with F#, that things like Silverlight and Windows 8 get released with caveats like “F# is supported, but you have to use C# to build the front end.” Stop pretending this is a language that’s only useful for heavy computer science – it’s a general purpose language!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=84</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Snap on Azure</title>
		<link>http://www.xoltar.org/?p=83</link>
		<comments>http://www.xoltar.org/?p=83#comments</comments>
		<pubDate>Tue, 19 Jun 2012 07:59:48 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[azure]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[snap]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=83</guid>
		<description><![CDATA[Yesterday I started experimenting with Haskell on Azure by putting up a Snap server. It doesn’t do much, it’s just the default starter application you get when you do “snap init,” but it’s up and running on Azure. Here’s how it works. Start with the latest Haskell Platform. Then install the Snap packages with cabal. [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I started experimenting with Haskell on Azure by putting up a <a href="http://snapframework.com/">Snap</a> server. It doesn’t do much, it’s just the default starter application you get when you do “snap init,” but it’s up and running on Azure. Here’s how it works.</p>
<p>Start with the latest Haskell Platform. Then install the Snap packages with cabal. A record of the steps I had to perform on my system is <a href="http://www.xoltar.org/?p=81">here</a>. Once you’ve got a working Snap install, the easiest way to accomplish the steps listed below is to just clone the <a href="https://github.com/xoltar/snapazure">snapazure github repository</a>. After that you can skip to the “Packing and Deploying” section.</p>
<p>Start by adding the various configuration files that Azure needs to know how to package up the application. </p>
<p>The most important one is the .csdef file that tells Azure about the files that comprise your application. I’ll spare you the actual XML, please take a look at the repository. There’s an interesting trick in there for passing environment variables to the application so that it can listen on the correct host and port – credit for this is due to Steve Marx, who used it first in his <a href="https://github.com/smarx/pythonrole">pythonrole</a> project.</p>
<p>The .config files are also XML files, they specify primarily the number of instances of your service that Azure should run when you upload them.</p>
<p>Once those files are in place, make a folder called WorkerRole, cd into it, and do “snap init” to create your Snap application. Build it using “cabal install &#8211;bindir=.” so that the executable will be placed in the WorkerRole folder.</p>
<p><strong>Packing and Deploying </strong></p>
<p>Next, “cd ..” and then run “cspack ServiceDefinition.csdef” – this will create the ServiceDefinition.csx file, which is the archive that you’ll upload to Azure. You’ll then go create a Cloud Service, and upload the ServiceDefinition.csx along with the ServiceConfiguration.Cloud.config file to either the staging or production site. It may take quite some time (my first upload took around 15 minutes), but in the end you’ll have a Snap application running in your Azure account.</p>
<p>Here’s mine: <a href="http://snapdemo.cloudapp.net">http://snapdemo.cloudapp.net</a> </p>
<p>Github repo to get you started: <a href="http://github.com/xoltar/snapazure">http://github.com/xoltar/snapazure</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=83</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Snap on Windows</title>
		<link>http://www.xoltar.org/?p=81</link>
		<comments>http://www.xoltar.org/?p=81#comments</comments>
		<pubDate>Mon, 04 Jun 2012 05:06:12 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[cabal]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[snap]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=81</guid>
		<description><![CDATA[Snap is a web framework for Haskell. Here are some notes on what I had to do in order to make it work on Windows. Caveat emptor, your mileage may vary. Hopefully this is of use to someone. 1. Install the Haskell Platform. You want version 2012.2.0.0 or later. 2. Install Git. You’ll need this [...]]]></description>
			<content:encoded><![CDATA[<p><a title="http://snapframework.com/" href="http://snapframework.com/">Snap</a> is a web framework for <a href="http://www.haskell.org">Haskell</a>. Here are some notes on what I had to do in order to make it work on Windows. Caveat emptor, your mileage may vary. Hopefully this is of use to someone.</p>
<p>1. Install the </strong><a href="http://hackage.haskell.org/platform/windows.html">Haskell Platform</a>. You want version 2012.2.0.0 or later.</p>
<p>2. Install <a href="http://git-scm.com/download/win">Git</a>. You’ll need this later. </p>
<p>3. Open up a command prompt and type: </p>
<pre>cabal install snap</pre>
<p>This will run for some time, and, if your experience is like mine, eventually fail while trying to build the &quot;network&quot; package. It will complain about the fact that a configure script is present and that it needs a Unix toolchain for that. If this step actually succeeds for you, great, you&#8217;re done. If it failed on something else, good luck to you. </p>
<p>4. Open up a Git Bash window. Type: </p>
<pre>which ghc</pre>
<p>to find your GHC location. It will be something like /c/Program Files/Haskell Platform/2012.2.0.0/bin/ghc. In the 2012.2.0.0 folder will be GHC&#8217;s installation of mingw. Add the path to that mingw folder&#8217;s bin folder. On my machine, this looks like: </p>
<pre>export PATH=$PATH:/c/Program\ Files/Haskell\ Platform/2012.2.0.0/mingw/bin</pre>
<p>You can verify that you&#8217;ve done it right by checking to make sure you can run gcc: </p>
<pre>gcc --version</pre>
<p>if you get a message with a version number back, you&#8217;re ready for the next step.</p>
<p>4. Run:</p>
<pre>cabal install network</pre>
<p>Assuming that worked, go back to your original command window and do: </p>
<pre>cabal install snap</pre>
<p>5. If this fails with a compile error in the snap package as it did for me, then do: </p>
<pre>git clone git://github.com/snapframework/snap</pre>
<p>6. cd into the newly created &quot;snap&quot; folder </p>
<p>7. Run </p>
<pre>cabal install</pre>
<p>to build and install from the source version </p>
<p>You&#8217;re done! You can now follow the <a href="http://snapframework.com/docs/quickstart">Getting Started</a> guide to create your first Snap application. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=81</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>When Type Constraints Meet Reflection In F#</title>
		<link>http://www.xoltar.org/?p=72</link>
		<comments>http://www.xoltar.org/?p=72#comments</comments>
		<pubDate>Fri, 18 May 2012 14:48:00 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=72</guid>
		<description><![CDATA[When you use a “type constraint” in F#, the kind of constraint that specifies that the type has to extend from some other type, it’s possible to confuse the compiler (or more accurately: confuse yourself) into allowing some code that is guaranteed to fail at runtime. Here’s how it can happen. If you have a [...]]]></description>
			<content:encoded><![CDATA[<p>When you use a “type constraint” in F#, the kind of constraint that specifies that the type has to extend from some other type, it’s possible to confuse the compiler (or more accurately: confuse yourself) into allowing some code that is guaranteed to fail at runtime.</p>
<p>Here’s how it can happen. If you have a constraint like <code>&lt;'a when 'a :&gt; IFace&gt;</code>, where <code>IFace</code> is an interface type, if the compiler doesn’t have enough information to establish a concrete type for <code>'a</code>, then at runtime, <code>typeof&lt;'a&gt;</code> will actually be <code>IFace</code>, not some derived, concrete type as you might have hoped. This may sound obvious, but it probably won’t be, the first time it happens to you.</p>
<p>Below is a code sample that gives a real-world example. Here we’re trying to instantiate a record type via reflection. In two of the test cases, we give the compiler enough information, and it correctly uses a concrete type. When we don’t provide enough, it defaults back to <code>IFace</code>, which leads to trouble – it tries to instantiate <code>IFace</code> as if it’s a record type, which certainly doesn’t work. This isn’t a bug – after all, in pretty much any situation <em>not</em> involving reflection, the supertype is a reasonable default &#8211; but it can be surprising.</p>
<p>It would be great to have a new kind of type constraint that could insist that the type be instantiable, i.e. concrete, non-abstract. Maybe something like <code>&lt;'a when 'a :&gt; IFace and 'a:concrete&gt;</code>. With such a constraint in place, we’d get a compile error instead of a runtime error if the compiler couldn’t prove that the type was concrete at any particular call site. </p>
<p>For the moment, though, just be aware that there is no such constraint, and you have to consider the possibility that your constrained type might just be an interface type. There <em>is</em> the <code>'a : (new: unit-&gt;'a)</code> constraint that works just like the <code>new</code> constraint in C#, and that would help, except it only works with a no-args constructor, which wouldn’t be appropriate for our example at all, since we don’t even know ahead of time how many arguments we’re going to pass the constructor.</p>
<p>This is just something to be aware of, so when you get exceptions with messages like “Type &#8216;ConstraintTest+IFace&#8217; is not an F# record type,” or “Constructor on type ‘ConstraintTest+IFace’ not found,” you don’t spend too much time thinking “Of course it isn’t! Why did you <em>think</em> that would work, compiler?”</p>
<p>By the way, Matt Podwysocki has a great series on what you can do with constraints in F#: <a href="http://weblogs.asp.net/podwysocki/archive/2009/09/16/generically-constraining-f-part-i.aspx">Part 1</a>, <a href="http://codebetter.com/matthewpodwysocki/2009/09/28/generically-constraining-f-part-ii/">Part 2</a>, <a href="http://codebetter.com/matthewpodwysocki/2009/10/02/generically-constraining-f-part-iii/">Part 3</a>. You should definitely head there next.</p>
<pre>module ConstraintTest</pre>
<pre>open NUnit.Framework

    //A simple interface
    type IFace =
        abstract member X: int

    //A record type that implements the interface
    type Foo = {FooX:int}
        with
            interface IFace with
                member this.X = this.FooX

    //A function that instantiates a new record
    //There's a type constraint to ensure the record type implements IFace.
    let makeRecord&lt;'a when 'a :&gt; IFace&gt; (values: obj array) =
        let record = Activator.CreateInstance(typeof&lt;'a&gt;, values)
        record :?&gt; 'a

    [&lt;Test&gt;]
    let ``insufficient type info``() =
        //F# can't figure out the concrete type, defaults to substituting IFace for 'a
        let exc = Assert.Throws&lt;System.MissingMethodException&gt;(fun () -&gt; makeRecord [|1|] |&gt; ignore)
        printf &quot;%A\n&quot; exc

    [&lt;Test&gt;]
    let ``specified type``() =
        //We help F# figure out what the concrete type should be, no problem.
        let record:Foo = makeRecord [|1|]
        ()

    [&lt;Test&gt;]
    let ``specified type 2``() =
        //Again, we help F# figure out what the concrete type should be (in a different way), no problem.
        let record = makeRecord&lt;foo&gt; [|1|]
        ()</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=72</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Outnumbered by Robots</title>
		<link>http://www.xoltar.org/?p=73</link>
		<comments>http://www.xoltar.org/?p=73#comments</comments>
		<pubDate>Wed, 02 May 2012 20:31:35 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[life]]></category>
		<category><![CDATA[robots]]></category>
		<category><![CDATA[trends]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=73</guid>
		<description><![CDATA[I heard a piece on the radio the other day about robots. One reporter told the story of how he’d driven across the United States almost without speaking to another human being the whole time. Food via self-checkout at the grocery store, hotels via robots check-in systems, etc. This was all very amusing at first. [...]]]></description>
			<content:encoded><![CDATA[<p>I heard a <a href="http://www.npr.org/player/v2/mediaPlayer.html?action=1&amp;t=1&amp;islist=false&amp;id=150001560&amp;m=150001542">piece on the radio the other day about robots</a>. One reporter told the story of how he’d driven across the United States almost without speaking to another human being the whole time. Food via self-checkout at the grocery store, hotels via robots check-in systems, etc. This was all very amusing at first. Then the discussion turned to jobs.</p>
<p>It turns out that more and more people are being put out of a job by robots. Not just repetitive factory work, mind. <a href="http://www.slate.com/articles/technology/robot_invasion/2011/09/will_robots_steal_your_job_3.html">Pathologists</a>. <a href="http://thenextweb.com/media/2011/04/18/robot-journalist-writes-a-better-story-than-human-sports-reporter/">Sports reporters</a>. Soon, <a href="http://www.pcmag.com/article2/0,2817,2400400,00.asp">drivers</a>.&#160; There are, as we all know, lots of things computers do better than we do. That list is growing all the time, and it’s growing faster. Moore’s law says that computing power doubles every eighteen months, and if that continues to hold true, we’re going to start seeing almost unimaginable science fiction-type robots and computers, very, very soon.</p>
<p>People seem not to be paying attention to this issue. I don’t want to call it a problem, because it’s just reality. However, for many (most? all?) of us, it will feel like a problem. It’s not just a matter of losing your current job, of suffering economic loss until you can retrain and find your balance in this new world. It’s a matter of being <em>completely outmoded</em>.</p>
<p>There’s really nothing special about humans. Unusual, perhaps, but not unique. People routinely claim that this or that trait is “uniquely human,” without the faintest justification. My cats have most of these “uniquely human” characteristics, too.&#160; There are others that the cats don’t have, but they’re not uniquely human, either. Laughter was the one I heard last. Turns out rats laugh too. Tool use is an old one. Chimps. Ravens. Lots of things use tools. Not unique.</p>
<p>There’s also nothing about carbon that makes it uniquely better for supporting life than silicon. True, there are things that we’re better at than computers are, today. We have emotions, better vision, better language processing, a few other advantages. This will change. Computers are getting better, smarter, faster, every single day, and we’re staying basically the same. Evolution is obsolete. Robots <em>will</em> be better than us in every conceivable way, sometime soon. Maybe within my lifetime. My kids, if I ever have any, might well be the last human generation, unless we figure out some kind of way to live in a world where robots are better than us at everything.</p>
<p>We have to figure this out. Nobody’s going to stop improving robots or computers. To keep this from happening, we’d have to have <em>everyone</em> agree to stop. At the same time. Sort of like how we collectively decided to restrain the development of nuclear weapons. The important difference, though, is that the atom bomb looks like the end of the world. Better robots just look like a pile of cash for the people who make them. There’s no stopping piles of cash.</p>
<p>What we need to do is come up with a plan for how to deal with this transition. Can we come up with some way to improve ourselves as quickly as we improve technology? Can we somehow remain as we are, yet stay in control and actually have our lives improved? There are many unknowns. This could be a coming golden age, or it could easily be crisis in the making, as big a problem as clean drinking water or global climate change. Take some time to think about it. How can we prepare for the day when robots do <em>everything</em> better than we do?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=73</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>powershell: Upgrade All Your .Net Projects</title>
		<link>http://www.xoltar.org/?p=69</link>
		<comments>http://www.xoltar.org/?p=69#comments</comments>
		<pubDate>Tue, 13 Mar 2012 00:30:16 +0000</pubDate>
		<dc:creator>xoltar</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[powershell]]></category>

		<guid isPermaLink="false">http://www.xoltar.org/?p=69</guid>
		<description><![CDATA[Here’s a quick PowerShell script you can use to update all your projects to a new version of .Net. Lots faster than opening the properties window for each project in Visual Studio and then reloading. &#160; function set-frameworkversion($version) { #scan current directory and below for project files #Add project types as desired $projects = dir [...]]]></description>
			<content:encoded><![CDATA[<p>Here’s a quick PowerShell script you can use to update all your projects to a new version of .Net. Lots faster than opening the properties window for each project in Visual Studio and then reloading.</p>
<p>&#160;</p>
<pre>	function set-frameworkversion($version) {
		#scan current directory and below for project files
		#Add project types as desired
		$projects = dir -r . -include *.csproj,*.fsproj;
		$projects | % {
			$x = [xml](gc $_);
			$x.project.propertygroup[0].TargetFrameworkVersion = $version;
			 $x.save($_)
		}
	}</pre>
<p>&#160;</p>
<p>Use like this: <code>set-frameworkversion 'v4.5'</code></p>
<p>&#160;</p>
<p>If anyone knows a better way or has corrections, please share! </p>
]]></content:encoded>
			<wfw:commentRss>http://www.xoltar.org/?feed=rss2&#038;p=69</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
