<?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>Mauro Krikorian</title>
	<atom:link href="http://blogs.southworks.net/mkrikorian/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.southworks.net/mkrikorian</link>
	<description></description>
	<lastBuildDate>Tue, 04 Jun 2013 15:04:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Data Driven Apps &#8211; State of the Art Techniques</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/06/04/data-driven-apps-state-of-the-art-techniques/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/06/04/data-driven-apps-state-of-the-art-techniques/#comments</comments>
		<pubDate>Tue, 04 Jun 2013 15:04:25 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Availability]]></category>
		<category><![CDATA[DB]]></category>
		<category><![CDATA[Data Driven]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Distributed databases]]></category>
		<category><![CDATA[Distributed systems]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Scalability]]></category>
		<category><![CDATA[Big Data]]></category>
		<category><![CDATA[Blob Storage]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Distributed Databases]]></category>
		<category><![CDATA[Fakes]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Neo4J]]></category>
		<category><![CDATA[NoSql]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[Table Storage]]></category>
		<category><![CDATA[WebApi]]></category>
		<category><![CDATA[Windows Azure]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=711</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/06/04/data-driven-apps-state-of-the-art-techniques/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve been working with the Pattern and Practices group in a guide around Data Access focused on high scalability and availability of data driven applications. Through the book we show several DB families while analyzing their advantages and disadvantages when used in real life apps.</p>
<p>The book is still in its final phase, but several drops have been done to the community in order to get early feedback.</p>
<p>If you&#8217;re a enthusiastic software developer or an architect looking for the best practices when building a highly scalable data driven application I recommend you to take a look on this <a href="http://dataguidance.codeplex.com/">Data Access Guidance</a> at CodePlex site.</p>
<p>Keep in touch for future releases!</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to easily unit test MVC routes using Fakes</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/03/15/how-to-easily-unit-test-mvc-routes-using-fakes/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/03/15/how-to-easily-unit-test-mvc-routes-using-fakes/#comments</comments>
		<pubDate>Fri, 15 Mar 2013 15:07:47 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Fakes]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[routes]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=687</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/03/15/how-to-easily-unit-test-mvc-routes-using-fakes/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify">In this short post I will show you how you can easily test your MVC routes using Fakes as mocking framework. Besides there is a lot of mocking frameworks you can choose to unit test your code, Fakes provides you the ability to mock almost any class within the framework, not just interfaces or virtual things.</p>
<p style="text-align: justify">The following concepts are first class citizens within the Fakes ecosystem:</p>
<ul>
<li>A <strong>stub </strong>replaces another class with a small substitute that implements the same interface. To use stubs, you have to design your application so that each component depends only on interfaces, and not on other components.</li>
</ul>
<ul>
<li>A <strong>shim </strong>modifies the compiled code of your application at run time so that instead of making a specified method call, it runs the shim code that your test provides. Shims can be used to replace calls to assemblies that you cannot modify, such .NET assemblies.</li>
</ul>
<p style="text-align: justify">Basically stubs are what you find in many other mocking frameworks for .NET, but shims provides extra value by allowing you to modify the compiled code (not targeting the classes you want to test, but the classes those ones rely on). You can read more about Fakes and usage <a href="http://msdn.microsoft.com/en-us/library/hh549175.aspx" target="_blank">here</a>.</p>
<p style="text-align: justify">Here I&#8217;ll show you how you can mock base classes within the ASP.NET pipeline as HttpContextBase, HttpRequestBase and HttpResponseBase in order to set up everything MVC needs to resolve a route.</p>
<p style="text-align: justify">So you can add a private method to your fixture setting up these mocks like the following one:</p>
<pre class="brush: csharp; title: ; notranslate">
private IDisposable MocksForMVCRouteTesting(string requestUrl, out HttpContextBase contextBase)
{
  var shimsContext = ShimsContext.Create();
  var requestBase = new System.Web.Fakes.StubHttpRequestBase
  {
    ApplicationPathGet = () =&gt; &quot;/&quot;,
    AppRelativeCurrentExecutionFilePathGet = () =&gt; requestUrl
  };

  contextBase = new System.Web.Fakes.StubHttpContextBase
  {
    RequestGet = () =&gt; requestBase,
    ResponseGet = () =&gt; new System.Web.Fakes.StubHttpResponseBase()
  };

  return shimsContext;
}
</pre>
<p style="text-align: justify">Ok, now you got your mocks to test the routes, but how to use it? Easy, following the next pattern:</p>
<pre class="brush: csharp; title: ; notranslate">
// Act
HttpContextBase context;
using (this.MocksForMVCRouteTesting(&quot;{mvc_route_to_text_here}&quot;, out context))
{
  var routeData = routes.GetRouteData(context);

  // Asserts here...
}
</pre>
<p>And what about a real like example?</p>
<pre class="brush: csharp; title: ; notranslate">
  // Arrange
  var routes = new RouteCollection();
  RouteConfig.RegisterRoutes(routes);

  // Act
  HttpContextBase context;
  using (this.MocksForMVCRouteTesting(&quot;~/account/register/&quot;, out context))
  {
    var routeData = routes.GetRouteData(context);

    // Assert
    Assert.IsNotNull(routeData);
    Assert.AreEqual(&quot;Account&quot;, (string)routeData.Values[&quot;controller&quot;], true);
    Assert.AreEqual(&quot;Register&quot;, (string)routeData.Values[&quot;action&quot;], true);
    Assert.IsTrue(string.IsNullOrWhiteSpace(routeData.Values[&quot;id&quot;].ToString()));
  }
