<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/feed.xslt" media="screen"?>

<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>C# test.net</title>
	<atom:link href="http://csharptest.net/feed/index.xml" rel="self" type="application/rss+xml" />
	<link>http://csharptest.net/index.html</link>
	<description>another random site full of random stuff</description>
	<lastBuildDate>Tue, 21 Jun 2016 18:00:23 +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>Hello? Is anyone there?</title>
		<link>http://csharptest.net/1299/hello-is-anyone-there/index.html</link>
		<comments>http://csharptest.net/1299/hello-is-anyone-there/index.html</comments>
		<pubDate>Fri, 06 May 2016 20:21:27 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Home]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1299</guid>
		<description><![CDATA[Yes, I am still alive and coding.  Besides from blogging being so last decade, I&#8217;ve been excessively busy these past two years. In the course of a little over two years I left my cushy job, started a new one, watched it crash and burn, and went back to my former job, and left again <a href='http://csharptest.net/1299/hello-is-anyone-there/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Yes, I am still alive and coding.  Besides from blogging being so last decade, I&#8217;ve been excessively busy these past two years.</p>
<p>In the course of a little over two years I left my cushy job, started a new one, watched it crash and burn, and went back to my former job, and left again to work with a different former employer.  2014 was an exciting and fun for a year watching and helping the BPlusTree perform inside a from-scratch effort to build a .NET NoSQL database.</p>
<p>At present I am no longer working with C#, or even Microsoft Windows for that matter. I&#8217;m enjoying life on the edge working with nodejs, React, Couchbase, etc.  Since I am no longer involved, I am archiving this site and will not be posting again.</p>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSharpTest.Net.Collections v14.906.1403.1082</title>
		<link>http://csharptest.net/1293/csharptest-net-collections/index.html</link>
		<comments>http://csharptest.net/1293/csharptest-net-collections/index.html</comments>
		<pubDate>Sat, 06 Sep 2014 19:54:32 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[BPlusTree]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[Library]]></category>
		<category><![CDATA[b+tree]]></category>
		<category><![CDATA[collection]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1293</guid>
		<description><![CDATA[So, just finally made time to port the last project out of my old Google code repo. So here are all the links for the new packages and repositories: BPlusTree (and supporting parts of Library) -&#62; CSharpTest.Net.Collections https://github.com/csharptest/CSharpTest.Net.Collections https://www.nuget.org/packages/CSharpTest.Net.Collections Library\Commands -&#62; CSharpTest.Net.Commands https://github.com/csharptest/CSharpTest.Net.Commands https://www.nuget.org/packages/CSharpTest.Net.Commands RpcLibrary -&#62; CSharpTest.Net.RpcLibrary https://github.com/csharptest/CSharpTest.Net.RpcLibrary https://www.nuget.org/packages/CSharpTest.Net.RpcLibrary Library\Tools\* -&#62; CSharpTest.Net.Tools https://github.com/csharptest/CSharpTest.Net.Tools https://www.nuget.org/packages/CSharpTest.Net.Tools The <a href='http://csharptest.net/1293/csharptest-net-collections/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>So, just finally made time to port the last project out of my <a href="https://code.google.com/p/csharptest-net">old Google code repo</a>. So here are all the links for the new packages and repositories:</p>
<p><strong>BPlusTree</strong> (and supporting parts of Library) -&gt; CSharpTest.Net.Collections<br />
<a href="https://github.com/csharptest/CSharpTest.Net.Collections">https://github.com/csharptest/CSharpTest.Net.Collections</a><br />
<a href="https://www.nuget.org/packages/CSharpTest.Net.Collections">https://www.nuget.org/packages/CSharpTest.Net.Collections</a></p>
<p><strong>Library\Commands</strong> -&gt; CSharpTest.Net.Commands<br />
<a href="https://github.com/csharptest/CSharpTest.Net.Commands">https://github.com/csharptest/CSharpTest.Net.Commands</a><br />
<a href="https://www.nuget.org/packages/CSharpTest.Net.Commands">https://www.nuget.org/packages/CSharpTest.Net.Commands</a></p>
<p><strong>RpcLibrary</strong> -&gt; CSharpTest.Net.RpcLibrary<br />
<a href="https://github.com/csharptest/CSharpTest.Net.RpcLibrary">https://github.com/csharptest/CSharpTest.Net.RpcLibrary</a><br />
<a href="https://www.nuget.org/packages/CSharpTest.Net.RpcLibrary">https://www.nuget.org/packages/CSharpTest.Net.RpcLibrary</a></p>
<p><strong>Library\Tools</strong>\* -&gt; CSharpTest.Net.Tools<br />
<a href="https://github.com/csharptest/CSharpTest.Net.Tools">https://github.com/csharptest/CSharpTest.Net.Tools</a><br />
<a href="https://www.nuget.org/packages/CSharpTest.Net.Tools">https://www.nuget.org/packages/CSharpTest.Net.Tools</a></p>
<p>The former package for CSharpTest.Net.BPlusTree has been deprecated. This package depended upon the CSharpTest.Net.Library and I wanted to make the package stand-alone.  To avoid causing unneeded headaches I&#8217;ve chosen to rename the package to eliminate the confusion with the previous version(s).  The new Collections package contains all the BPlusTree code, plus the code within the Library that it depended on.  Hopefully this stand-alone version will make it much more usable.</p>
<p>For all the packages, my goal was to not change code, add features, or fix bugs during the move.  This is 99% the case, a few changes were made to reduce dependencies in some cases, but the overall code remains basically the same.</p>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing the LurchTable as a C# version of LinkedHashMap</title>
		<link>http://csharptest.net/1279/introducing-the-lurchtable-as-a-c-version-of-linkedhashmap/index.html</link>
		<comments>http://csharptest.net/1279/introducing-the-lurchtable-as-a-c-version-of-linkedhashmap/index.html</comments>
		<pubDate>Tue, 28 Jan 2014 20:33:12 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[Library]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[dictionary]]></category>
		<category><![CDATA[queue]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1279</guid>
		<description><![CDATA[So to start with what does &#8220;LurchTable&#8221; stand for? Least Used Recently Concurrent Hash Table Of course I am dyslexic so I can get away with swapping U and R around. My dyslexia aside, It&#8217;s a fair representation of what the class does. It essentially is a ConcurrentDictionary that keeps and maintains a linked-list of <a href='http://csharptest.net/1279/introducing-the-lurchtable-as-a-c-version-of-linkedhashmap/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>So to start with what does &#8220;<strong><a href="http://help.csharptest.net/?CSharpTest.Net.Library~CSharpTest.Net.Collections.LurchTable%602.html">LurchTable</a></strong>&#8221; stand for?</p>
<div style="padding-left: 20px;"><strong>L</strong>east<br />
<strong>U</strong>sed<br />
<strong>R</strong>ecently<br />
<strong>C</strong>oncurrent<br />
<strong>H</strong>ash<br />
<strong>Table</strong></div>
<p>Of course I am dyslexic so I can get away with swapping U and R around. My dyslexia aside, It&#8217;s a fair representation of what the class does. It essentially is a ConcurrentDictionary that keeps and maintains a linked-list of nodes in specific way. It does differ significantly from ConcurrentDictionary in a few very important ways&#8230;</p>
<ol>
<li><strong>The number of hash buckets available can not change after construction.</strong> This keeps the code simple and maintainable while providing all the tread-safety goodness. This is also going to be the biggest change from the ConcurrentDictionary. The LurchTable is typically used with a hard-limit on items. For example a cache might allow no more than 10k items. So we probably want at least 5k hash buckets, each &#8216;bucket&#8217; is just an integer so this would pre-allocate 20kb of memory as an int[]. On the extreme end, if you were to supply int.Max as the hash size you would exceed .NET&#8217;s ability to allocate the memory required.</li>
<li><strong>Key/Value pairs (entries) are allocated and expanded dynamically as-needed.</strong> Unused entries are tracked in a separate linked-list. Unlike the .NET Framework&#8217;s Dictionary that will fail when adding the &#8216;nth&#8217; entry due to an OutOfMemoryException being raise, the LurchTable does not allocate all entries as a single array. The allocation size is specified (or derived) at construction and the LurchTable will allocate a new array of this size and &#8216;append&#8217; it to the existing allocated entries. This preserves time and memory as the contents of the dictionary fluctuate and prevent the LurchTable from attempting excessively large allocations.</li>
<li><strong>The linked lists, both used and unused entries, are maintained via lockless linked lists.</strong> The use of non-blocking linked lists allows for a high-degree of concurrent modifications to be made to the contents of the collection. This approach also greatly reduces the contention on the &#8216;free&#8217; entries required to find an empty entry to use for a new item. In addition, the LurchTable maintains several &#8216;free&#8217; lists to even further reduce contention.</li>
</ol>
<h4>Linking Entries</h4>
<p>Entries can be either non-linked, linked by insertion, lined by insertion or modification, or linked by insertion, modification or access. The internal linking strategy is determined at construction by specifying one of the LurchTableOrder enumeration members (Access, Insertion, Modified, None).  When ordering by anything other than None, a hard-limit on items can be specified at construction as well.  When a hard-limit is set, the insertion of n+1 items will cause the &#8216;oldest&#8217; item in the ordered list to be removed.  Typically all this is specified at construction by using the more verbose ctor on the LurchTable:</p>
<pre class="brush:csharp">
    public LurchTable&lt;TKey, TValue>(
        LurchTableOrder ordering,         // One of Access, Insertion, Modified, or None
        int limit,                        // Hard-limit number of items, or int.MaxValue for no limit
        int hashSize,                     // The number of hash buckets to allocate (adjusted up to a prime number)
        int allocSize,                    // The number of items to allocate at once (power of 2 that is < = allocSize)
        int lockSize,                     // The number of locks to allocate (adjusted up to a prime number)
        IEqualityComparer&lt;TKTKey> comparer  // The comparer to use for the keys
    )
</pre>
<h4>Other Deltas from the ConcurrentDictionary</h4>
<p>New methods not typically found on a dictionary include the ability to Peek, Dequeue, or TryDequeue the oldest item in the collection.  Peek will return the oldest entry based upon the link order.  TryDequeue will attept to remove the oldest entry based upon the link order and can optionally take a predicate to control removal.  Lastly, Dequeue is a tight-polling loop on TryDequeue and returns only after an item is successfully dequeued (Note: For obvious reasons Dequeue should be used cautiously).</p>
<p>All enumerations of the LurchTable are thread-safe and in Hash-order.  Due to the lockless nature of the internal linking, it is not possible to enumerate the contents of the collection in the linked order.  Enumeration of the links could easily be added; however, it would not be thread-safe and thus is not currently implemented.</p>
<p>All methods on the collection are thread-safe except the &#8220;Initialize&#8221; method.  The Initialize() method recreates the internal &#8216;entries&#8217; collection and essentially removes all items in O(1) whereas the Clear() method is now an O(n) time operation.</p>
<p>Events for ItemAdded, ItemUpdated, and ItemRemoved are exposed from the collection and are executed in-lock with the operation.  While I don&#8217;t like events that execute from synchronized code, there really isn&#8217;t a better way to deal with this.  Since I heavily rely on ItemRemoved events to flush data from a LurchTable cache to primary store, the event must act as an atomic operation to the consumer of the collection.  All events are fire after internal structures have been modified and just prior to lock-release.  Care should be taken not to raise exceptions from these events as these will propagate to the caller attempting to add/update/remove the item.</p>
<h4>Uses for LurchTable</h4>
<ul>
<li><strong>LRU Cache</strong> An LRU (Least Recently Used) cache is the most common of applications for this structure.  Simply configure a hard-limit on the items and use LurchTableOrder.Access at construction.  Then from the caller use the GetOrAdd call to either pull from cache or fetch from primary and add to cache in a single call.</li>
<li><strong>Write-through Cache</strong> Another common usage might be a write-behind/delayed-write strategy for an external storage mechanism.  Constructing with a hard-limit and using LurchTableOrder.Modified will give you a read-through/write-through cache. Use the GetOrAdd to fetch and any of the available set operations to write, then hook the ItemRemoved to flush to external storage.</li>
<li><strong>Throttling Work Queue</strong> An interesting use (or abuse?) of the LurchTable is using it to distribute work across several threads.  When a producer of work can outpace the ability of the consumers one needs to throttle the producer.  One way is to simply sleep the producer until more work can be queued, another is to let the producer also consume work.  Construct with LurchTableOrder.Insert and a hard-limit on the back-log to allow.  Hook the ItemRemoved event to implement the work item processing.  Start one or more threads producing work items by adding them to the dictionary.  Finally start one or more threads consuming data by calling Dequeue/TryDequeue.  This works well if the work to be performed is small (since the consumer can block the producer), mileage may vary for longer running tasks.</li>
</ul>
<p>I&#8217;ve used this collection extensively for the past year and have been very pleased with the results and ease of use.  It&#8217;s probably one of the more versatile and better pieces of code I&#8217;ve put together in a while.  Give it a try by just including the source directly (<a href="http://csharptest.net/browse/src/Library/Collections/LurchTable.cs" target="_blank">/browse/src/Library/Collections/LurchTable.cs</a>) or by using the <a href="https://www.nuget.org/packages/CSharpTest.Net.Library/" target="_blank">NuGet package CSharpTest.Net.Library</a>.  You can also find the online help at <a href="http://help.csharptest.net/?CSharpTest.Net.Library~CSharpTest.Net.Collections.LurchTable%602.html" target="_blank">http://help.csharptest.net</a>.</p>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Breaking apart the Library&#8230;</title>
		<link>http://csharptest.net/1272/breaking-apart-the-library/index.html</link>
		<comments>http://csharptest.net/1272/breaking-apart-the-library/index.html</comments>
		<pubDate>Sun, 26 Jan 2014 23:12:47 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1272</guid>
		<description><![CDATA[Time has clearly come to accomplish two things&#8230; Move to GitHub.com instead of google code Split the library apart based on consumer feedback Why move to GitHub?  While I still prefer mercurial there are a couple of things that motivate me to make the switch.  Firstly Google has utterly failed to get to a point <a href='http://csharptest.net/1272/breaking-apart-the-library/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Time has clearly come to accomplish two things&#8230;</p>
<ol>
<li>Move to <a href="https://github.com/">GitHub.com</a> instead of google code</li>
<li>Split the library apart based on consumer feedback</li>
</ol>
<div>Why move to GitHub?  While I still prefer mercurial there are a couple of things that motivate me to make the switch.  Firstly Google has utterly failed to get to a point where community contribution are easy and painless.  They also do not provide a whole-project download and with the removal of downloads I can no longer provide one easily.  Lastly I&#8217;m no longer receiving appropriate alerts about issues being entered, and thus much of your valuable feedback is being ignored.</div>
<div>
<p>As to breaking the library apart, I think it&#8217;s just well past due.  At the onset of this library the goal was not to really provide any one thing that was useful, but rather a collection of small things that support a larger project.  That just simply no longer holds true.  Many users have requested that the BPlusTree be split off as well as the SslTunnel and the RpcLibrary.  This makes a lot of sense as these components have matured to a state of being able to stand alone. So I am in the process of breaking out the following projects:</p>
<ul>
<li>CSharpTest.Net.Collections (BPlusTree, LurchTable, OrdinalList, and others)</li>
<li>CSharpTest.Net.Commands (The CommandInterpreter and dependecies)</li>
<li>CSharpTest.Net.RpcLibrary</li>
<li>CSharpTest.Net.SslTunnel</li>
<li>CSharpTest.Net.Tools (CmdTool, ResX Exception Generators, StampVersion, StampCopyright)</li>
</ul>
<div>I am leaning towards keeping the CSharpTest.Net.Library around but pruning out most of the functionality that is encompassed above as well as some more-or-less obsolete stuff.  The issue I struggle with is keeping it&#8217;s name or not&#8230;  TBD<br />
&nbsp;</div>
<div>Also, be aware that projects are being migrated to .NET 4 builds with Visual Studio 2012 projects.  They should still compile under 2.0/3.5 but after this past release they will no longer be included in nuget packages.<br />
&nbsp;</div>
<div>Please leave comments if you like to make any specific requests regarding the move/transition&#8230;</div>
</div>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Version 2.14.126.467 Released</title>
		<link>http://csharptest.net/1268/version-2-14-126-467-released/index.html</link>
		<comments>http://csharptest.net/1268/version-2-14-126-467-released/index.html</comments>
		<pubDate>Sun, 26 Jan 2014 22:51:16 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1268</guid>
		<description><![CDATA[Additions in this release: Added CSharpTest.Net.Collections.LurchTable a thread-safe dictionary with the option of linking entries by insert, modify, or access. (LinkedHashMap for C#) Added CSharpTest.Net.Data.DbGuid to provide time based sequential GUID generation (COMB Guid). BPlusTree added INodeStoreWithCount and allowed injection of IObjectKeepAlive implementation. Added Crc64 for a quick 64-bit CRC using algorithm (CRC-64/XZ) Added a <a href='http://csharptest.net/1268/version-2-14-126-467-released/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p><strong>Additions in this release:</strong></p>
<ol>
<li>Added CSharpTest.Net.Collections.LurchTable a thread-safe dictionary with the option of linking entries by insert, modify, or access. (LinkedHashMap for C#)</li>
<li>Added CSharpTest.Net.Data.DbGuid to provide time based sequential GUID generation (COMB Guid).</li>
<li>BPlusTree added INodeStoreWithCount and allowed injection of IObjectKeepAlive implementation.</li>
<li>Added Crc64 for a quick 64-bit CRC using algorithm (CRC-64/XZ)</li>
<li>Added a simple HttpServer class.</li>
<li>Added Services/ServiceAccessRights and Services/SvcControlManager to provide more control over services.</li>
<li>Added Http/MimeMessage to parse raw HTML form where ContentType = &#8220;multipart/form-data&#8221;, including one or more attachments.</li>
<li>Extended the CommandInterpreter to allow exposing console commands over REST services via built-in service.</li>
<li>Added a CallsPerSecondCounter to allow quick estimation of performance metrics in high-traffic code.</li>
<li>Added an experimental TcpServer (currently under test)</li>
<li>Extended the RpcError enumeration to encompass more errors and decorated descriptions.</li>
<li>RpcLibrary now supports RpcServerRegisterIf2 allowing un-authenticated TCP access and control of max TCP request size.</li>
<li>Added the IDL for the RpcLibrary for unmanaged interop</li>
</ol>
<p><strong>Fixes in this release:</strong></p>
<ol>
<li>Converted BPlusTree&#8217;s Storage.Cache to use LurchTable to address memory issues in buggy LRU cache.</li>
<li>Optimization of BPlusTree&#8217;s TransactedCompoundFile in location of free data blocks.</li>
<li>Fixed the dreaded SEHException in the RpcLibrary, now expect acurate RpcException with correct RpcError details.</li>
</ol>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding the pitfalls of using System.Guid with sequential values</title>
		<link>http://csharptest.net/1258/understanding-the-pitfalls-of-using-system-guid-with-sequential-values/index.html</link>
		<comments>http://csharptest.net/1258/understanding-the-pitfalls-of-using-system-guid-with-sequential-values/index.html</comments>
		<pubDate>Tue, 04 Dec 2012 02:43:20 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[BPlusTree]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[Library]]></category>
		<category><![CDATA[b+tree]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[guid]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1258</guid>
		<description><![CDATA[In my previous post &#8220;Why GUID primary keys are a database’s worst nightmare&#8221; I spoke about some of downsides to using GUID primary keys. In this post I&#8217;m going to focus more specifically on the .NET Framework&#8217;s implementation of System.Guid. I have a few complaints about this class, let&#8217;s cover them&#8230; 1. Guid.ToByteArray() This, IMHO, <a href='http://csharptest.net/1258/understanding-the-pitfalls-of-using-system-guid-with-sequential-values/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>In my previous post &#8220;<a href="http://csharptest.net/1250/">Why GUID primary keys are a database’s worst nightmare</a>&#8221; I spoke about some of downsides to using GUID primary keys.  In this post I&#8217;m going to focus more specifically on the .NET Framework&#8217;s implementation of <a href="http://msdn.microsoft.com/en-us/library/system.guid.aspx" target="_blank">System.Guid</a>.  I have a few complaints about this class, let&#8217;s cover them&#8230;</p>
<p><b>1. Guid.ToByteArray()</b></p>
<p>This, IMHO, is one of the worst possible things about a Guid.  First this method returns a byte array in <a href="http://en.wikipedia.org/wiki/Endianness" target="_blank">little-endian</a> format.  Not only is this directly opposite the stated <a href="http://en.wikipedia.org/wiki/Guid" target="_blank">standard GUID format</a>, but it also means the bytes do not compare the same as the structured value.  Thus when you combine System.Guid with a sequential guid generation you wind up with either a structure that doesn&#8217;t compare sequentially, or a byte array that doesn&#8217;t compare sequentially.  Yes you can always swap bytes (1,4), (2,3), (5,6), and (7,8), but really? should I have to?</p>
<p>The second issue I have with this method is that it absolutely requires me to allocate the bytes on the heap.  While this may not sound like such a big deal, if you are moving large volumes of data and serializing those Guids the only way you can (as byte[]) it will thrash the GC.  I&#8217;m hopeful that in some future version of .NET we will find a Guid with a ToByteArray(GuidFormatType, byte[], offset) where GuidFormatType would allow little-endian or big-endian formats.  </p>
<p><b>2. Guid.GetHashCode()</b></p>
<p>This one does puzzle me.  They choose to completely ignore bytes 9, 10, 12, 13, 14, and 15 when computing a Guid&#8217;s hash code.  Ok so maybe with random Guids this really doesn&#8217;t matter, but when you start trying to use Guid with sequential values this starts to impact hash performance.  If, as in my example on the previous post, bytes 1-8 are date-time, then your entire hash value amounts to the entropy introduced in bytes 11 and 16.  To be specific, byte 11 xors with the MSB and byte 16 xors with the LSB.</p>
<p><b>3. Guid.NewSequentialGuid()</b></p>
<p>Don&#8217;t you wish that .NET could just do this for us?  We&#8217;ve know this to be a problem, and have know of a resolution to it, since 2002.  They&#8217;ve even added &#8220;<a href="http://msdn.microsoft.com/en-us/library/ms189786.aspx" target="_blank">NEWSEQUENTIALGUID()</a>&#8221; to Sql Server.  Wouldn&#8217;t you think they could get this done for us?  I guess until they fix the endianness of ToByteArray it&#8217;s really a moot point anyway.</p>
<p>Of course one option is to just PInvoke <a href="http://msdn.microsoft.com/en-us/library/aa379322(VS.85).aspx" target="_blank">UuidCreateSequential</a>. </p>
<pre class="brush:csharp">
static class Win32
{
    [DllImport("rpcrt4.dll", SetLastError=true)]
    public static extern int UuidCreateSequential(out Guid guid);
}
</pre>
<p><b>4. Guid.(Missing Properties)</b></p>
<p>Another annoyance is the lack of exposing the values of the Guid.  Would it have really been that hard to expose the same integer, two shorts, and 8 bytes that we can pass to the constructor?  One could then create an efficient binary serializer for the Guid type without a GC allocation and without worrying about byte-swapping little-endian values.  In addition, the underlying randomization could then be reused without using the ToByteArray method.  Maybe this isn&#8217;t a big deal for most people, but I&#8217;m still miffed that (AFAIK) there is not a single thread-safe means of creating a random value without allocating a byte[].</p>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why GUID primary keys are a database&#8217;s worst nightmare</title>
		<link>http://csharptest.net/1250/why-guid-primary-keys-are-a-databases-worst-nightmare/index.html</link>
		<comments>http://csharptest.net/1250/why-guid-primary-keys-are-a-databases-worst-nightmare/index.html</comments>
		<pubDate>Mon, 03 Dec 2012 23:33:19 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[BPlusTree]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[b+tree]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[guid]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1250</guid>
		<description><![CDATA[When you ask most people why using a GUID column for a primary key in a database might be slower than auto-incremented number the answer your likely to get is usually along these lines: &#8220;Guids are 16 bytes, and integers are only 4 bytes.&#8221; While this information is technically accurate, it is completely the wrong <a href='http://csharptest.net/1250/why-guid-primary-keys-are-a-databases-worst-nightmare/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>When you ask most people <strong>why using a GUID column for a primary key in a database might be slower than auto-incremented number</strong> the answer your likely to get is usually along these lines: </p>
<blockquote><p>&#8220;Guids are 16 bytes, and integers are only 4 bytes.&#8221;</p></blockquote>
<p>While this information is technically accurate, it is completely the wrong answer to the question.  The performance delta from a 16 byte key to a 4 byte key is most likely negligible and almost certainly impossible to accurately measure.  To understand what is wrong with a guid, you first need to know a little about how a database stores it&#8217;s data.</p>
<p>The most common storage used by databases (to the best of my knowledge) is a B+Tree.  They offer great performance even for very large sets of data.  They do however suffer from one problem, let&#8217;s call this &#8216;<strong>key density</strong>&#8216;.</p>
<p>By <strong>key density</strong> I&#8217;m referring to the density, or close proximity, of the keys being accessed at any given moment as it compares the universe of all the keys in storage.  For example let&#8217;s say I have 10 million records, each keyed by a unique integer numbered from 1 to 10,000,000.  I can say that keys {44,46,52} have a high-density, whereas keys {100,10553,733555} have a very low-density.</p>
<p>Cache is everything.  When a database needs to read or write a record, they traverse nodes in the tree and read them into memory from disk.  Disk IO is the single biggest time expense a database has.  So to reduce the number of reads, nodes visited while fetching or writing a record are usually cached.  This allows more efficient retrieval of the record next time it is requested.  As more low-density keys are accessed, more and more unique nodes are fetched from disk into memory and cache.  Yet every cache has its limits, bound primarily by the hardware available and often by software configuration.  Once the available cache space has been used, stale/old nodes are removed from cache to make room for newer ones.</p>
<p>So now let us imagine how this applies when using a auto-numbered field.  To insert the next new row I&#8217;ll need to travel down the right-edge (highest key values) of the tree.  Once at the leaf, insert and done (oversimplified).  Since the next write uses the next possible key from the last one used, it is practically guaranteed to find the nodes it needs in cache.  So a few quick memory look-ups later the record can be inserted without reading from disk.  It should now be obvious why Guids will have problems&#8230;</p>
<p>Creating a new Guid is essentially done by taking a value &#8216;uniformly at random&#8217; from the entire range of possible Guid values.  That means that unlike our auto-number field with a high key-density, our Guid keys are designed to be sparse, or to have a low key-density.  Because of this for two Guid values to be stored in the same tree node is likely going to be statistically more improbable than winning the lottery.  Using a Guid as a primary key practically obliterates the ability for a database to reliably find nodes in the cache based upon previous queries.  By the time the database has passed about 10 million rows your performance will fall drastically.</p>
<p>Want more proof? Read the <a href="http://en.wikipedia.org/wiki/Guid">Guid article on Wikipedia</a> under the section &#8220;Sequential algorithms&#8221; it discusses this very topic.  It also discusses solutions to this, as first introduced by Jimmy Nilsson in 2002, called a COMB Guid or Combined Guid for the combination of a timestamp.</p>
<p><strong>So are Guid&#8217;s Evil in a Database?</strong>  No. It&#8217;s the algorithm that generates the Guid that is the issue, not the Guid itself.  As mentioned in the articles linked above, there are other algorithms.  There are numerous possibilities documented online.  I&#8217;ve implemented one of these that out-performs the native Guid.NewGuid() implementation that will be released in the next few weeks.  Until then, this is fairly similar to the algorithm I&#8217;m using&#8230;</p>
<pre class="brush:csharp">

static class SequentialGuidGenerator
{
    static int _sequenced = (int)DateTime.UtcNow.Ticks;

    private static readonly System.Security.Cryptography.RNGCryptoServiceProvider _random =
        new System.Security.Cryptography.RNGCryptoServiceProvider();
    private static readonly byte[] _buffer = new byte[6];

    public static Guid NewGuid()
    {
        long ticks = DateTime.UtcNow.Ticks;
        int sequenceNum = System.Threading.Interlocked.Increment(ref _sequenced);
        lock (_buffer)
        {
            _random.GetBytes(_buffer);
            return new Guid(
                (int) (ticks >> 32), (short) (ticks >> 16), (short) ticks,
                (byte) (sequenceNum >> 8), (byte) sequenceNum,
                _buffer[0], _buffer[1], _buffer[2], _buffer[3], _buffer[4], _buffer[5]
                );
        }
    }
}
</pre>
<p>The problem with this code is that not all databases compare Guids the same way, or in the same format.  So you should be cautious about using this approach until you understand your database and how it stores and compares a Guid type.</p>
<h3>Lessons Learned and Applied Concept</h3>
<p>The interesting and rather undocumented aspect about this issue is that it applies just as well across all types of composite keys.  Let&#8217;s take an example, we have a simple logging structure we are writing to with NLog in a database.  The rows are identified by a Guid, but we almost never query these records by Id.  Most of the time when we query this data we are looking within a range of dates for a specific event.  How would you model the primary key and indexes?  Well most people want to use as small of a primary key as possible and so the natural assumption is to use the ID of the record.  This, as we&#8217;ve already covered, is generally a bad idea just because we are using Guids, but even more because our queries will be time based.  By promoting the timestamp into the primary key we not only gain better query performance, but we also remove the problem of the GUID identifier.  Let&#8217;s see the example:</p>
<pre>
TABLE LogFile {
    Column DateTime timestamp,
    Column GUID id,
    Column int eventType,
    Column string message,
    Primary Key ( timestamp, id )
}
</pre>
<p>With the primary key using the timestamp as it&#8217;s first comparison we will always be writing to the same area within the table and will consistently hit the cache for writes.  When seeking for data the timestamp will group all the records needed together so that the data we are after is stored as dense as is possible requiring the fewest possible reads.</p>
<p>Now let&#8217;s drift this example a little to a new scenario.  Let&#8217;s say the log above is being written from an ASP.NET application in which all users are authenticated.  We want to add this user identity to the LogFile data being written, and we want to constrain queries to be associated with a user.  In the example above it may be safe to simply modify the Primary Key ( timestamp, id ), to include the user as first key.  Thus the Primary Key ( userId, timestamp, id ) will now perform well for a single user right?  Well the answer Yes and No.  It really depends greatly on the application.  Introducing userId as the primary key means that we could be writing to as many places in the file as we have users.  If the application is a mobile app polling our web server every minute, then we&#8217;ve just scattered our writes across all N thousands of users in our system.  Yet if our application requires a human being to use a web browser or mobile app, the number of active writing points in the file drops considerably&#8230; Well at least until your Facebook and at that point you cash out and go home :)</p>
<p>One last example.  Given you are building SkyDrive, or GDrive, or whatever you want to store the following entities:  Customer, Drive, Folder, File.  Each entity is identified by a GUID.  What does the File&#8217;s primary key look like?  Well I&#8217;d probably key the File by (CustomerID, DriveID, FolderID, Timestamp, FileID).  You would obviously need an ancillary index by FileID in order to access the file directly.  Food for thought anyway&#8230;</p>
<p>The reason I bring all this up is that there is no rule of thumb for a good primary key.  Each application will have different needs and different requirements.  Want you should take away is that the density of keys being written to in that first field of your primary key will ultimately dictate your write throughput and likely your scalability.  Be conscious of this, and choose keys wisely.  The Guid ID of a record is not always the best answer for a primary key. </p>
<p>As a side-note, using Guid&#8217;s as a primary key in the <a href="http://csharptest.net/projects/bplustree/index.html">B+Tree</a> will work but much more slowly at large volumes (2+ million).  Using a sequential guid generator like the one above, or using an ordered natural key (like a qualified file name) will serve you much better.  Ordered (or near-ordered) keys will provide linear scalability whereas unique random GUIDs will start to suffer once you&#8217;ve exceeded the cache space.</p>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BPlusTree and Custom ISerializer Implementations</title>
		<link>http://csharptest.net/1230/bplustree-and-custom-iserializer-implementations/index.html</link>
		<comments>http://csharptest.net/1230/bplustree-and-custom-iserializer-implementations/index.html</comments>
		<pubDate>Wed, 22 Aug 2012 18:41:22 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[BPlusTree]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Protocol Buffers]]></category>
		<category><![CDATA[b+tree]]></category>
		<category><![CDATA[protobuffer]]></category>
		<category><![CDATA[serialization]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1230</guid>
		<description><![CDATA[Almost the first thing you need to create a BPlusTree is going to be the key/value serializers which are implementations of the ISerializer&#60;T> interface. They are also going to be one of the things that can make or break your first impressions of using the BPlusTree. A descent performing implementation is going to be important <a href='http://csharptest.net/1230/bplustree-and-custom-iserializer-implementations/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p><span id="more-1230"></span>Almost the first thing you need to create a <a href="http://help.csharptest.net/?CSharpTest.Net.BPlusTree~CSharpTest.Net.Collections.BPlusTree%602.html" title="B+Tree Help Contents" target="_blank">BPlusTree</a> is going to be the key/value serializers which are implementations of the <a href="http://help.csharptest.net/?CSharpTest.Net.Library~CSharpTest.Net.Serialization.ISerializer%601.html" title="ISerializer interface" target="_blank">ISerializer&lt;T> interface</a>.  They are also going to be one of the things that can make or break your first impressions of using the BPlusTree.  A descent performing implementation is going to be important in order to get the most out of your BPlusTree.  Aside from performance alone, there is one other area of concern, that of the semantic interface.</p>
<h3>Implementing the ISerializer&lt;T> Interface</h3>
<p>First let&#8217;s take a quick look at the interface definition for those that are not familiar with it.</p>
<pre class="brush:csharp">
public interface ISerializer&lt;T>
{
    void WriteTo(T value, Stream stream);
    T ReadFrom(Stream stream);
}
</pre>
<p>Simple enough, right?  Well, not exactly.  It seems that one thing is not obvious from this interface.  The &#8216;stream&#8217; parameter is not constrained in any way.  One could seek to an offset they should not be at, or read past the end of the item they are suppose to be reading.  Exceptions are also a bad idea here since it can prevent you from reading the tree.  So the following guidelines should be used when implementing this interface for use with the BPlusTree:</p>
<ol>
<li>Always use an immutable class, a value type, or ensure that references to the class inserted/updated/fetched are not modified.</li>
<li>When writing values you should try to avoid any case for throwing an exception.</li>
<li>Always use a length-prefix or termination value to prevent reading more data than was written for this value.</li>
<li>When reading you should only throw exceptions when you believe the data has been corrupted.</li>
<li>Never read more data than was written for this record as this will cause subsequent values to be corrupted.</li>
<li>Do not seek or use positional information from the stream, assume it is either append-only writing, or forward-only reading.</li>
</ol>
<h3>Primitive Serialization</h3>
<p>For most primitive types you should not need to write one, instead use the The <a href="http://help.csharptest.net/?CSharpTest.Net.Library~CSharpTest.Net.Serialization.PrimitiveSerializer_members.html" title="PrimitiveSerializer members" target="_blank">PrimitiveSerializer</a> class (declared in CSharpTest.Net.Serialization). The PrimitiveSerializer class has static properties for many of the serializers you will need for primitives.  These are all written using little-endian byte ordering for numeric values.</p>
<p>If you need to write a compact format there is another class to help you with numeric encoding.  The <a href="http://help.csharptest.net/?CSharpTest.Net.Library~CSharpTest.Net.Serialization.VariantNumberSerializer_members.html" title="VariantNumberSerializer members" target="_blank">VariantNumberSerializer</a> class exposes serialization for protocol buffer-like variant encoding of integer values.  Basically this can be used to store positive integer values in more compact format than using the PrimitiveSerializer.</p>
<p>Neither of these provide an array serializer for anything other than a byte[].  This can often be a desired type so here is a generic implementation that will serialize arrays given a serializer for the item type.</p>
<pre class="brush:csharp">
public class ArraySerializer&lt;T> : ISerializer&lt;T[]>
{
    private readonly ISerializer&lt;T> _itemSerializer;
    public ArraySerializer(ISerializer&lt;T> itemSerializer)
    {
        _itemSerializer = itemSerializer;
    }

    public T[] ReadFrom(Stream stream)
    {
        int size = PrimitiveSerializer.Int32.ReadFrom(stream);
        if (size < 0)
            return null;
        T[] value = new T[size];
        for (int i = 0; i < size; i++)
            value[i] = _itemSerializer.ReadFrom(stream);
        return value;
    }

    public void WriteTo(T[] value, Stream stream)
    {
        if (value == null)
        {
            PrimitiveSerializer.Int32.WriteTo(-1, stream);
            return;
        }
        PrimitiveSerializer.Int32.WriteTo(value.Length, stream);
        foreach (var i in value)
            _itemSerializer.WriteTo(i, stream);
    }
}
</pre>
<h3>Using Protocol Buffers with the BPlusTree</h3>
<p>Protocol buffers make an excellent way to serialize data for the BPlusTree.  They are compact, fast, and can be extended/modified over time without having to rewrite the records.  Due to this I highly recommend using <strong><a href="http://code.google.com/p/protobuf-csharp-port/" target="_blank">protobuf-csharp-port</a></strong> to generate the classes you will use.  In addition to the serialization benefits mentioned this library is also built upon immutable types with builders.  This is very important for the accuracy of the data since the BPlusTree makes no guarantees about when the instance will be serialized and it may use the same instance multiple times when reading.  The following serializer will provide you a generic implementation that can be used with the protobuf-csharp-port library (NuGet <a href="http://nuget.org/packages/Google.ProtocolBuffers" title="Google.ProtocolBuffers" target="_blank">Google.ProtocolBuffers</a>).
</pre>
<pre class="brush:csharp">
using CSharpTest.Net.Serialization;
using Google.ProtocolBuffers;
internal class ProtoSerializer&lt;T, TBuilder> : ISerializer&lt;T>
    where T : IMessageLite&lt;T, TBuilder>
    where TBuilder : IBuilderLite&lt;T, TBuilder>, new()
{
    private delegate TBuilder FactoryMethod();
    private readonly FactoryMethod _factory;

    public ProtoSerializer()
    {
        // Pre-create a delegate for instance creation, new TBuilder() is expensive...
        _factory = new TBuilder().DefaultInstanceForType.CreateBuilderForType;
    }

    public T ReadFrom(Stream stream)
    {
        // Use Build or BuildPartial, the later does not throw if required fields are missing.
        return _factory().MergeDelimitedFrom(stream).BuildPartial();
    }

    public void WriteTo(T value, Stream stream)
    {
        value.WriteDelimitedTo(stream);
    }
}
</pre>
<p>What about using <strong><a href="http://code.google.com/p/protobuf-net/" target="_blank">protobuf-net</a></strong>?  This is also very easy to implement and would be the preferred way of code-first serialization (no proto description, just a .NET class/struct).  As we did with the protobuf-csharp-port you must length-prefix the messages.  Avoid using the IFormatter implementation in protobuf-net since this has a semantic incompatibility with BinaryFormatter and other implementations (it is not length prefixed and reads to end-of-stream).   Here is a generic class for serialization using the protobuf-net&#8217;s static Serializer class:</p>
<pre class="brush:csharp;">
public class ProtoNetSerializer&lt;T> : ISerializer&lt;T>
{
    public T ReadFrom(Stream stream)
    {
        return ProtoBuf.Serializer.DeserializeWithLengthPrefix&lt;T>(stream, ProtoBuf.PrefixStyle.Base128);
    }
    public void WriteTo(T value, Stream stream)
    {
        ProtoBuf.Serializer.SerializeWithLengthPrefix&lt;T>(stream, value, ProtoBuf.PrefixStyle.Base128);
    }
}
</pre>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Version 2.12.810.409 Released</title>
		<link>http://csharptest.net/1227/version-2-12-810-409-released/index.html</link>
		<comments>http://csharptest.net/1227/version-2-12-810-409-released/index.html</comments>
		<pubDate>Fri, 10 Aug 2012 20:48:18 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[Home]]></category>
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1227</guid>
		<description><![CDATA[Release Notes: NOTES: Major version increment primarily due to extensive changes in BPlusTree&#8217;s capabilities and storage format. The next release will flag the v1 Options class as Obsolete to ensure people are using the latest version. All new code should be using &#8216;OptionsV2&#8242; when constructing a BPlusTree. Additions in this release: Added BPlusTree.OptionsV2 to provide <a href='http://csharptest.net/1227/version-2-12-810-409-released/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p><strong>Release Notes:</strong></p>
<p>NOTES: Major version increment primarily due to extensive changes in BPlusTree&#8217;s capabilities and storage format. The next release will flag the v1 Options class as Obsolete to ensure people are using the latest version. All new code should be using &#8216;OptionsV2&#8242; when constructing a BPlusTree.</p>
<p>Additions in this release:</p>
<ol>
<li>Added BPlusTree.OptionsV2 to provide a more simple set of options and uses the v2 file format.</li>
<li>BPlusTree now supports key range enumeration as well as accessing first/last key in the tree.</li>
<li>BPlusTree now supports optimized AddRange and BulkInsert methods.</li>
<li>BPlusTree now supports transaction logging for improved durability and recovery.</li>
<li>BPlusTree now has a completely new file format (use the OptionsV2 class) for improved performance and reliability.</li>
<li>The generator&#8217;s ResXtoMC complier now supports application manifest files and the inclusion of win32 resource files.</li>
<li>Added the IConcurrentDictionary interface to provide an abstraction on concurrent dictionary implementations.</li>
<li>BPlusTree now supports all relevent members of the .NET ConcurrentDictionary class and implements IConcurrentDictionary.</li>
<li>Updated SynchronizedDictionary to implement IConcurrentDictionary, great for testing code without a BPlusTree backend.</li>
<li>Added BTreeDictionary&amp;lt;TKey,TValue&gt; to support in-memory always sorted key/value dictionary.</li>
<li>Added BTreeList&amp;lt;T&gt; to support an in-memory B+Tree backed sorted list.</li>
<li>Added collection classes to deal with KeyValue comparision, ordering, enumerating, etc.</li>
<li>Added MergeSort (stable sorting) static class for more efficient sorting with custom comparer implementations.</li>
<li>Added an alternative to FragmentedFile called TransactedCompoundFile to support the rewite of the BPlusTree file format.</li>
<li>CmdTool.exe now supports a boolean &#8216;stop&#8217; attribute on the FileMatch tag, allowing complete override of files that appear higher in the folder structure.</li>
</ol>
<p>Fixes in this release:</p>
<ol>
<li>XmlLightElement CDATA handling was incorrectly decoding html content.</li>
<li>OrdinalList had a bug in the IntersectWith and UnionWith implementations where the inputs were the same length.</li>
<li>BPlusTree enumeration of Keys or Values would load the entire tree into a list, this is now fixed.</li>
</ol>
<p>Breaking changes in this release:</p>
<ol>
<li>The following breaking changes were made to BPlusTree to bring it&#8217;s concurrent interface members inline with .NET 4&#8242;s ConcurrentDictionary.</li>
<ul>
<li>BPlusTree changed the delegate type provided to TryUpdate to include both Key and Value.</li>
<li>BPlusTree changed the method name and delegate type of Add(TKey, delegate) to TryAdd(TKey, delegate).</li>
<li>BPlusTree changed the delegate types provided to AddOrUpdate to include both Key and Value.</li>
</ul>
<li>BPlusTree.Options is still backwards compatible with existing files; however, BPlusTree.OptionsV2 uses a new format.</li>
</ol>
<p>For more information on the BPlusTree changes read <a href="http://csharptest.net/?p=1101">BPlusTree 2.0 Changes Part 1 &#8211; Interface Changes</a></p>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BPlusTree 2.0 Changes Part 5 &#8211; Using the v2 Storage Format</title>
		<link>http://csharptest.net/1207/bplustree-2-0-changes-part-5-using-the-v2-storage-format/index.html</link>
		<comments>http://csharptest.net/1207/bplustree-2-0-changes-part-5-using-the-v2-storage-format/index.html</comments>
		<pubDate>Sun, 29 Jul 2012 15:17:13 +0000</pubDate>
		<dc:creator>roger</dc:creator>
				<category><![CDATA[BPlusTree]]></category>
		<category><![CDATA[Home]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[b+tree]]></category>

		<guid isPermaLink="false">http://csharptest.net/?p=1207</guid>
		<description><![CDATA[Continued from: BPlusTree 2.0 Changes Part 4 &#8211; Rewriting the Storage Format Getting Started To utilize the new file format in the BPlusTree you will need to use OptionsV2 class. The previous Options class is still there and continues to use the same file format. // Create the OptionsV2 class to specify construction arguments: var <a href='http://csharptest.net/1207/bplustree-2-0-changes-part-5-using-the-v2-storage-format/index.html'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Continued from: <a href="http://csharptest.net/?p=1193">BPlusTree 2.0 Changes Part 4 &#8211; Rewriting the Storage Format</a></p>
<h3>Getting Started</h3>
<p>To utilize the new file format in the BPlusTree you will need to use OptionsV2 class.  The previous Options class is still there and continues to use the same file format.</p>
<pre class="brush:csharp">
// Create the OptionsV2 class to specify construction arguments:
var options = new BPlusTree&lt;string, Guid>.OptionsV2(
    PrimitiveSerializer.String, PrimitiveSerializer.Guid, StringComparer.Ordinal)
    {
        CreateFile = CreatePolicy.IfNeeded,
        FileName = @"C:\Temp\Storage.dat",
        StoragePerformance = StoragePerformance.Default,
        TransactionLogLimit = 100 * 1024 * 1024, // 100 MB
    }
    .CalculateBTreeOrder(10, 16);

// Create the BPlusTree using these options
using(var map = new BPlusTree&lt;string, Guid>(options))
{
    map.Add("foo", Guid.NewGuid());
    Assert.IsTrue(map.ContainsKey("foo"), "Failed to find foo");
}
</pre>
<h3>Choosing a StoragePerformance Option</h3>
<p>I&#8217;ve attempted to simplify the multitude of options available into this simple enumeration.  The default (LogFileInCache) should be acceptable to most uses, but read the following carefully to understand what you are getting.  The StoragePerformance has the following possible values and their implications:</p>
<p><strong>StoragePerformance.Fastest</strong><br />
This option is safe from corruption and provides the fastest possible throughput.  This is essentially the same behavior as LogFileInCache without the ability to recover any data written since the last successful call to Commit() or Dispose().  For some operations, for example, a temporary index of data that will not fit entirely in memory, this is going to be the best option.  The performance again can vary but you should be able to see 100~200k writes/second.</p>
<p><strong>StoragePerformance.LogFileInCache (Default)</strong><br />
This is the Default option and fastest durable option.  The transaction log is written to system cache and in the event of a power failure or OS crash some records may be lost.  This option should not corrupt state but may take some time to recover from a crash.  The performance, even on slow disks, is quite good.  You should expect anywhere from 30~60k writes/second or more depending the size of the data.</p>
<p><strong>StoragePerformance.CommitToCache</strong><br />
This is the least durable option and the only one that may result in data file corruption.  Corruption may occur in the event of power failure or OS crash with a partially flushed system cache.  Provided the OS cache is flushed entirely or not at all, the file will not be corrupted.  The performance of this option will usually reach around 6~8k writes/second.  This can be a viable option if you do not want a transaction log and need to keep every write on disk in the case of a process crash.</p>
<p><strong>StoragePerformance.LogFileNoCache</strong><br />
This option is intended to give you an ACID BPlusTree at the least cost in performance.  The downside is that should the process crash or the power fail the file will need to be recovered.<br />
See the discussion below on using transaction log files.  Generally this option will perform about 2~4k writes/second.</p>
<p><strong>StoragePerformance.CommitToDisk</strong><br />
Using this options should give you a fully ACID compliant BPlusTree.  To be completely ACID (as with any database) means you need to disable cache and write behind features on the hardware as well.  Performance will suffer, like with any real database.  Depending on the speed of the disk and size of the data you can expect 1~2k writes/second or less.</p>
<h3>Using Transaction Logs</h3>
<p>Recovering the file from log can be expensive depending on the volume of data.<br />
This option will open a transaction log with FileOptions.WriteThrough to cause every write to go through system cache to disk.  The data file will remain in it&#8217;s current state until a call to Commit() or Dispose().  Calling Rollback() will, if using transaction logs, revert the storage file to it&#8217;s last committed state. Calling Commit/Rollback are exclusive operations on the entire tree, so all readers and writers must exit prior to processing.</p>
<p>For long-running processes (i.e. services) you may want to provide a thread to perform periodic calls to Commit() when idle.  If you do not have a way to detect idle conditions, or don&#8217;t want to bother, set the OptionsV2.TransactionLogLimit to the max allowable log size.  Keep in mind that calls to Commit require a OS-level flush of all file buffers, and as such, are expensive.  My recommendation is to use a large constant value, 100MB or so.</p>
<h3>Transaction Log Recovery</h3>
<p>Transaction logs will by default be auto-recovered the next time the BPlusTree is opened after a crash.  This comes at a cost of performing the operation as an &#8216;exclusive&#8217; task which is generally what you are going to want.  There are times when controlling this recovery can be useful.  To this end there is a new option OptionsV2.ExistingLogAction which can be used to control the activity performed when opening a BPlusTree that has a existing log data.  For instance you can choose to use the &#8220;Truncate&#8221; option to discard all changes in the transaction log.</p>
<h3>Upgrading Existing Data</h3>
<p>Upgrading from one BPlusTree to another is easily accomplished via the BulkInsert operation.  The following example leverages the fact that the existing tree will enumerate in key order:</p>
<pre class="brush:csharp">
using Btree = CSharpTest.Net.Collections.BPlusTree&lt;int, string>;
static void UpgradeDatabase(Btree.Options source, Btree.OptionsV2 target)
{
    source = source.Clone();
    source.ReadOnly = true;
    using(Btree input = new Btree(source))
    using (Btree output = new Btree(target))
    {
        output.BulkInsert(input,
                          new BulkInsertOptions
                              {
                                  ReplaceContents = true
                                  InputIsSorted = true,
                                  CommitOnCompletion = true,
                                  DuplicateHandling = DuplicateHandling.RaisesException,
                              }
        );
    }
}
</pre>
]]></content:encoded>
			
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>