</pre>
<p>Hope that you can find this useful <img src='http://blogs.southworks.net/mkrikorian/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More NoSql stuff :: Couchbase from C#</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/02/06/more-nosql-stuff-couchbase-from-c/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/02/06/more-nosql-stuff-couchbase-from-c/#comments</comments>
		<pubDate>Wed, 06 Feb 2013 21:33:51 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Couchbase]]></category>
		<category><![CDATA[DB]]></category>
		<category><![CDATA[Distributed databases]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Distributed Databases]]></category>
		<category><![CDATA[NoSql]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=496</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/02/06/more-nosql-stuff-couchbase-from-c/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify">Continuing with my incursion in the <a href="http://en.wikipedia.org/wiki/NoSQL">NoSql</a> database world, these days I&#8217;ve been playing with <a href="http://www.couchbase.com/">Couchbase</a> installed on Windows 8 (after <a href="http://blogs.southworks.net/mkrikorian/2013/02/06/installing-couchbase-under-windows-8/">tackling several issues</a>). Finally, after downloaded and installed it successfully, I&#8217;ve created a simple console application in C# to test its basis (as I did in my previous articles &#8216;<a href="http://blogs.southworks.net/mkrikorian/2013/01/29/using-mongodb-from-c/">Using MongoDB from C#</a>&#8216; and &#8216;<a href="http://blogs.southworks.net/mkrikorian/2013/02/01/a-little-of-ravendb/">A little of RavenDB</a>&#8216; a few days ago).</p>
<p style="text-align: justify">This turns to be a <em>Document Oriented </em>store working as a key-value DB when interacting with its HTTP RESTful API. It stores JSON documents, and support sharding, replication, and many other things that we can find these days in most NoSql databases. You can go to the Couchbase home site and <a href="http://www.couchbase.com/learn">learn more</a> about it.</p>
<p style="text-align: justify">As I said before, in order to try some of its features, I’ve created a console application (the client driver is very simple to add to your solution – just using <a href="https://nuget.org/">NuGet</a>).</p>
<p style="text-align: justify">First at all you need to get a configured client instance before interact with the DB. So let&#8217;s start by downloading the <a href="http://nuget.org/packages/CouchbaseNetClient/">client NuGet package</a> into your project, and add a new section within your <em>.config</em> file for Couchbase:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;configSections&gt;
   &lt;section name=&quot;couchbase&quot; type=&quot;Couchbase.Configuration.CouchbaseClientSection, Couchbase&quot;/&gt;
&lt;/configSections&gt;

&lt;couchbase&gt;
   &lt;servers bucket=&quot;default&quot; bucketPassword=&quot;&quot;&gt;
      &lt;add uri=&quot;http://127.0.0.1:8091/pools/default&quot;/&gt;
   &lt;/servers&gt;
&lt;/couchbase&gt;
</pre>
<p style="text-align: justify">Now you can get a client instance from your app just this easy:</p>
<pre class="brush: csharp; title: ; notranslate">
var client = new CouchbaseClient();
</pre>
<p style="text-align: justify">Let&#8217;s perform some simple CRUD operations like adding and getting a document. Having the following <em>Book </em>class defined:</p>
<pre class="brush: csharp; title: ; notranslate">
[Serializable]
public class Book
{
 public string Title { get; set; }
 public string[] Authors { get; set; }
 public decimal Price { get; set; }
 public bool Recommended { get; set; }
}
</pre>
<p>How do we create and add a new book to the store? Simple, just like the following:</p>
<pre class="brush: csharp; title: ; notranslate">
var bookId = &quot;f1637bb1-cd16-40bd-9ae7-e267d58ff62f&quot;;
client.StoreJson(StoreMode.Add, bookId, new Book
{
   Title = &quot;For Whom the Bell Tolls&quot;,
   Authors = new string[] { &quot;Ernest Hemingway&quot; },
   Recommended = true,
   Price = 15.64M
});
</pre>
<p style="text-align: justify">In this example I have chosen the key to be a <em>Guid</em>, but you can use any string-set you want to define your own keys domain. I have also used a <em>StoreJson()</em> method that is not present at the <em>CouchbaseClient </em>class interface; well you can take advantage of it by using the <em>Couchbase.Extensions</em> namespace static classes containing some extension methods for this class.</p>
<p style="text-align: justify">And what&#8217;s the code to retrieve? Some kind of <em>GetJson()</em>? Exactly! Actually a <em>GetJson&lt;T&gt;()</em> extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
var book = client.GetJson&lt;Book&gt;(bookId);
</pre>
<p style="text-align: justify"><span style="text-decoration: underline">Note</span>: the <em>CouchbaseClient </em>class contains simple<em> Store()</em> and <em>Get&lt;T&gt;()</em> methods, so why I didn&#8217;t use them before? Well, if you use these methods the client will store the document instance as binary within a JSON document in the server. Having a JSON readable document stored in the server will be helpful to perform server-side operations over them (basically <a href="http://en.wikipedia.org/wiki/MapReduce">MapReduce</a> operations).</p>
<p style="text-align: justify">But now, how you can retrieve or perform a custom operation, and get its results, over a set of documents? Well, as you may guessed, the answer here (as in many other NoSql databases) is to recall the MapReduce concept I&#8217;ve mentioned before. In Couchbase you have a concept that is very similar to relational DB&#8217;s <em><a href="http://en.wikipedia.org/wiki/View_(database)">Views</a> </em>to resolve this kind of things, and as happens in a RDBMS, it allows you to obtain a subset or full set of documents from the store (besides performing aggregation operations). <a href="http://www.couchbase.com/docs/couchbase-manual-2.0/couchbase-views-basics.html"><em>Views </em>in Couchbase</a> iterate over a specific bucket, and they can be expensive to build if the dataset you selected is big, but once created they are automatically updated whenever data changes (having low performance impact). To store the views this DB has a <em>design document</em> concept (as we can find it in <a href="http://couchdb.apache.org/">CouchDB</a> &#8211; where you can store your <a href="http://wiki.apache.org/couchdb/Technical%20Overview#Views">views within a design document or run temporary views</a>, resulting in performance degradation as temporary views execute when you sent them to the server &#8211; refer to <a href="http://wiki.apache.org/couchdb/Technical%20Overview">CouchDB technical documentation</a> for more info).</p>
<p style="text-align: justify">To create a new view you can go to your administrative console at <a href="http://localhost:8091/">http://localhost:8091/</a> and click in the <em>Views</em> tab to create a new <em>design document</em> and add some views to it, but I&#8217;ll show you how you can achieve this from your client app later.</p>
<p style="text-align: justify">Let&#8217;s first create a view that will be useful to search using book&#8217;s titles as I did on previous articles, a <em>BookByTitle </em>view/index. I&#8217;ve created a <em>JavascriptFunctions</em> class within my application to contain (as strings) the Javascript functions I need for the MapReduce operations, although you can store them whenever you want. Here it is, containing the mapping function for getting books by title:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class JavascriptFunctions
{
 public static string Dev_Books_ByTitle_Map
 {
   get
   {
      return @&quot;function (doc, meta) {
         if (doc.title &amp;&amp; doc.authors) {
            emit(doc.title, null);
         }
      }&quot;;
   }
 }
}
</pre>
<p style="text-align: justify">As you can see within the function I&#8217;m checking for documents that contain a <em>title</em> and <em>authors</em>, as the documents within the bucket can be of any kind and the map function will receive all the documents in the bucket (at least if they contain <em>title</em> and <em>authors</em> there is a big chance that they are books &#8211; you can split your documents within different buckets or choose to have a kind of &#8216;<em>document </em><em>type</em>&#8216; identifier).</p>
<p style="text-align: justify">If you add this view to the server you can use it from the client to get a range of books by title for example, as shown below:</p>
<pre class="brush: csharp; title: ; notranslate">
var booksByTitle = client.GetView&lt;Book&gt;(&quot;dev_books&quot;, &quot;bytitle&quot;, true);
foreach (var book in booksByTitle.StartKey(&quot;S&quot;))
{
   Console.WriteLine(string.Format(&quot;* Book retrieved: {0}&quot;, book));
}
</pre>
<p style="text-align: justify">Using the <em>GetView&lt;T&gt;()</em> method you can instruct the server that you want to get the results from the view (ie. the map or reduce functions results), but setting the last method parameter (<em>shouldLookupDocById</em>) to <em>true</em> you will get the documents either. And there I&#8217;m showing the books which titles start with &#8216;S&#8217; until the end of the collection (remember that you have an index built below).</p>
<p style="text-align: justify">But, what if I want now to count books by authors as I did in previous articles? I&#8217;ll just need to add another view that maps the authors names with their book count from each document, and reduce these results grouping by the key (the author in these case).. as with other NoSql DBs I worked with, obtaining this result is a piece of cake. So let&#8217;s add two new &#8216;functions&#8217; to my <em>JavascriptFunctions </em>class that will map and reduce authors with their books count:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class JavascriptFunctions
{
 public static string Dev_Books_ByTitle_Map
 {
   get
   {
      return @&quot;function (doc, meta) {
         if (doc.title &amp;&amp; doc.authors) {
            emit(doc.title, null);
         }
      }&quot;;
   }
 }

 public static string Dev_Books_AuthorWithBookCount_Map
 {
   get
   {
      return @&quot;function (doc, meta) {
         if (doc.authors &amp;&amp; doc.recommended) {
            for (var i in doc.authors) {
               emit(doc.authors[i], 1);
            }
         }
      }&quot;;
   }
 }

 public static string Dev_Books_AuthorWithBookCount_Reduce
 {
   get
   {
      return @&quot;function (keys, values, rereduce) {
         if (!rereduce) {
            return sum(values);
         }
      }&quot;;
   }
 }
}
</pre>
<p style="text-align: justify">Now I have two new Javascript functions defined at this class: <em>Dev_Books_AuthorWithBookCount </em>(map &amp; reduce versions). If you pay attention to the Map version, you can see that I&#8217;m only interested in books that are &#8216;<em>recommended</em>&#8216; (an again, to know that they are books I&#8217;m querying its <em>authors </em>property). From the client app you can get its results in the following way:</p>
<pre class="brush: csharp; title: ; notranslate">
var countPerAuthor = client.GetView(&quot;dev_books&quot;, &quot;authorwithbookcount&quot;).Group(true);
foreach (var row in countPerAuthor)
{
   Console.WriteLine(&quot;* Author {0} has {1} books&quot;, row.Info[&quot;key&quot;], row.Info[&quot;value&quot;]);
}
</pre>
<p style="text-align: justify">Please note that I&#8217;m using <em>Group()</em> method from the <em>IView </em>interface there to indicate the server that the reduce function should operate on each one of the keys. You can get more information <a href="http://www.couchbase.com/docs/couchbase-manual-2.0/couchbase-views-writing-reduce.html">here</a> (and see there how to handle <em>rereduce </em>parameter &#8211; something that I&#8217;m not doing here since I don&#8217;t expect any).</p>
<p style="text-align: justify">Well&#8230; up to now the client code seems pretty simple in order to get view results, but how can we test it so far? Until now you could have been creating the respective views within the administration console (under the <em>Views </em>tab).</p>
<p style="text-align: justify">At first glance, it seems the C# SDK doesn&#8217;t have an API to manage views. Nevertheless, as the design document that contains views details is just another document within the DB, I&#8217;ll show you how you can create with a <em>PUT </em>request. You can achieve the &#8216;<em>trick</em>&#8216; easily with the following code that relies on the <em>WebClient </em>class from .NET framework to do the job, but first let&#8217;s add the <em>design document&#8217;s </em>body (JSON) to the <em>JavascriptFunction </em>class to have it at hand:</p>
<pre class="brush: csharp; title: ; notranslate">
public static string Dev_Books_DesignDocument
{
   get
   {
      return @&quot;{&quot;&quot;views&quot;&quot;:{
         &quot;&quot;bytitle&quot;&quot;:{
            &quot;&quot;map&quot;&quot;:&quot;&quot;function (doc, meta) {\n if (doc.title &amp;&amp; doc.authors) { \n   emit(doc.title, null); \n }\n}&quot;&quot;
         },
         &quot;&quot;authorwithbookcount&quot;&quot;:{
            &quot;&quot;map&quot;&quot;:&quot;&quot;function (doc, meta) {\n  if (doc.authors &amp;&amp; doc.recommended) {\n    for (var i in doc.authors) {\n      emit(doc.authors[i], 1); \n    }\n  }\n}&quot;&quot;,
            &quot;&quot;reduce&quot;&quot;:&quot;&quot;function (keys, values, rereduce) {\n  if (!rereduce) {\n    return sum(values); \n  }\n}&quot;&quot;}}
         }&quot;;
   }
}
</pre>
<p style="text-align: justify"><span style="text-decoration: underline">Note</span>: This is a temporary solution to have the design document body, but I recommend you to create a C# class instance that can be mapped to that JSON body and transform it before make the request. That will be a better, and more elegant, way to do this.</p>
<p style="text-align: justify">Anyway, with the JSON body there we can make the <em>PUT </em>request now:</p>
<pre class="brush: csharp; title: ; notranslate">
var url = &quot;http://localhost:8091/couchBase/default/_design/dev_books&quot;;
var webRequest = new WebClient();
try
{
   webRequest.DownloadData(url);
}
catch (WebException ex)
{
   if (ex.Response is HttpWebResponse &amp;&amp; ((HttpWebResponse)ex.Response).StatusCode.Equals(HttpStatusCode.NotFound))
   {
      var data = Encoding.ASCII.GetBytes(JavascriptFunctions.Dev_Books_DesignDocument);
      webRequest.Headers.Add(&quot;Content-Type&quot;, &quot;application/json&quot;);
      webRequest.UploadData(url, &quot;PUT&quot;, data);
   }
   else
      throw;
}
</pre>
<p style="text-align: justify">Where are making a <em>PUT </em>request to the default bucket with the <em>_design/dev_books</em> id. If you go to your Views tab within the administration console you should see the design document and its views. At the code I&#8217;m trying to get the <em>design document</em> and if doesn&#8217;t exist within the DB (404 &#8211; not found) I&#8217;m creating it.</p>
<p style="text-align: justify">You can find the sample code <a href="https://docs.google.com/file/d/0B_7pmFlnMxlmUDFUNDJBQjFfMzQ/edit?usp=sharing">here</a>. As usually, I recommend you go to the <a href="http://www.couchbase.com/">DB home site</a>, download and try it yourself (you can do it from C#, using any other <a href="http://www.couchbase.com/develop">language</a> found there or simply by using the REST interface the server has).</p>
<p style="text-align: justify">That&#8217;s all folks!!</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing Couchbase under Windows 8</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/02/06/installing-couchbase-under-windows-8/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/02/06/installing-couchbase-under-windows-8/#comments</comments>
		<pubDate>Wed, 06 Feb 2013 21:03:42 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Couchbase]]></category>
		<category><![CDATA[DB]]></category>
		<category><![CDATA[Distributed databases]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Windows 8]]></category>
		<category><![CDATA[Distributed Databases]]></category>
		<category><![CDATA[NoSql]]></category>
		<category><![CDATA[Troubleshooting]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=505</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/02/06/installing-couchbase-under-windows-8/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify">The following are the workaround steps, that worked for me, when installing <a href="http://www.couchbase.com/">Couchbase</a> (<a href="http://www.couchbase.com/download">Enterprise Edition</a>) under a Windows 8 operating system. After following these steps I&#8217;ve been able to get a healthy instance running.</p>
<p style="text-align: justify">The workarounds in which this article is based can be found online, so here I&#8217;m going to keep it simple and just write a list of steps (you can refer to these articles, found at the end of this post, if you need more information). So after install the package you downloaded, a CouchbaseServer service (Windows Service) instance should be running as shown below:</p>
<p style="text-align: justify"><a href="http://blogs.southworks.net/mkrikorian/files/2013/02/image.png"><img style="border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2013/02/image_thumb.png" border="0" alt="image" width="667" height="50" /></a></p>
<p style="text-align: justify">Execute the following steps in order to get a working instance (if it&#8217;s not working yet):</p>
<ol>
<li><span style="text-align: justify"><strong>Stop </strong>the <em><strong>service</strong></em></span></li>
<li><strong>Edit </strong>the your Windows <em><strong>hosts file</strong></em> with Administrator rights</li>
<li><strong>Add </strong>the following line: <strong>127.0.0.1    couchbase-node1</strong></li>
<li><strong>Save </strong>and close the <strong><em>hosts file</em></strong></li>
<li>Now relative to the root folder where you installed Couchbase <strong>edit </strong>the <strong><em>.\Server\bin\service_register.bat</em></strong> with Administrator rights</li>
<li><strong>Update </strong>the line that is setting the <strong><em>NS_NAME</em></strong> var to be: <strong><em>set NS_NAME=ns_1@couchbase-node1</em></strong></li>
<li><strong>Update </strong>the line next to it to also <strong><em>set NS_NAME=ns_1@couchbase-node1</em></strong></li>
<li><strong>Save </strong>and close the file</li>
<li>From your Couchbase root folder <strong>delete </strong>the contents of <strong><em>.\Server\var\lib\couchbase\mnesia</em></strong></li>
<li>Now <strong>run </strong>the <strong><em>.\Server\bin\service_unregister.bat</em></strong> as Administrator (from your root folder)</li>
<li>Next <strong>run </strong>the <strong><em>.\Server\bin\service_register.bat</em></strong> file you edited</li>
<li>At this point if you run the service and check the listening sockets (netstat -a) you should seen ports 8091 &amp; 8092</li>
<li>To run the memcached healthy <strong>replace </strong>the <strong><em>libtcmalloc_minimal-4.dll</em></strong> (at .\Server\bin) with an previous version (<a href="https://docs.google.com/file/d/0B_7pmFlnMxlmSm9zemk3Mmd1Q3M/edit?usp=sharing">this </a>works for me)</li>
<li>And finally, <strong>start </strong>the <strong><em>service</em></strong></li>
</ol>
<p style="text-align: justify">After all these steps have been performed you should have access to your administrative console under IE (<a href="http://localhost:8091/">http://localhost:8091/</a>) and see everything running <strong>OK </strong>as shown below:</p>
<p><a href="http://blogs.southworks.net/mkrikorian/files/2013/02/image1.png"><img style="border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2013/02/image_thumb1.png" border="0" alt="image" width="668" height="469" /></a></p>
<p style="text-align: justify">
<p><em><strong>Related articles:</strong></em></p>
<p><a href="http://tugdualgrall.blogspot.com.ar/2012/12/what-to-do-if-your-couchbase-server.html">IP Address related</a></p>
<p>Allocation library related (<a href="http://www.couchbase.com/issues/browse/MB-6395">article1</a>, <a href="http://www.couchbase.com/issues/browse/MB-7016">article2</a>)</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A little of RavenDB</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/02/01/a-little-of-ravendb/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/02/01/a-little-of-ravendb/#comments</comments>
		<pubDate>Fri, 01 Feb 2013 21:44:32 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[DB]]></category>
		<category><![CDATA[Distributed databases]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[RavenDB]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Distributed Databases]]></category>
		<category><![CDATA[NoSql]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=382</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/02/01/a-little-of-ravendb/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify">Hi, a few days ago I published an article showing how you can easily use <a href="http://blogs.southworks.net/mkrikorian/2013/01/29/using-mongodb-from-c/">MongoDB under C#</a>. In this article I mainly plan to show the same operations or features, but using <a href="http://ravendb.net/">RavenDB</a>. As this database is built in C# it will be easier to integrate it a native C# client.</p>
<p style="text-align: justify">Besides both databases have very similar features, RavenDB supports ACID transactions under the unit or work pattern. For a fully set of features that both databases support, and a comparison, I suggest you to go to their respective home sites and read more about them.</p>
<p style="text-align: justify">So, in order to try some of its features, I&#8217;ve created a console application using RavenDB (after installing the server, the client driver is very simple to add to your solution &#8211; just using <a href="https://nuget.org/">NuGet</a>).</p>
<p style="text-align: justify">First at all you need to get a document store instance and configure it before using sessions, after you downloaded the <a href="https://nuget.org/packages/RavenDB.Client/2.0.2230">client NuGet package</a> you can do it like this:</p>
<p style="text-align: justify">
<pre class="brush: csharp; title: ; notranslate">
var documentStore = new DocumentStore { Url = &quot;http://localhost:8080/&quot; };
documentStore.DefaultDatabase = &quot;mauro&quot;;
documentStore.Conventions.FindTypeTagName = (t) =&gt; t.Equals(typeof(City)) ? &quot;Cities&quot; : string.Format(&quot;{0}s&quot;, t.Name);
documentStore.Initialize();
</pre>
<p style="text-align: justify">Now you can perform for example a book adding operation. You will have to do it under a session (that will track all your changes on objects, as an ORM does, and commit or discard the whole thing):</p>
<pre class="brush: csharp; title: ; notranslate">
using (var session = documentStore.OpenSession())
{
 session.Store(new Book
 {
   Title = &quot;For Whom the Bell Tolls&quot;,
   Authors = new string[] { &quot;Ernest Hemingway&quot; },
   Price = 15.64M
 });
 session.SaveChanges();
}
</pre>
<p>Where your <em>Book </em>class is defined as:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Book
{
 public string Title { get; set; }
 public string[] Authors { get; set; }
 public decimal Price { get; set; }
}
</pre>
<p style="text-align: justify">How we can iterate over all our book collection? Well, as RavenDB is &#8216;<a href="http://ravendb.net/docs/2.0/intro/safe-by-default">Safe by Default</a>&#8216; meaning, among other things, that you can NOT do a &#8216;<em>SELECT * from Books</em>&#8216; you will need to paginate through your collection or take another approach for custom queries and/or aggregation operations.</p>
<p style="text-align: justify">For this purpose is that RavenDB uses <a href="http://ravendb.net/docs/2.0/client-api/querying/using-linq-to-query-ravendb">indexes for everything</a>. And what is an index under this DB? Well, in the most simple concept an index here is a <a href="http://en.wikipedia.org/wiki/MapReduce">MapReduce </a>operation. If you don&#8217;t have an existing, or <em>static </em>in RavenDB language, index for a specific query, the server will create a temporary one for you when needs to resolve a query (I recommend you to read more about at the home site documentation as indexes are the core of the inner working of queries).</p>
<p style="text-align: justify">So, how we can define a <em>static </em>index to resolve a specific query? This is pretty simple from the C# client and using LINQ. You can set for example this index to query all the books in the book collection (anyway remember always the &#8216;safe&#8217; behavior):</p>
<pre class="brush: csharp; title: ; notranslate">
using (var session = documentStore.OpenSession())
{
 if (session.Advanced.DocumentStore.DatabaseCommands.GetIndex(&quot;allBooks&quot;) == null)
 {
   session.Advanced.DocumentStore.DatabaseCommands.PutIndex(&quot;allBooks&quot;, new IndexDefinitionBuilder&lt;Book&gt;
   {
      Map = documents =&gt; documents.Select(entity =&gt; new { })
   });
 }
}
</pre>
<p style="text-align: justify">You can choose to create an <em>IndexDefinition </em>with your map/reduce function as strings within it, or use the <em>IndexDefinitionBuilder </em>helper (as here) and make things easier as you can use code-insight help to write the LINQ queries and you have all your domain objects at hand. As we are returning an empty object here for each one of the iterated books we are creating like a &#8216;mock index&#8217; over the whole collection.</p>
<p style="text-align: justify"><em>Tip</em>: you can use this index to delete the book collection with the <em>DeleteByIndex()</em> command as it is shown next:</p>
<pre class="brush: csharp; title: ; notranslate">
session.Advanced.DocumentStore.DatabaseCommands.DeleteByIndex(&quot;allBooks&quot;, new IndexQuery());
</pre>
<p style="text-align: justify">You can create any index you want to this way, just using the <em>PutIndex()</em> command as shown above and the <em>IndexDefinitionBuilder </em>class, but what is the best practice to create an index?</p>
<p style="text-align: justify">Well, another way to define and create a <em>static </em>index within the DB is to inherit <em>AbstractIndexCreationTask&lt;TDocument&gt;</em> class and set the index properties and behavior within the new class ctor. Let&#8217;s use this approach to create an index per book&#8217;s title:</p>
<pre class="brush: csharp; title: ; notranslate">
public class BooksByTitleIndex : AbstractIndexCreationTask&lt;Book&gt;
{
 public BooksByTitleIndex()
 {
   this.Map = books =&gt; books.Select(book =&gt; new { Title = book.Title });

   //will analyze title to be available on search operations
   this.Indexes.Add(x =&gt; x.Title, FieldIndexing.Analyzed);
 }
}
</pre>
<p style="text-align: justify">Besides being the recommended approach to create <em>static </em>indexes, this one is also good for use them later on queries where you can explicitly tell the engine what index should use or leave it to be decided by the query resolver. In the following code you have two queries, the first one does not specify which index should use to resolve, and the second one does, anyway both queries in this case will use the same index: &#8216;<em>BooksByTitleIndex</em>&#8216;.</p>
<p style="text-align: justify">Why? Because the resolver sees that your are using the <em>Title </em>property of your class and it has an index for it.</p>
<pre class="brush: csharp; title: ; notranslate">
var book1 = session.Query&lt;Book&gt;()
      .Where(b =&gt; b.Title.Equals(&quot;Seven Databases in Seven Weeks&quot;))
      .FirstOrDefault();

var book2 = session.Query&lt;Book, BooksByTitleIndex&gt;()
      .Where(b =&gt; b.Title.Equals(&quot;Seven Databases in Seven Weeks&quot;))
      .FirstOrDefault();
</pre>
<p style="text-align: justify">But how do we create the index in the DB before executing the queries? Well, you can simple instantiate and call the <em>Execute()</em> method for your index, or use a <em>static </em>index creation helper class that takes all types that inherited from the <em>AbstractIndexCreationTask</em> class and creates the indexes for you if they don&#8217;t exist (it is recommended to do this when initializing):</p>
<pre class="brush: csharp; title: ; notranslate">
// create from index classes
IndexCreation.CreateIndexes(typeof(Program).Assembly, documentStore);
</pre>
<p style="text-align: justify">Now let’s say that you want to sum the prices of all books in your collection. Well that’s something that you can very easily do with just a couple of lines in C# using LINQ and workaround the &#8216;safe&#8217; behavior by retrieving pages of books (or change the &#8216;safe&#8217; behavior settings - although this is NOT recommended!).</p>
<p style="text-align: justify">The problem with this? You are transferring all the data to the client, need to paginate over all the books in your collection and it&#8217;s bizarre. The cost will be prohibitive if this collection is huge and you will be going against the &#8216;safe&#8217; behavior the DB has &#8211; that will be for sure a very bad design decision.</p>
<p style="text-align: justify">So let&#8217;s create a new index for this using the <a href="http://ravendb.net/docs/2.0/client-api/querying/static-indexes/defining-static-index">MapReduce features</a> RavenDB has for us. Again, we are going to define a class for the new index to follow best practices and, in addition, simplify our code after:</p>
<pre class="brush: csharp; title: ; notranslate">
public class SumBookPricesIndex: AbstractIndexCreationTask&lt;Book, SumBookPricesIndex.ReduceResult&gt;
{
 public class ReduceResult
 {
   public string SetOfBooks { get; set; }
   public decimal SumOfPrices { get; set; }
 }

 public SumBookPricesIndex()
 {
   this.Map = books =&gt; books.Select(book =&gt; new ReduceResult { SetOfBooks = &quot;all&quot;, SumOfPrices = book.Price });

   this.Reduce = results =&gt; results
      .GroupBy(result =&gt; result.SetOfBooks)
      .Select(group =&gt; new ReduceResult { SetOfBooks = group.Key, SumOfPrices = group.Sum(groupCount =&gt; groupCount.SumOfPrices) });
 }
}
</pre>
<p style="text-align: justify">Look how a new <em>ReduceResult </em>class is defined within the new index class. This is to make things easier later also, and because as the MapReduce engine could call reduce with mapped or reduced lists you will need to have a logic that can handle both type of items (this is the simplest way). Refer to the <a href="http://ravendb.net/docs/2.0/client-api/querying/static-indexes/defining-static-index">documentation </a>for more information.</p>
<p style="text-align: justify">How do you get the sum of  all the book prices using MapReduce then? It is very simple after you have the index shown above created, just like this:</p>
<pre class="brush: csharp; title: ; notranslate">
var sumOfBooksPrices = session
   .Query&lt;SumBookPricesIndex.ReduceResult, SumBookPricesIndex&gt;()
   .FirstOrDefault();
</pre>
<p style="text-align: justify">Here we are also using the <em>ReduceResult </em>class definition to indicate the query the type of the returned objects.</p>
<p style="text-align: justify">What if for example we want to group the authors in our DB and count their books? The driver does not support the<em> GroupBy()</em> operation (at least using the <em>Query()</em> method exposed by the LINQ interface &#8211; but it is supported within the <em>LuceneQuery()</em> advanced method)&#8230; So? Just create another index!</p>
<pre class="brush: csharp; title: ; notranslate">
public class GroupBookAuthorsIndex : AbstractIndexCreationTask&lt;Book, GroupBookAuthorsIndex.ReduceResult&gt;
{
 public class ReduceResult
 {
   public string Author { get; set; }
   public int NumberOfBooks { get; set; }
 }

 public GroupBookAuthorsIndex()
 {
   // be aware with linq queries [here SelectMany(authors,new) is not the same as SelectMany(authors).Select(new)]
   this.Map = books =&gt; books
      .SelectMany(book =&gt; book.Authors, (book, author) =&gt; new ReduceResult { Author = author, NumberOfBooks = 1 });

   this.Reduce = results =&gt; results
      .GroupBy(result =&gt; result.Author)
      .Select(group =&gt; new ReduceResult { Author = group.Key, NumberOfBooks = group.Sum(groupCount =&gt; groupCount.NumberOfBooks) });
 }
}
</pre>
<p style="text-align: justify">To finish this article I&#8217;ll show you a cool thing you can do by using RavenDB and taking advantage of the <a href="http://en.wikipedia.org/wiki/Lucene">Lucene engine</a> it relies on (in this particular case <a href="http://lucenenet.apache.org/">Lucene.NET</a>): the &#8220;Did you mean?&#8221; feature (<a href="http://ravendb.net/docs/2.0/client-api/querying/static-indexes/suggestions">suggestions</a>).</p>
<p style="text-align: justify">Let&#8217;s say that you want to look for a book title but remember just an approximate word or you did a typo when entering your search:</p>
<pre class="brush: csharp; title: ; notranslate">
var query = session.Query&lt;Book, BooksByTitleIndex&gt;().Where(book =&gt; book.Title.Equals(&quot;sells&quot;));
var searchedBook = query.FirstOrDefault();
</pre>
<p>And you have the following titles in your DB:</p>
<ul>
<li>For Whom the Bell Tolls</li>
<li>Cat&#8217;s Cradle</li>
<li>Slaughterhouse-Five</li>
<li>Seven Databases in Seven Weeks</li>
</ul>
<p>What will be the result (<em>searchedBook </em>variable)? Well, as there is no match for &#8216;<em>sells</em>&#8216; the result will be null.</p>
<p>At this point you can show suggestions to the user (using several comparison algorithms, the user&#8217;s input and your index&#8217;s tokens [<em>BooksByTitleIndex</em>]) calling the <em>Suggest()</em> method from the <em>LinqExtensions </em>class:</p>
<pre class="brush: csharp; title: ; notranslate">
if (searchedBook == null)
{
   Console.WriteLine(&quot;Did you mean:&quot;);
   foreach (var suggestion in query.Suggest(new SuggestionQuery { Accuracy = 0.4f, MaxSuggestions = 5 }).Suggestions)
   {
      Console.WriteLine(&quot;\t. {0}?&quot;, suggestion);
   }
}
</pre>
<p>Being the output something like this:</p>
<p>Did you mean:</p>
<ul>
<li>tools?</li>
<li>bell?</li>
<li>seven?</li>
</ul>
<p>You can find the sample code <a href="https://docs.google.com/file/d/0B_7pmFlnMxlmQU4wWkRZWEhwY3M/edit?usp=sharing">here</a>. Anyway, this is just the top of the iceberg, there is a lot of features (<a href="http://ravendb.net/docs/2.0/client-api/querying/handling-document-relationships">document relationships</a>, <a href="http://ravendb.net/docs/2.0/client-api/querying/polymorphism">polymorphic indexes</a>, <a href="http://ravendb.net/docs/2.0/client-api/querying/results-transformation">transformation of results</a>, <a href="http://ravendb.net/docs/2.0/client-api/querying/lazy-operations">lazy operations</a>, and many many more not just related to querying) RavenDB offers not used within this article. I recommend you to <a href="http://ravendb.net/download">download the DB</a> and give it a try.</p>
<p style="text-align: justify">
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using MongoDB from C#</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/01/29/using-mongodb-from-c/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/01/29/using-mongodb-from-c/#comments</comments>
		<pubDate>Tue, 29 Jan 2013 21:44:11 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[DB]]></category>
		<category><![CDATA[Distributed databases]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Distributed Databases]]></category>
		<category><![CDATA[NoSql]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=311</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/01/29/using-mongodb-from-c/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify">Today I&#8217;ve been playing a little with <a href="http://www.mongodb.org/">MongoDB</a>, and after enjoyed triggering a few commands from Mongo’s console, I decided to download, build and try the <a href="http://www.mongodb.org/display/DOCS/CSharp+Language+Center">C# driver</a>. Build it and use it is pretty straightforward, and in a couple of minutes you can be playing with your local database from a C# console application.</p>
<p style="text-align: justify">So I created a simple console application, that inserts and gets a couple of books from a DB collection in minutes with just very few simple steps. First at all you need to get a client instance and a server reference from C#, and using the driver you can do it like this:</p>
<pre class="brush: csharp; title: ; notranslate">
// connect to localhost and get server
var server = new MongoClient().GetServer();
var db = server.GetDatabase(&quot;mauro&quot;);

// get book collection and clean it
var books = db.GetCollection(&quot;books&quot;);
</pre>
<p style="text-align: justify">From now on you can start performing operations in your books collection, for example adding a new book:</p>
<pre class="brush: csharp; title: ; notranslate">
books.Insert(
 new BsonDocument
 {
   { &quot;Authors&quot;, new BsonArray { &quot;Ernest Hemingway&quot; } },
   { &quot;Title&quot;, &quot;For Whom the Bell Tolls&quot; },
   { &quot;Price&quot;, 31.53 }
 });
</pre>
<p style="text-align: justify">To learn about the <em>BsonDocument</em>, <em>BsonArray </em>and other types related to this DB, browse its information <a href="http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-TheBSONLibrary">here</a>.</p>
<p style="text-align: justify">If you are wondering why the keys for the JSON object are capitalized, you will find the answer in just a few  seconds, when a C# <em>Book </em>class will be introduced and used with the driver. This is an easy way to work with your domain objects as you would do if you were using an ORM. In this case I decided to follow C# convention when naming class properties (except for the _id used in Mongo) as you can see below:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Book
{
 public BsonObjectId _id { get; set; }
 public string Title { get; set; }
 public string[] Authors { get; set; }
 // decimal is not well-converted by the driver
 public double Price { get; set; }
}
</pre>
<p style="text-align: justify">Now that we have a <em>Book </em>class defined we can use it within the driver calls and work with this typed domain object. If you use the <em>db.GetCollection&lt;TDocumentType&gt;()</em> getter when instancing a collection of entities you will tell the driver that you want to wrap the BSON objects (managed under the hood) as <em>TDocumentType </em>objects:</p>
<pre class="brush: csharp; title: ; notranslate">
var typedBooks = db.GetCollection&lt;Book&gt;(&quot;books&quot;);
</pre>
<p style="text-align: justify">Now you can make iterate all the elements in this collection; each element returned as a Book instance:</p>
<pre class="brush: csharp; title: ; notranslate">
Console.WriteLine(&quot;\nRetrieving all books (typed collection)&quot;);
foreach (var book in typedBooks.FindAll())
{
   Console.WriteLine(string.Format(&quot;Book retrieved: {0}&quot;, book));
}
</pre>
<p style="text-align: justify">And, of course, you can also add a new <em>Book </em>instance to the collection in a more easy way that having to deal with ‘JSON’ in C#:</p>
<pre class="brush: csharp; title: ; notranslate">
typedBooks.Insert(new Book
 {
   Title = &quot;Seven Databases in Seven Weeks&quot;,
   Authors = new string[] { &quot;Eric Redmond&quot;, &quot;Jim R. Wilson&quot; },
   Price = 35.67
 })
</pre>
<p style="text-align: justify">At this point all these things are pretty much what any DB can offer (in addition to the ORM features we have from the driver), but what about using a little of <a href="http://en.wikipedia.org/wiki/MapReduce">MapReduce</a>?</p>
<p style="text-align: justify">Can I use it from C#? Yes!</p>
<p style="text-align: justify">Let’s say that you want to sum the prices of all books in your collection. Well that’s something that you can very easily do with just a single line in C# using LINQ:</p>
<pre class="brush: csharp; title: ; notranslate">
var allPrices = typedBooks.FindAll().Sum(b =&gt; b.Price);
Console.WriteLine(string.Format(&quot;Sum of all prices [linq]: ${0}&quot;, allPrices));
</pre>
<p style="text-align: justify">The problem with this? You are transferring all the data to the client, all the books in your collection. Think what will be the cost if this collection is huge! In addition, this is a simple process that just sum values, but what if the logic would be more complex and require more processing power to obtain the result in a reasonable time?</p>
<p style="text-align: justify">Fortunately, you can take advantage of the <a href="http://docs.mongodb.org/manual/applications/map-reduce/">MapReduce engine MongoDB provides</a>, besides being this the correct way to perform this kind of operations (over all your dataset). So let’s try MapReduce from C#.</p>
<p style="text-align: justify">First at all, I created a static class to put there my Javascript functions (as MongoDB talks Javascript):</p>
<pre class="brush: csharp; title: ; notranslate">
public static class JavascriptFunctions
{
 public static string MapBuildAllPricesKey
 {
   get
   {
      return &quot;function(obj) { return 'all'; }&quot;;
   }
 }

public static string MapAllPrices
 {
   get
   {
      return @&quot;function() { emit(buildAllPricesKey(this), this.Price); }&quot;;
   }
 }

public static string ReduceAllPrices
 {
   get
   {
      return @&quot;function(key, values) {
         var allPrices = 0;
         for (var i=0; i&lt;values.length; i++) {
            allPrices += values[i];
         }
         return { key: key, books: values.length, total: allPrices };
      }&quot;;
   }
 }
}
</pre>
<p style="text-align: justify">How can I use this functions now?</p>
<p style="text-align: justify">Well, the <em>MongoCollection </em>provides a <em>MapReduce()</em> method that you can use to instruct the server what are the map and reduce operations you want to perform over a collection.</p>
<p style="text-align: justify">In addition to just try MapReduce, I&#8217;ve also decided to take advantage of the possibiliy to store a function in the server (kind of stored procedure in RDBMS) and, as you can see, I&#8217;m planning to use it within the <em>MapAllPrices() </em>js function. Here’s the code to store a function in the server that can be called from other functions you upload:</p>
<pre class="brush: csharp; title: ; notranslate">
db.GetCollection(&quot;system.js&quot;).Save(
 new BsonDocument
 {
   { &quot;_id&quot;, &quot;buildAllPricesKey&quot; },
   { &quot;value&quot;, new BsonJavaScript(JavascriptFunctions.MapBuildAllPricesKey) }
 });
</pre>
<p style="text-align: justify">But how do we finally sum all prices using MapReduce? Easy, just like this:</p>
<pre class="brush: csharp; title: ; notranslate">
var mr = books.MapReduce(JavascriptFunctions.MapAllPrices, JavascriptFunctions.ReduceAllPrices);
Console.WriteLine(string.Format(&quot;Sum of all prices [map/reduce]: ${0}&quot;, mr.GetResults().First()[&quot;value&quot;][&quot;total&quot;]));
</pre>
<p style="text-align: justify">The mr variable contains the results of your MapReduce call, you can iterate its elements using LINQ (if the result values are many), here we are just taking the <em>First()</em> as we have only one.</p>
<p style="text-align: justify">You can find the complete sample <a href="https://docs.google.com/file/d/0B_7pmFlnMxlmaDR1ZG80aGNaUFE/edit">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A touch from the distributed NoSql DB world</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/01/28/a-touch-from-the-distributed-nosql-db-world/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/01/28/a-touch-from-the-distributed-nosql-db-world/#comments</comments>
		<pubDate>Mon, 28 Jan 2013 20:39:55 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[DB]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Distributed databases]]></category>
		<category><![CDATA[Distributed systems]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Distributed Databases]]></category>
		<category><![CDATA[NoSql]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=287</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/01/28/a-touch-from-the-distributed-nosql-db-world/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal" style="text-align: justify">Lately I’ve reading the ‘Seven Databases in Seven Weeks’ book, and besides recommending it if you like databases in general, there are a lot of interesting concepts and ideas to learn from. In this post I won’t be talking about the details or good uses of a particular DB or which one to choose to resolve a particular data problem you have, but from something that I enjoyed significantly more while reading: the supporting algorithms, data structures and architectures applied to resolve specific problems.</p>
<p class="MsoNormal" style="text-align: justify">I enjoy watching how complex things can be resolved with just a simple idea, or a couple of them, and this is the case in the DB world where the integration of all the things is more than the sum of individual parts. So, let’s start with the things that gladly caught my attention:</p>
<p class="MsoNormal" style="text-align: justify">One of the things I liked most and never gone into detail before, more than just heard its name and vaguely known what it could be used for, are the <a href="http://en.wikipedia.org/wiki/Bloom_filter">Bloom filters</a>. I gladly understood how some of the databases analyzed during the book take advantage of them in order to perform fast lookups when need to get a specific value. It is a good structure to manage a not accurate index using significantly less space than an accurate index would use and, with a certain probability and error rate, can tell you if the thing you are looking for is maybe there, or answer that is not there (being 100% sure – i.e. it guarantees no false negatives). One interesting thing about its theory is that you can calculate these probabilities according to how many bits you are using to track things, how many hash functions are used to evaluate each piece of data and how big the set you are indexing is getting (or will be). Using this and having an approximate idea of how your data will grow you can know the number of bits you need to maintain a filter with an error rate below a specific bound.</p>
<p class="MsoNormal" style="text-align: justify">A good practical example is how this is used within <a href="http://hbase.apache.org/">HBase</a>. As this database stores columns in chunks that are split among several servers according to some random sharding schema (decided by the servers), you can know what is the chunk you need to go looking for something but you don’t know it that something could be there or not (here a Bloom filter can avoid you to search at all if it answers that what you are looking for is not there). You can find an interactive example and related stuff <a href="http://billmill.org/bloomfilter-tutorial/">here</a>.</p>
<p class="MsoNormal" style="text-align: justify">Another interesting concept used in many <a href="http://en.wikipedia.org/wiki/NoSQL">NoSql databases</a> to resolve query and aggregation demands, among others, is the usage of the <a href="http://en.wikipedia.org/wiki/MapReduce">MapReduce</a> algorithm. Since the idea is very simple to understand, it is a powerful concept and unleashes you to perform whatever logic you want to execute over your distributed and probably huge sets of data in several ways. Its foundations is the <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm">divide and conquer</a> principle, where a task (or big problem) is split and treated as subtask (or small problems) returning partial results, and at the end a final step is performed to merge them all (this approach sometimes helps to simplify <a href="http://en.wikipedia.org/wiki/Computational_complexity_theory">computational complexity</a> and demanded resources, where both can be analyzed <a href="http://en.wikipedia.org/wiki/Big_O_notation">theoretically</a>). Besides, being a very old concept in computer science, the MapReduce new boom is related to how Google (who patented it) uses it to resolve its huge query demands. In this case this is just a particular scenario that happens on nodes within a cluster so it introduces parallelism as well. Each of the participants containing part of the data you need to process, and waiting for the function (or logic) each one must execute (over its owned set) in order to return its results to the caller. An overall view consists of: a first step (map) where you possibly evaluate and convert set of elements to another domain, and a merge step (reduce) that operates with the list of results from different nodes to generate the final result.</p>
<p class="MsoNormal" style="text-align: justify">A practical example of this can be found on <a href="http://basho.com/products/riak-overview/">Riak DB</a> where map/reduce function is sent to the cluster and distributed over the participant nodes in the “Riak Ring”. The map function is ran in each of the nodes in the cluster closer to where the data is (without the need to transfer ‘raw’ data through the network). So, besides avoiding network latency issues (by moving big sets of data), you don’t also need high centralized processing power as this architecture evaluates (in parallel) each subset in each individual node. Finally the reduce function is executed after all the partial results from nodes has been collected. You can find more details about how this works <a href="http://docs.basho.com/riak/1.2.0/tutorials/querying/MapReduce/">here</a>.</p>
<p class="MsoNormal" style="text-align: justify">A (very) interesting theorem, from theoretical computer science and related to distributed computing, is the <a href="http://en.wikipedia.org/wiki/CAP_theorem">CAP theorem</a>. This basically asserts that if you have a distributed system, you can have simultaneously two of the following properties: Consistency, Availability or Partition Tolerance, but not the three of them. Taking into consideration the environment and the many factors that act against a distributed system is not possible to fulfill these three features without falling into the <a href="http://en.wikipedia.org/wiki/Fallacies_of_Distributed_Computing">fallacies of distributed computing</a>.</p>
<p class="MsoNormal" style="text-align: justify">Beyond what the theorem says, it’s more interesting to see how some NoSql databases, that are also distributed, deal with it and allow ‘playing’ with this assertion. If we get Riak into scene again, we will find that this DB has an interesting way of parameterize its inner workings while reading/writing data within the cluster. Riak’s <a href="http://docs.basho.com/riak/1.3.0/references/appendices/concepts/Clusters/#The-Ring">ring architecture</a> distributes, and replicates, data within the nodes in its cluster. This clearly sets the DB as Partition Tolerance but other features are still available for you to play with: Consistency &amp; Availability. Nevertheless, in the case of Riak you will never achieve full consistency if you use it in a real distributed environment (Riak has something that it calls ‘<a href="http://docs.basho.com/riak/1.3.0/references/appendices/concepts/Eventual-Consistency/">Eventual Consistency’</a>).</p>
<p class="MsoNormal" style="text-align: justify">This database allows you to freely select the values for: the total of nodes (<em>N</em>) that will participate in replicating data, how many nodes should be written (<em>W</em>) before a successful write is returned, and how many nodes should be read (<em>R</em>) to get the latest value for a key. With these parameters you can for example achieve high availability by setting a high value for <em>N</em>, nevertheless, if what you want to achieve is consistency you can try setting <em>W</em>=<em>N</em> or <em>R</em>=<em>N</em> (leaving the other value <em>R</em> or <em>W</em> to 1), where the first set of settings is called <em>consistency by writes</em> and the last one <em>consistency by reads</em>. You can think that having a high <em>N</em> and one of two choices you can achieve both consistency and availability, but this is not the case as having a high number of replica nodes leads to the following scenario: if you choose to configure <em>consistency by writes</em>, the number of endpoints where an update can hit is bigger leading to inconsistent versions of data for the same key (that the user must resolve); in addition to degrading the performance when writing to multiple nodes. If you try to set <em>consistency by reads</em> you will finally find a similar scenario, showing that you can’t achieve both. I encourage you to read <a href="http://docs.basho.com/riak/1.3.0/references/appendices/concepts/Eventual-Consistency/">more</a> of how Riak allows you to play with it and its internals.</p>
<p style="text-align: justify">This is how Riak stands in front of the CAP theorem, and it’s nice to see how tweaking some parameters and playing a little with the cluster configuration, you can set Riak as {c}AP having sometimes (or eventually) consistency. Other databases achieve consistency or availability exclusively, but not both.</p>
<p style="text-align: justify">There are also another interesting structures used in the web distributed DB world that you can find, and if you like algorithms, data structures and architectures like me, I recommend you to dive into them: <a href="http://en.wikipedia.org/wiki/Inverted_index">inverted indexes</a>, <a href="http://en.wikipedia.org/wiki/Vector_clock">vector clocks</a>, <a href="http://en.wikipedia.org/wiki/Write-ahead_logging">write-ahead logging</a>, <a href="http://en.wikipedia.org/wiki/Distributed_file_system">distributed file systems</a>, <a href="http://en.wikipedia.org/wiki/Shard_(database_architecture)">DB sharding</a>, and many more.</p>
<p style="text-align: justify">Thanks for reading, happy diving!! <img src='http://blogs.southworks.net/mkrikorian/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate mappings tips using an Alternative Key</title>
		<link>http://blogs.southworks.net/mkrikorian/2013/01/28/nhibernate-mappings-tips-using-an-alternative-key/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2013/01/28/nhibernate-mappings-tips-using-an-alternative-key/#comments</comments>
		<pubDate>Mon, 28 Jan 2013 17:11:43 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[DB]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Alternative Key]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Mappings]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=249</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2013/01/28/nhibernate-mappings-tips-using-an-alternative-key/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p>Recently I’ve been working with NHibernate, and besides configuring trivial mappings, I had to deal with some not so trivial: when I wanted to link to tables using an alternative key between them. In this short post I’ll resume the necessary steps to do this in case you need to do it too (in a very easy and mechanical way).</p>
<p>Below is an abstraction of the datamodel I had that time (two tables related using an alternative key in the <em>Master</em>):</p>
<p><a href="http://blogs.southworks.net/mkrikorian/files/2013/01/image.png"><img style="border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2013/01/image_thumb.png" border="0" alt="image" width="583" height="224" /></a></p>
<p>Besides the primary key of each one of the tables (composite for <em>Master</em>, and not defined for <em>Detail</em>), you can see the relation among both tables by the <em>AlternativeKeyQ</em> field (by taking advantage of this unique field you don&#8217;t have to propagate the composite PK from <em>Master </em>to the <em>Detail</em>). Also the <em>Detail</em> table has a foreign key to another entity called <em>ForeignKeyN</em> in this case.</p>
<p>So, how do you setup the NHibernate mappings to make it work?</p>
<p>First at all you’ll need to define your domain object for <em>Detail</em>. Of course, you want to have a <em>Master</em> and a <em>ForeignKeyN</em> instances to allow easy navigability from <em>Detail</em> to both entities. So here is your base class defined in C#:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="638" valign="top">
<pre class="brush: csharp; title: ; notranslate">
public class Detail
{
public virtual Master Master { get; set; }
public virtual ForeignKeyN ForeignKeyN { get; set; }
}
</pre>
</td>
</tr>
</tbody>
</table>
<p>Now you have two navigation, and entity, properties in your <em>Detail</em> domain object. You need to define your mapping:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="638" valign="top">
<pre class="brush: xml; title: ; notranslate">
&lt;hibernate-mapping xmlns=&quot;urn:nhibernate-mapping-2.2&quot;&gt;
&lt;class name=&quot;MyNamespace.Detail, MyAssembly&quot; table=&quot;Detail&quot; lazy=&quot;true&quot;&gt;
&lt;many-to-one name=&quot;Master&quot; column=&quot;AlternativeKeyQ&quot; property-ref=&quot;AlternativeKeyQ&quot; class=&quot;MyNamespace.Master, MyAssembly&quot; /&gt;
&lt;many-to-one name=&quot;ForeignKeyN&quot; column=&quot;ForeignKeyN&quot; class=&quot;MyNamespace.ForeignKeyN, MyAssembly&quot; /&gt;
&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
</td>
</tr>
</tbody>
</table>
<p>You can see how the relation to <em>Master</em> is defined there, using the ‘property-ref’ attribute we let NHibernate know that we are using that field on the <em>Master</em> table to establish the relation. But if you try to parse this NHibernate mapping within a session you’ll receive an error saying that the entity doesn’t contain an identifier (basically).</p>
<p>So we’re going to fix this by adding an identifier to the entity, as we need to add this field to both (class and mapping) we are going to define it in a way that only NHibernate makes use of it:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="638" valign="top">
<pre class="brush: csharp; title: ; notranslate">
public class Detail
{
public virtual Master Master { get; set; }
public virtual ForeignKeyN ForeignKeyN { get; set; }
protected virtual int Id
{
get { return this.Master.AlternativeKey; }
set { // do nothing.. }
}
}
</pre>
</td>
</tr>
</tbody>
</table>
<p>Now we added a protected field to the <em>Detail</em> class that we are going to use as main identifier within the NHibernate mapping (but don’t expose it in the object’s interface – i.e. it won’t be visible to users).</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="638" valign="top">
<pre class="brush: xml; title: ; notranslate">
&lt;hibernate-mapping xmlns=&quot;urn:nhibernate-mapping-2.2&quot;&gt;
&lt;class name=&quot;MyNamespace.Detail, MyAssembly&quot; table=&quot;Detail&quot; lazy=&quot;true&quot;&gt;
&lt;id name=&quot;Id&quot; column=&quot;AlternativeKeyQ&quot; /&gt;
&lt;many-to-one name=&quot;Master&quot; column=&quot;AlternativeKeyQ&quot; property-ref=&quot;AlternativeKeyQ&quot; class=&quot;MyNamespace.Master, MyAssembly&quot; insert=&quot;false&quot; update=&quot;false&quot; /&gt;
&lt;many-to-one name=&quot;ForeignKeyN&quot; column=&quot;ForeignKeyN&quot; class=&quot;MyNamespace.ForeignKeyN, MyAssembly&quot; /&gt;
&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre>
</td>
</tr>
</tbody>
</table>
<p>As you can see in the mapping, we are using the <em>Id</em> property of the class as the identifier, and mapping it to the <em>AlternativeKeyQ</em> table field. We also disabled insertion or edition (insert=”false” – update=”false”) via the many-to-one <em>Master </em>property as otherwise it will clash with the <em>Id </em>update when NHibernate tries to update the entity.</p>
<p>In the <em>Master</em> mapping to add a bag with the <em>Detail</em> entities you have to use again the ‘property-ref’ attribute to let NHibernate know that you are linking these entities by <em>AlternativeKeyQ </em>field in the <em>Master</em> (if NHibernate requires you to override <em>Equals()</em> and <em>GetHashCode()</em> within your Detail domain object, use your new <em>Id</em> property to compare and return hash values).</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>User defined fields (UDF) with Windows Azure Table Storage using Azure SDK</title>
		<link>http://blogs.southworks.net/mkrikorian/2012/09/12/user-defined-fields-udf-with-windows-azure-table-storage-using-azure-sdk/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2012/09/12/user-defined-fields-udf-with-windows-azure-table-storage-using-azure-sdk/#comments</comments>
		<pubDate>Wed, 12 Sep 2012 00:34:30 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Data Extensibility]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Table Storage]]></category>
		<category><![CDATA[UDF]]></category>
		<category><![CDATA[Windows Azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=172</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2012/09/12/user-defined-fields-udf-with-windows-azure-table-storage-using-azure-sdk/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p>Lately, I’ve been working with the P&amp;P group and something came up requiring to do Data Extensibility within Azure Table Storage. As this storage model is different to traditional DB schemas, we’ve found a similar approach relying on reflection and continued using the <strong>Microsoft.WindowsAzure.StorageClient</strong> assembly provided by Azure’s SDK.</p>
<p>The problem to solve is how to allow the user have its custom UDFs within entities we’re storing at Azure Table Storage as the client API works with models inherited from <strong>TableServiceEntity</strong> (types that are well known at design time). Our core logic will not be aware of UDFs created by the customer, and in consequence, will not know their models. This is where reflection comes in!</p>
<p>So, let’s suppose the customer defines in ‘CustomerModels.dll’ assembly its own model as the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public class MyCustomEntityFields : TableServiceEntity
{
    public int MyCustomId { get; set; }
    public string MyCustomText { get; set; }
    public override string ToString()
    {
        return string.Format(&quot;CustomId: {0} - CustomText: {1}&quot;, this.MyCustomId, this.MyCustomText);
    }
}
</pre>
<p>Then you could associate by convention or configuration this model to your main entity, as a customer’s extension of main fields.  Things are simple when you add a new entity as you will associate the <em>PartitionKey</em> and <em>RowKey</em> to main entity’s keys and you will fill other properties by reflection (for example asking for them in the UI) and the <em>Add()</em> method supports any object. So you can have an adding code like this:</p>
<pre class="brush: csharp; title: ; notranslate">
var customType = customerAssembly.GetType(&quot;CustomerNamespace.MyCustomEntityFields&quot;);
var udfInstance = Activator.CreateInstance(customType) as TableServiceEntity;

// fill instance custom properties (interacting via UI?) { ... }

udfInstance.PartitionKey = entityPartitionKey;
udfInstance.RowKey = entityRowkey;

// save instance using the TableServiceContext.Add() method
</pre>
<p>Let’s suppose that after the user filled the instance properties in a ‘new entity’ page (you can map its properties to a dictionary via reflection, gather their values and set them back), and you do <em>udfInstance.ToString()</em> you get:</p>
<table style="border-width: 1px;border-style: solid;margin: 10px 0px 10px 0px" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="638" valign="top">CustomId:   17 – CustomText: positive number</td>
</tr>
</tbody>
</table>
<p>But what when you need to retrieve these fields to show their data in the UI for edition or details?  Well, as the <em>TableServiceContext.CreateQuery()</em> has a generic &lt;T&gt; parameter you don’t know (as the class/type is defined by the customer), is at this point when things get complicated and need to be solved using reflection. A practical approach to handle this is to create a ‘QueryWrapper’ class that you will instantiate via reflection and use it to retrieve this unknown instance data.  You can create a simple query wrapper like the one shown below that is going to help you to retrieve this unknown objects:</p>
<pre class="brush: csharp; title: ; notranslate">
public class UDFQueryWrapper where T : TableServiceEntity
{
    private readonly CloudStorageAccount account;
    private readonly string tableName;

    public UDFQueryWrapper(CloudStorageAccount account, string tableName)
    {
        this.account = account;
        this.tableName = tableName;
     }

    public IQueryable Query
    {
        get
        {
            var context = new TableServiceContext(this.account.TableEndpoint.ToString(), this.account.Credentials);
            return context.CreateQuery&lt;T&gt;(this.tableName).AsTableServiceQuery();
        }
     }
}
</pre>
<p>And you can create a static class with no generic parameter to make things even easier:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class UDFQueryWrapper
{
    public static IQueryable&lt;TableServiceEntity&gt; BuildQuery(CloudStorageAccount account, string tableName, Type udfType)
    {
        var queryWrapper = typeof(UDFQueryWrapper&lt;&gt;).MakeGenericType(new Type[] { udfType });
        var queryWrapperInstance = Activator.CreateInstance(queryWrapper, account, TableName);
        return (queryWrapper.GetProperty(&quot;Query&quot;).GetValue(queryWrapperInstance, null) as IQueryable&lt;TableServiceEntity&gt;);
    }
}
</pre>
<p>Then, when you need to get additional data for an entity you can take advantage of the <em>UDFQueryWrapper.BuildQuery()</em> method and you will use the <em>PartitionKey</em> and <em>RowKey</em> of the main entity to retrieve the correct instance data:</p>
<pre class="brush: csharp; title: ; notranslate">
var udfInstance = UDFQueryWrapper.BuildQuery(account, TableName, customType)
    .Where(e =&gt; e.PartitionKey.Equals(entityPartitionKey) &amp;&amp; e.RowKey.Equals(entityRowKey))
    .FirstOrDefault();
</pre>
<p>You can get the <em>udfInstance</em> data via reflection and if you call the <em>ToString()</em> overridden method you will get:</p>
<table style="border-width: 1px;border-style: solid;margin: 10px 0px 10px 0px" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="638" valign="top">CustomId:   17 – CustomText: positive number</td>
</tr>
</tbody>
</table>
<p>Just what you stored, demonstrating that the instance’s type and data binding were resolved correctly during retrieval <img src='http://blogs.southworks.net/mkrikorian/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Microsoft Trust Services to protect a shared resource</title>
		<link>http://blogs.southworks.net/mkrikorian/2012/08/08/using-microsoft-trust-services-to-protect-a-shared-resource/</link>
		<comments>http://blogs.southworks.net/mkrikorian/2012/08/08/using-microsoft-trust-services-to-protect-a-shared-resource/#comments</comments>
		<pubDate>Wed, 08 Aug 2012 19:08:39 +0000</pubDate>
		<dc:creator>mkrikorian</dc:creator>
				<category><![CDATA[Data Encryption]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Windows Azure]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Encryption]]></category>
		<category><![CDATA[PKI]]></category>
		<category><![CDATA[Symmetric key]]></category>

		<guid isPermaLink="false">http://blogs.southworks.net/mkrikorian/?p=136</guid>
		<description><![CDATA[... <a href="http://blogs.southworks.net/mkrikorian/2012/08/08/using-microsoft-trust-services-to-protect-a-shared-resource/" class="more-link">read more<img src="http://blogs.southworks.net/mkrikorian/wp-content/themes/southworks/assets/img/arrow-blue.png" width="12" height="12" alt="" /></a>]]></description>
			<content:encoded><![CDATA[<p>Microsoft Codename “Trust Services” lets several parties to encrypt/decrypt data over shared resources according to policies determined by an Administrator, where none of the parties have direct knowledge of the encryption key which is managed by a Trust Server. The Administrator, via an X509 certificate uploaded while provisioning a Trust Server, is the only one that can determine the ‘trusted’ partners and the authorization policies over resources. For detailed information about how all this is done you can check <a href="http://www.microsoft.com/en-us/sqlazurelabs/labs/trust-services.aspx">here</a>.</p>
<p>In this post I’ll show you with just a few steps how you can use it to secure a resource and shared only with a couple of partners. First at all you need to get the X509 certificates for the actors that are going to be involved. You should have both: the .CER format having only the public part of the RSA key and the .PFX format having the complete RSA key. To be used with the Trust Services SDK these certificates should have a key length of 1024 bits and should be able to encrypt and sign data.</p>
<p>You can use the MakeCert tool for create the certificates you’re going to need, for example:</p>
<table style="color: #000000" border="0" cellspacing="0" cellpadding="5" width="700">
<tbody>
<tr>
<td width="698" valign="top">
<ol>
<li><span style="font-family: Courier New;font-size: x-small">makecert.exe &#8220;Admin.cer&#8221; -r -n &#8220;CN=TS-Admin&#8221; -sr LocalMachine -ss My -sky exchange -pe -len 1024</span></li>
<li><span style="font-family: Courier New"><span style="font-size: x-small">makecert.exe &#8220;Partner1.cer&#8221; -r -n &#8220;CN=TS-Partner1&#8243; -sr LocalMachine -ss My -sky exchange -pe -len 1024</span></span></li>
<li><span style="font-family: Courier New"><span style="font-size: x-small">makecert.exe &#8220;Partner2.cer&#8221; -r -n &#8220;CN=TS-Partner2&#8243; -sr LocalMachine -ss My -sky exchange -pe -len 1024</span></span></li>
</ol>
</td>
</tr>
</tbody>
</table>
<p>By executing these commands you will create three new self-signed certificates which are valid to be used with the Trust Services SDK. You can then export the .PFX files needed from the certificate store (LocalMachine/My).</p>
<p>Next step is to provision a Trust Server. You can do this by going to the <a href="http://www.microsoft.com/en-us/sqlazurelabs/labs/trust-services.aspx">Trust Services site</a> and click on the ‘Use the Service’ link, sign in with your Live ID and create a new Trust Server establishing as TSPA’s certificate the Admin.cer created before.</p>
<p>The main scenario for using this service is when you upload sensitive data to the Cloud and want to protect it. Nevertheless, lets going to suppose that you have a shared repository in the file system where you store sensitive data and want only to be seen by authorized partners (but letting access to the resource to everyone). So first at all you have to define and ID for the resource or set of resources you want to protect. This is a simple task as you only need to define a resource Uri like the following one:</p>
<p><a href="http://blogs.southworks.net/mkrikorian/files/2012/08/image.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2012/08/image_thumb.png" border="0" alt="image" width="677" height="33" /></a></p>
<p>The next step is to use the management API via the SDK to authorize Partner1 and Partner2 to access the resources:</p>
<p><a href="http://blogs.southworks.net/mkrikorian/files/2012/08/image1.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2012/08/image_thumb1.png" border="0" alt="image" width="677" height="162" /></a></p>
<p>By doing this you are establishing an encryption policy for the Resource Uri and allow accessing it to both partners only. Now let’s suppose that Partner1 wants to update data and store it (protected) in the shared repository, it can easily do that by using the SDK as shown below:</p>
<p><a href="http://blogs.southworks.net/mkrikorian/files/2012/08/image2.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2012/08/image_thumb2.png" border="0" alt="image" width="677" height="165" /></a></p>
<p>By executing the code shown above Partner1 is storing the PlainData.txt file at a shared repository but encrypted. Performing this operation through the Trust Server ensures that: the data will no be accessed by unauthorized parties and no one has the key to decrypt it. So, if the Administrator decides to exclude a partner from the list of authorized people at the Trust Server then that partner will not be able to read the file content anymore.</p>
<p>When the authorized Partner2 wants to read the data stored in that shared resource he can do that by performing the following operations:</p>
<p><a href="http://blogs.southworks.net/mkrikorian/files/2012/08/image3.png"><img style="padding-top: 0px;padding-left: 0px;padding-right: 0px;border: 0px" src="http://blogs.southworks.net/mkrikorian/files/2012/08/image_thumb3.png" border="0" alt="image" width="677" height="165" /></a></p>
<p>Partner2 is able to read the original data (decrypted) while he belongs to the authorized partners list at the Trust Server, if the Administrator revokes its priviledges then he will not be able to decrypt CipherData.enc anymore as it does not know the encryption key.</p>
<p>To understand which is the mechanism that secures the data and how the keys are managed in a way that no one knows them I recommend you to see the videos at the web site mentioned before.</p>
]]></content:encoded>
			<wfw:commentRss></wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
