<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Francesco Cogno's blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/frcogno/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/frcogno/feed.xml</link>
    <description>Where data hit programming languages. Hard. In the shin.</description>
    <lastBuildDate>Tue, 16 Apr 2019 05:07:02 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>End-to-end WordCloud using Rust, TypeScript, AngularJS 2, and timdream's WordCloud</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/word_cloud</link>
      <pubDate>Fri, 26 Aug 2016 22:21:15 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/?p=315</guid>
      <description><![CDATA[Word clouds are a very attractive way of visually representing the relative importance of words. At...]]></description>
      <content:encoded><![CDATA[<p id="wordcloud-using-rust-typescript-angularjs-2-and-timdreams-wordcloud">Word clouds are a very attractive way of visually representing the relative importance of words. At a glance you can guess how important a word is relative to the others in the cloud. We will build two components:</p>

<ol>
 	<li style="text-align: justify">A text parser that will calculate the relative weight of each word in a given text (we'll use some classical texts as source). The text parser will also expose a JSON REST interface.</li>
 	<li style="text-align: justify">An AngularJS app that will get the JSON data and then pass it to timdream's WordCloud component in a suitable manner.</li>
</ol>
<p style="text-align: justify">The final result is like this:</p>
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/00.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/00.gif" alt="00" width="944" height="759" class="size-full wp-image-325 aligncenter" /></a>
<p style="text-align: justify">You can find the complete source code here: <a href="https://github.com/MindFlavor/word_count_rust_angular2">https://github.com/MindFlavor/word_count_rust_angular2</a>. Due to the nature of this blog we will discuss here the data management parts only. Our logic is pretty simple: count each occurrence of a word and use it to determine how big the word will appear in the cloud.</p>

<h2 id="angularjs-2-app">AngularJs 2 App</h2>
<p style="text-align: justify">There are many open source JavaScript libraries that render word clouds, for this post we'll use timdream's one: <a href="http://timdream.org/wordcloud/">http://timdream.org/wordcloud/</a>. Timdream's library comes complete with Typings which is helpful working with TypeScript. This time I will skip the steps required to startup a TypeScript project in Visual Studio Code. If you need more help please refer to my previous post: <a href="http://bit.ly/bcts1">How to render SQL Server acyclic blocking graphs using Visual Studio Code, TypeScript, NodeJS and TreantJS – Part 1</a>.</p>

<h3 id="service" style="text-align: justify">Service</h3>
<p style="text-align: justify">We will start with the service. The service is responsible to retrieve the data (an HTTP GET) and to map it to the strongly typed class. The class for our word weight is a two-liner:</p>
<script src="https://gist.github.com/MindFlavor/747f31ca5cdcb24adae2fbf8b5c9f89d.js"></script>

The service itself is:

<script src="https://gist.github.com/MindFlavor/b7c47b175c2d39c6cf90e4c86bfd6231.js"></script>
<div style="text-align: justify">Notice the <code>@Injectable</code> attribute. It's required so Angular knows that our service can be injected in our component. We are also requesting an instance of the <code>Http</code> class in the constructor (via dependency injection). We can then use <code>Http </code>member to get the JSON from our service.</div>
<p style="text-align: justify">Using <code>Promise</code>s, along with the TypeScript's arrow operator, makes the code simple and easy to follow.</p>

<h3 id="component">Component</h3>
<p style="text-align: justify">The Angular component requests the service as prerequisite. It does it in the class decorator under the name <code>providers</code>:</p>
<script src="https://gist.github.com/MindFlavor/1d9546263420e43b9400244acee75783.js"></script>

<div style="text-align: justify">And requests its injection in the constructor:</div>

<script src="https://gist.github.com/MindFlavor/cf4641deb4f482af7654c04c07b5d7fa.js"></script>
<div style="text-align: justify"><span class="hljs-keyword"></span>The WordCloud code is in the <code>setText</code> method. Here, again, we exploit the <code>Promise</code> in order to get rid of the async HTTP call:</div>
<script src="https://gist.github.com/MindFlavor/f3ccccfb999ccd3b5264464e24e150e2.js"></script>

<div style="text-align: justify">That's it for our presentation layer. If we want to try it we can create a mock service returning static values. For example:</div>

<script src="https://gist.github.com/MindFlavor/2ffe06e446b089d46202317b4c1a4c6f.js"></script>
<p style="text-align: justify">Now just inject the mock service instead of the real one and test the app.</p>

<h2 id="wordcount-service">WordCount service</h2>
<p style="text-align: justify">The WordCount service should simply count the occurrences of every word in a given file. This is basically the textbook example of map/reduce. To spice the things up a bit we also want to:</p>

<ol>
 	<li>Exclude noise words (based on a dictionary).</li>
 	<li>Consolidate similar words (singular/plural, synonyms, etc...).</li>
</ol>
<p style="text-align: justify">We also want to create a multithreaded word count service. If we are CPU-bound this should help to speed up the computation on multithreaded machines. This kind of programs are - this example excluded - hard to code. Fortunately there are new languages built from the ground up to tackle the concurrency problems. One I particularly like is Rust (<a href="https://www.rust-lang.org">https://www.rust-lang.org</a>). While targeted to systems programming Rust can be successfully used for other tasks too. In our case it forces us to think about <em>ownership</em> of shared resources, which is good for multithreaded applications (you can find more about it in this blog post <a href="https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html">https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html</a>).</p>
Let's recap the serial logic:
<ol>
 	<li>Load a file. For each word:
<ol>
 	<li>Check if is a noise word.</li>
 	<li>Lookup the most relevant synonym (if any). If found use it instead of the original word.</li>
 	<li>Increase the word's count by one.</li>
</ol>
</li>
 	<li>Present the total per word ordered by occurrence count.</li>
</ol>
<p style="text-align: justify">If we were able to apply the serial logic in parallel we could come up with:</p>

<ol>
 	<li>Load the file. For each word:
<ol>
 	<li>Find an available thread and dispatch the word to it.</li>
</ol>
</li>
 	<li>Each thread will, for each word received:
<ol>
 	<li>Check if it is a noise word.</li>
 	<li>Lookup the most relevant synonym (if any). If found use it instead of the original word.</li>
 	<li>Increase the word's count by one.</li>
</ol>
</li>
 	<li>When all the words are dispatched and processed, present the total per word ordered by occurrences.</li>
</ol>
<h3 id="the-data-race">The data race</h3>
<p style="text-align: justify">The parallel algorithm is good in theory but poses some immediate questions: "<em>How do I dispatch a word to a thread?"</em> or "<em>How can a thread know when there are no more words to process?"</em>.</p>
<p style="text-align: justify">The biggest problem, however, lies in the data race between threads. The step <em>Increase the word's count by one</em> will be performed by multiple threads in parallel and, unless we mediate the access to the <em>counter</em> somehow, problems will arise. This is nasty because, in most languages, your code will compile and run even if you were modifying the same object from multiple threads. The result can be a segfault if you're lucky or, <strong>way</strong> worse, miscalculations.</p>
<p style="text-align: justify">Bottom line you're own your own. If you are a superstar coder you will prevent problems and end up with an efficient concurrent algorithm. But if you're a normal person like me, chances are you will end up scratching your head at the pseudo random errors.</p>
<p style="text-align: justify">The good news is, with Rust, you <strong>cannot</strong> forget about such things. Rust will force you to prevent data races or your code won't even compile.</p>
<p style="text-align: justify">Even the apparent innocuous concurrent access to a shared vector should be safe. With Rust it <strong>must</strong> be safe (thankfully). Let's see how.</p>

<h3 id="concurrent-access-to-a-shared-resource">Concurrent access to a shared resource</h3>
<p style="text-align: justify">Let's try to share an immutable vector across threads. A first approach could be:</p>
<script src="https://gist.github.com/MindFlavor/dd04bd956ef228b3185b2f535ed95125.js"></script>

Here we declare a vector (<code>v</code>) and then we spawn 3 threads that will print the vector contents concurrently. Seems legitimate? Well, it isn't. Rust will tell us why:

<script src="https://gist.github.com/MindFlavor/fa96a0a9adb03ccf8b06aaf24ace99cc.js"></script>
<div style="text-align: justify">Rust tell us that the thread may outlive <code>work</code> (the spawning function). But if the spawning function (<code>work</code>) terminates, what happens to the vector <code>v</code>? Since the <em>ownership</em> of <code>v</code> belongs to <code>work</code> and not the threads, as soon as <code>work</code> finishes the vector would be deallocated. And the threads would end up keeping a reference to dellocated memory. <strong>Bad</strong>.</div>
<div style="text-align: justify"></div>
<h3 id="transferring-ownership">Transferring ownership</h3>
<p style="text-align: justify">Rust's new error system will suggest you to move (transfer) the ownership of the vector to the thread. It makes sense: if <code>work</code> relinquishes the ownership of <code>v</code> to the thread it will no longer deallocate <code>v</code>. <code>v</code> would get deallocated at the end of the thread (as it should).</p>
<p style="text-align: justify">Let's try it (notice the <code>move</code> keyword before the closure):</p>
<script src="https://gist.github.com/MindFlavor/72d9c5520020015616fb43feee53c2b6.js"></script>

Will this work? No. Rust error is like this one:

<script src="https://gist.github.com/MindFlavor/b7ca9601bf8425989a1c75a1c248b908.js"></script>
<p style="text-align: justify">The error this time is harder to interpret. The hint is in the note: <code>v does not implement `Copy` trait</code>. Why Rust tries to copy our vector instead of simply transferring ownership? Because we are transferring the ownership of <em>one </em>vector to <em>three</em> threads. Since it's impossible Rust tries to send <em>three</em> separate copies of our vector to our <em>three</em> threads. But since by default our structures cannot be copied it doesn't work (luckily because it's not something we wanted to do in the first place).</p>
<p style="text-align: justify">Go on and try to remove the <code>for loop</code> and spawn a <em>single</em> thread instead of <em>three</em>. In that case the move will work.</p>

<h3 id="reference-counted-pointers">Reference-counted pointers</h3>
<p style="text-align: justify">Clearly moving the ownership of the vector to our threads cannot work without copying it for each thread. This solution is a waste of memory since we know our vector to be immutable. We should be able to access it concurrently without mutexes of any kind. But without copies we cannot move the vector and without move the thread will outlast the vector.</p>
<p style="text-align: justify">So, how do we solve the lifespan problem?</p>
<p style="text-align: justify">One answer is to use reference counted pointers. These wrappers will keep count of how many references are present at any time and only deallocate the inner object when nobody else is referencing it. It's roughly what a GC-based language would do. Only here we get deterministic deallocation (and also the circular reference problem).</p>
<p style="text-align: justify">In our case it means the inner object will be referenced by the <code>work</code> function and by <em>each</em> thread. So there are 4 references (1 for <code>work</code> + 1 for each thread). When <code>work</code> terminates the reference count will simply drop to 3. And the vector won't be deallocated (yet).</p>
<p style="text-align: justify">You can read more about it here: <a href="https://doc.rust-lang.org/std/sync/struct.Arc.html">https://doc.rust-lang.org/std/sync/struct.Arc.html</a> and here <a href="https://doc.rust-lang.org/book/concurrency.html">https://doc.rust-lang.org/book/concurrency.html</a>.</p>
<p style="text-align: justify">That's our final, working, code:</p>
<script src="https://gist.github.com/MindFlavor/06d53b34bd6e98a21494adc03df2b8f2.js"></script>

<div style="text-align: justify"><span class="hljs-function"><span class="hljs-keyword"></span></span>If you try to call it chances are your program will terminate even before the threads have got a chance to print the vector. You could join the threads or, better, coordinate the execution via <code>channels</code>.</div>
<div style="text-align: justify"></div>
<h3 id="channels">Channels</h3>

Channels are an elegant way to send messages between threads. Rust's channels are special: they are also able to transfer <em>ownership</em> of entities between threads. Let's see how with an example.

We have this super dumb function that returns a Vector:

<script src="https://gist.github.com/MindFlavor/a7cc4d1100bb72a77101a29c2f04933b.js"></script>
<div style="text-align: justify"><span class="hljs-function"><span class="hljs-keyword"></span></span>If we were to run it in a separate thread we could call the <code>join</code> method of the thread and retrieve the result:</div>
<script src="https://gist.github.com/MindFlavor/1cb223a2f4cac8efde581496a178d115.js"></script>

<div style="text-align: justify"><span class="hljs-function"><span class="hljs-keyword"></span></span>It works (unwrap notwithstanding) but if we wanted to return data from the thread as soon as it's created? The answer is simple: open a channel between threads.</div>
<div style="text-align: justify"></div>

<script src="https://gist.github.com/MindFlavor/4e816d5eff2ddebc4262bd927f6a8c0e.js"></script>
<div style="text-align: justify"><span class="hljs-function"><span class="hljs-keyword"></span></span>In this example we are sending unsigned longs but we could send anything. In our WordCount service we will be sending in lines to be processed and we will receive back the partial word count. In other words, we will stream lines into the thread to be processed as fast as possibile. When there are no more rows to process we will close the channel. This way the processing thread will know that there is no more data and should produce the results. The results are sent back via another channel which in fact moves the ownership back to the main thread. At this point the processing thread can terminate.</div>
<div style="text-align: justify"></div>
<h2 id="putting-all-together">Putting all together</h2>
<p style="text-align: justify">Now that we are able to share safely an immutable structure between threads and to send ownership using channels we can implement our concurrent word counter method:</p>
<script src="https://gist.github.com/MindFlavor/297c9b52ccb0d04bcc5f26dd28ff80b1.js"></script>
<div style="text-align: justify"><span class="hljs-function"><span class="hljs-keyword"></span></span>Now all we have to do is to expose this method through a REST interface. For this I've used <a href="https://github.com/iron/iron">Iron framework</a>. I will not show the code here since it's very simple.</div>
<p style="text-align: justify">This example of <span style="color: #808000">parallel map =&gt; parallel reduce =&gt; serial reduce</span> is surprisingly fast and, last but not least, cross platform.</p>
<p style="text-align: justify">I'm sure better performance can be achieved further optimizing the code but I'll leave it up to you :).</p>


<hr />

&nbsp;

Happy coding,

<a href="mailto:francesco.cogno@outlook.com">Francesco Cogno</a>]]></content:encoded>
    </item>
    <item>
      <title>How to render SQL Server acyclic blocking graphs using Visual Studio Code, TypeScript, NodeJS and TreantJS – Part 2</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/how-to-render-sql-server-acyclic-blocking-graphs-using-visual-studio-code-typescript-nodejs-and-treantjs-part-2</link>
      <pubDate>Thu, 04 Aug 2016 22:57:03 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/?p=245</guid>
      <description><![CDATA[Recap
In the previous blog post (you can find it here: http://bit.ly/bcts1) we've seen how to setup...]]></description>
      <content:encoded><![CDATA[<h2 id="recap">Recap</h2>
<p style="text-align: justify">In the previous blog post (you can find it here: <a href="http://bit.ly/bcts1">http://bit.ly/bcts1</a>) we've seen how to setup a NodeJs REST application in Visual Studio Code. We've also seen how easy is to debug the application without leaving the IDE. In this second part, we will see how to wire some data to a gorgeous library: <a href="https://github.com/fperucic/treant-js">TreantJS</a>. In our example, we wanted to be able to graphically visualize the SQL Server acyclic blocking graph. Let's review the server code:</p>
<script src="https://gist.github.com/MindFlavor/1cedabb172adbc7f03ac97f4a2d58970.js"></script>

This code is fairly simple. All we do is register a path (<code>/spwho</code>) in <code>express</code>. That URL will trigger the <code>spWhoService.GetEntries()</code> code. That code, upon success, will return a JSON representation of the <code>sp_who</code> stored procedure.

The service, in case you are wondering, is like this:

<script src="https://gist.github.com/MindFlavor/98edec8de50fc7e61e8c117c7d02b509.js"></script>
<p style="text-align: justify">As you can see we are returning a strongly-typed array - in fact a promise to be fulfilled. We use an interface in order to render unit testing using mock services easier.</p>

<h2 id="next-step">Next step</h2>
<p style="text-align: justify">What we need now is to create an html page that will call our web service, do some data manipulation and then render the graph. We want to do it in TypeScript (obviously) and we want to use Visual Studio Code.</p>

<h3 id="debugger-for-chrome">Debugger for Chrome</h3>
<p style="text-align: justify">There are many techniques for debugging a TypeScript transpiled code. Visual Studio Code, using the <a href="https://github.com/Microsoft/vscode-chrome-debug">Debugger for Chrome plugin</a>, has first class support to web debugging. You can set breakpoints in the code and, upon hit, the browser will pause and surrender control to Visual Studio Code. From there, you will be able to inspect the variables, call stack, execute a step over, step into, and so on.</p>

<h2 id="dual-debugging">Dual debugging</h2>
<p style="text-align: justify">We want to be able to debug the NodeJs server and the Chrome webapp so we can follow the data from end to end. But how to debug a NodeJs server <strong>and</strong> a Chrome webapp at the same time in the same Visual Studio Code solution? Ideally we want to setup two different Visual Studio Code solutions, one for the NodeJs server and another for the webapp. But the webpage will be sent by the server (so the code must be there), not by the webapp solution. There are many ways to solve this chicken-and-egg solution. I usually end up using symbolic links but any vendoring technique should be fine.</p>
<p style="text-align: justify">In my case I will have the final web folder in the NodeJs solution (to be exported as static files by <code>express</code>). I will not, however, use it from there. I will, instead, create a new solution specific for the webapp and link the web folder from the NodeJs solution. This way I can work on my webapp solution and publish only the transpiled files (which I would want to do anyway). I'll be able to debug the webapp from my source TypeScript files since I'll configure the source maps. The downside of this technique is that is very git unfriendly. You can solve this limitation with <code>git submodules</code> but it's beyond the scope of this article (for more info, see here:<a href="https://git-scm.com/docs/git-submodule">https://git-scm.com/docs/git-submodule</a>).
This is how the webapp folder appears in my solution. Notice I've also linked the typings folder so the code will compile successfully in both solutions.</p>
<p style="text-align: justify"><a href="https://msdnshared.blob.core.windows.net/media/2016/08/00.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/00.png" alt="00" width="912" height="393" class="size-full wp-image-255 aligncenter" /></a></p>
<p style="text-align: justify"><span>Once set - I will skip the details now - you will be able to hit breakpoints in Chrome even if the </span><em>source</em><span> code comes from another solution. Here I show you how the debugging works.</span></p>
<p style="text-align: justify"><a href="https://msdnshared.blob.core.windows.net/media/2016/08/01.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/01.gif" alt="01" width="1030" height="800" class="size-full wp-image-265 aligncenter" /></a></p>

<h2 id="typescript-and-browsers">TypeScript and browsers</h2>
<p style="text-align: justify">One of the main problems when working with browsers instead of NodeJs is the complexity of module loading. Fortunately there are many high-quality module loaders. I use SystemJs (<a href="https://github.com/systemjs/systemjs">https://github.com/systemjs/systemjs</a>) because I find it clear. Your mileage may vary, pick the one that better suits your needs. Here is a very simple SystemJs loader (extracted from <code>index.html</code>):</p>
<script src="https://gist.github.com/MindFlavor/70231561d53a917b6986fc5c95b9e8d4.js"></script>

We don't need many advanced SystemJs features because the transpilation process will be handled by tsc (and Visual Studio Code) so all we have to do is to point it to the dependency folders.

<h2 id="mapping-json-to-strongly-typed-entries">Mapping JSON to strongly typed entries</h2>

In our NodeJs server solution we publish, as JSON, entities called <code>WhoEntry</code>. These are the representation of a single sp_who row.

<script src="https://gist.github.com/MindFlavor/7db2634981140ca7797c217d989aee2b.js"></script>
<p style="text-align: justify">Our client webapp, however, receives the JSON which is not strongly typed. In order to get the WhoEntry class back all we have to do is to map the JSON to our class:</p>
<script src="https://gist.github.com/MindFlavor/89780e169249e173e4403da4f6ca181e.js"></script>

This of course works since we have a non-written contract between server and client. Using the same source file helps to avoid conversion errors.

<h2 id="treantjs">TreantJS</h2>

TreantJS requires you to create a hierarchical structure: any node can have zero to infinite childs and so on. What we will do is to start from the root SPID (the blocking one) and then add its blocked SPIDs as childs. Then, recursively, we'll add their own blocked SPIDs until there are no more blocked SPIDs. But first how can we identify the root blocking SPID?

<h3 id="root-blocking-spids">Root blocking SPIDs</h3>

The logic is simple. The root blocking SPID is the one blocking something but not blocked by something else. In other word, there must be at least one WhoEntry with blk equals the SPID. And the SPID's blk entry must be zero:

<script src="https://gist.github.com/MindFlavor/ff0d1a582285fc3f2e093810732fd9de.js"></script>
<p style="text-align: justify">Notice in the code we relaxed the assumption of having only one root blocking SPID in a given scenario.</p>

<h3 id="recursively-add-blocked-spids">Recursively add blocked SPIDs</h3>
<p style="text-align: justify">The recursive function can be functional - better - or purely side effecting like this one:</p>
<script src="https://gist.github.com/MindFlavor/5b2a1b0800b042a8386ffd7367c1d05a.js"></script>

<h3 id="treantjs-again">TreantJS again</h3>

Now that we have the hierarchical structure in place all we have to do is to add some mandatory fields (container, etc...) and create the Treant object. We choose to hide the root node since it does not give any useful information. You can experiment a bit, TrantJS is very powerful and customizable.

<script src="https://gist.github.com/MindFlavor/fdcdbc4856aeb66ff361ebb40381e58f.js"></script>
<h2 id="final-result">Final result</h2>
<p style="text-align: justify">Let's try our solution. Fire the NodeJs server (remember to configure the SQL Server connection properties or use the mock service) and open a browser pointing to <a href="http://localhost:3000">http://localhost:3000</a>. You should see the blocking graph (or nothing if you don't have any blocking, play with TRANSACTIONs to create one!).</p>
<p style="text-align: justify">For example, suppose to have this output from <code>sp_who</code>:</p>
<p style="text-align: justify"><a href="https://msdnshared.blob.core.windows.net/media/2016/08/03.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/03.png" alt="03" width="806" height="595" class="size-full wp-image-285 aligncenter" /></a></p>
<p style="text-align: justify"><span>Our code will create this JSON:</span></p>
<script src="https://gist.github.com/MindFlavor/c3d0809cd24bef20f71ee80497b90add.js"></script>
<p style="text-align: justify">TreantJS ignores the extra fields, like whoEntry in our case. We added it to make the recursive function easier.</p>
<p style="text-align: justify">This JSON, given to TreantJS with a very basic CSS, gives us the expected result:</p>
<p style="text-align: justify"><a href="https://msdnshared.blob.core.windows.net/media/2016/08/04.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/04.png" alt="04" width="1046" height="691" class="size-full wp-image-295 aligncenter" /></a></p>
<p style="text-align: justify">As you can see from the picture above, someone (SPID 54) left a transaction open! All in all, the sloc is minimal and the result is useful. If you export the connection string you will have a handy tool to impress fellow DBAs: all you need is a NodeJs installation. Even your laptop can do that!</p>


<hr />

<strong>Happy coding</strong>,

<a href="mailto:francesco.cogno@outlook.com">Francesco Cogno</a>]]></content:encoded>
    </item>
    <item>
      <title>How to render SQL Server acyclic blocking graphs using Visual Studio Code, TypeScript, NodeJS and TreantJS - Part 1</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/how-to-render-sql-server-acyclic-blocking-graphs-using-visual-studio-code-typescript-nodejs-and-treantjs-part-1</link>
      <pubDate>Sun, 31 Jul 2016 22:03:51 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/?p=155</guid>
      <description><![CDATA[Introduction
SQL Server uses blocking - among other technologies - to ensure ACID transactions....]]></description>
      <content:encoded><![CDATA[<h2>Introduction</h2>
<p style="text-align: justify">SQL Server uses blocking - among other technologies - to ensure ACID transactions. There are a lot of lock types in SQL Server, ranging from Shared and Exclusive, Page and Range or even table level. You can find more about these here: <a href="https://technet.microsoft.com/en-us/library/ms175519(v=sql.105).aspx">[TechNet] - Lock Modes</a>. Whenever SQL server tries to acquire a lock on a resource and that resource is already owned by another, incompatible lock, blocking occurs. Depending on how long - and how often - these blocks persist the execution slowdown becomes noticeable. We will use this premise in order to show how to create a simple SQL Server-backed web site using Visual Studio Code, NodeJS and TypeScript. Since the post is very long I'll split it into two separate ones. In the first part we'll setup Visual Studio code for TypeScript + NodeJs debugging. We will also create a skeleton web service using express and mssql packages. In the second part we will create a TrantJs page rendering the data provided by the REST API just created. You can find the following post here: <a href="http://bit.ly/bcts2">http://bit.ly/bcts2</a>.</p>

<h2>How to inspect blocking</h2>
<p style="text-align: justify">There are many ways to find out the SPIDs (process IDs) involved in blocking. For the purpose of this article, we will focus on the sp_who stored procedure. This little helper will give back the current list of processes active in SQL Server along with the blocking process, if any. You can find more details here: <a href="https://msdn.microsoft.com/en-us/library/ms174313.aspx">https://msdn.microsoft.com/en-us/library/ms174313.aspx</a>.</p>
In the following example we have some blocked processes:

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/017.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/017.png" alt="01" width="631" height="428" class="alignnone size-full wp-image-196" /></a>
<p style="text-align: justify">The column blk is either zero - no blocking - or the SPID blocking the session. In the example we see the SPID 54 blocked by 55. The SPID 54 blocks SPID 56 and SPID 62 in turn. The SPID 56 blocks SPID 60. These blocked processes are a directed <em>acyclic</em> graph (if it were a <em>cyclic</em> graph we would have had a deadlock instead).</p>
The blocked graph could be better visualized like this:

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/00.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/00.png" alt="00" width="919" height="612" class="alignnone size-full wp-image-205" /></a>
<p style="text-align: justify">Suppose now you are a DBA tasked on killing the offending SPID. But you cannot kill SPIDs at random: for example, killing SPID 56 is not guaranteed to resolve the problem because the SPID 60 might end up blocked by SPID 55. So, in general, you want to kill the root SPID - that is, the one blocking one or more SPIDs without being blocked by someone else. In our example the root SPID is SPID 55. It's easy to find the root in our graph but it's hard to do with the sp_who output because we will have to re-create the graph in our heads first (and when there are hundreds of blocked processes the task becomes daunting).</p>
So what about a tool to visualize the blocking graph on demand?
<h2>Architecture</h2>
<p style="text-align: justify">For our tool we will use many open source technologies. We will use <a href="https://nodejs.org/en/">NodeJs</a> with <a href="https://expressjs.com/">Express</a> for the backend and <a href="https://github.com/fperucic/treant-js">TreantJs</a> for the graph.</p>
Something like this:

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/028.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/028.png" alt="02" width="1031" height="115" class="alignnone size-full wp-image-195" /></a>
<h2>Setup</h2>
<h3>npm and TypeScript</h3>
<p style="text-align: justify">Generally speaking setting up a TypeScript project is cumbersome - especially if you are spoiled like me by Visual Studio. You need to have Node and npm installed (if you don't, go <a href="https://www.npmjs.com/package/npm">here</a>). First create a working folder, go in it and initialize the project:</p>
<script src="https://gist.github.com/MindFlavor/4210c293e5fa96e140ef55dd63aba2dd.js"></script>

Now install TypeScript and Typings:

<script src="https://gist.github.com/MindFlavor/72e8fdbc697c31d1a80fa0ef862423ce.js"></script>

Now initialize the TypeScript compiler options and Typings:

<script src="https://gist.github.com/MindFlavor/ad8e6f295fe8a584fa8829b2fed12012.js"></script>

Once done your folder should be like this:

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/037.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/037.png" alt="03" width="1334" height="612" class="alignnone size-full wp-image-185" /></a>

<h3>Transpilation and debugging</h3>

Let's edit tsconfig.json a bit to allow debugging via source maps. We want to add these compilerOptions:

<table width="1062">
<tbody>
<tr>
<td width="145"><strong>Option</strong></td>
<td width="879"><strong>Use</strong></td>
<td width="38"></td>
</tr>
<tr>
<td width="145">
<pre>outDir</pre>
</td>
<td width="879">Directory where to store the transpiled JavaScript files</td>
<td width="38"></td>
</tr>
<tr>
<td width="145">
<pre>sourceMap</pre>
</td>
<td width="879"> true  since we want to be able to debug our code in the TypeScript source files directly.</td>
<td width="38"></td>
</tr>
</tbody>
</table>

<script src="https://gist.github.com/MindFlavor/21e724a1354b112bd10e080374b5c773.js"></script>
<p style="text-align: justify">The sourceMap field takes care of that. emitDecoratorMetadata and experimentalDecorators are not strictly needed in our project but are useful and required if you plan to use metadata-heavy frameworks (such as <a href="https://angular.io/">Angular 2</a>).</p>
<p style="text-align: justify">We also tell the TypeScript compiler (tsc) to avoid transpiling the node_modules and the typings module files. Now let's add a dummy app.ts file with this code:</p>
<script src="https://gist.github.com/MindFlavor/6ba8bb9aeb95d4eb247aa86a5276faf7.js"></script>

<h3>Task runner for building the solution</h3>

Now let's ask Visual Studio Code to build our solution. Since we don't have the appropriate configuration (again) we will be asked to create one. Luckily Visual Studio Code does that for us:

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/Ux5bYBhT4a.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/Ux5bYBhT4a.gif" alt="Ux5bYBhT4a" width="1006" height="756" class="alignnone size-full wp-image-175" /></a>

<h3>Debugging</h3>

Last step is to debug our code. Press F5 in Visual Studio Code and - again - we will be asked to create a configuration file. We pick Node.Js as runtime. Remember we must change the configuration because we have created a typescript file and we use source maps.

<table width="1024">
<tbody>
<tr>
<td width="145"><strong>Option</strong></td>
<td width="879"><strong>Use</strong></td>
</tr>
<tr>
<td width="145">
<pre>program</pre>
</td>
<td width="879">Main ts file to start</td>
</tr>
<tr>
<td width="145">
<pre>sourceMaps</pre>
</td>
<td width="879"> true since we want to be able to debug our code in the TypeScript source files directly.</td>
</tr>
<tr>
<td width="145">
<pre>outDir</pre>
</td>
<td width="879">Where our transpiled files are stored (in our case, the dist folder).</td>
</tr>
</tbody>
</table>

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/3H6fUfAbAT.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/3H6fUfAbAT.gif" alt="3H6fUfAbAT" width="1008" height="759" class="alignnone size-full wp-image-165" /></a>

We should also check if the breakpoints are working correctly. Just add a breakpoint in our  ts  file and  Start Debugging:

<a href="https://msdnshared.blob.core.windows.net/media/2016/07/VL0wlsVBWN.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/VL0wlsVBWN.gif" alt="VL0wlsVBWN" width="1006" height="758" class="alignnone size-full wp-image-157" /></a>

You will be able to inspect the running process regardless of the transpilation and see the variables as usual.

<h3>Install required packages</h3>

For out project we will use three open source packages using npm. Let's add them:

<script src="https://gist.github.com/MindFlavor/dcd17add1ae972655e7af302b85caa56.js"></script>
<p style="text-align: justify">Also install the typings in order to exploit TypeScript's strong type checking:</p>
<script src="https://gist.github.com/MindFlavor/76f80eb625455b7a87625ed3e91a52a8.js"></script>

<h3>.gitignore</h3>

The --save flag tells npm to store the package information in our package.json file. The same applies with typings and the typings.json file. This is useful because in order to get all the dependencies again all we have to do is issue npm install (or typings install). In general you don't want to ship the external packages with your code. The user will install the dependencies upon download/clone. To avoid checking in the downloaded packages, we will add the node_modules folder to our .gitignore file. My final .gitignore is like this:

<script src="https://gist.github.com/MindFlavor/abcb846ab7074426c0a5e1ed8a41ff4e.js"></script>
<p style="text-align: justify">I've also excluded the output folder of the transpilation (dist), the typings folder and the .vscode specific folder.</p>

<h3>Create a dummy program</h3>
<p style="text-align: justify">Let's create a dummy program to test that everything is in place. We will create a web server that responds to the URL /sp_who sending back the result of the stored procedure as JSON:</p>
<script src="https://gist.github.com/MindFlavor/d3a6d67e353e6cfffcc5577269aa019e.js"></script>
<p style="text-align: justify">The result will be browsable from http://localhost:3000/spwho:</p>
<a href="https://msdnshared.blob.core.windows.net/media/2016/07/HpTjvGFnlm.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/HpTjvGFnlm.gif" alt="HpTjvGFnlm" width="1176" height="813" class="alignnone size-full wp-image-225" /></a>
<h3>Hide noisy folders from Visual Studio Code</h3>
<p style="text-align: justify">Our <em>solution</em> is cluttered with many noisy folders. We have the  node_modules , the  typings  folders which are automatically handled by npm and typings, respectively. We do not need to concern with them so we want to hide them from the Visual Studio Code folder view. All we have to do is to add the  "files.exclude"  property to the workspace settings:</p>
<p style="text-align: justify">This will leave less clutter in the Visual Studio Code folder tree allowing you to focus on your code.</p>
<a href="https://msdnshared.blob.core.windows.net/media/2016/07/LHnrjPYB9N.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/07/LHnrjPYB9N.gif" alt="LHnrjPYB9N" width="1166" height="757" class="alignnone size-full wp-image-215" /></a>
<h2>Moving on</h2>
Right now we have:
<ul>
 	<li>A functional, unauthenticated web server serving static pages.</li>
 	<li>A functional, unauthenticated web server serving REST verbs in JSON.</li>
 	<li>A way to interact with SQL Server.</li>
 	<li>We are able to debug step by step in our TypeScript source code, directly in Visual Studio Code.</li>
</ul>
<p style="text-align: justify">All we have to do is to render the data graphically. We need to serve some static JavaScript that will interact with our REST API service. We will use AJAX for that. However, this is the topic of the following blog post (<a href="http://bit.ly/bcts2">http://bit.ly/bcts2</a>).</p>
<strong>Happy coding</strong>

<a href="mailto:francesco.cogno@outlook.com">Francesco Cogno</a>]]></content:encoded>
    </item>
    <item>
      <title>Spark and Zeppelin BI using Azure HDInsight with OpenData Lombardia datasets</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/spark-and-zeppelin-bi-using-azure-hdinsight-with-opendata-lombardia-datasets</link>
      <pubDate>Wed, 23 Mar 2016 12:31:34 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/?p=123</guid>
      <description><![CDATA[Intro
In the previous blog post (Azure Data Lake BI sample using Open Data Lombardia) we've shown...]]></description>
      <content:encoded><![CDATA[<div>
<h1>Intro</h1>
In the previous blog post (<a href="https://blogs.msdn.microsoft.com/frcogno/2016/03/07/azure-data-lake-bi-sample-using-arpa-lombardia-dataset/" target="_blank">Azure Data Lake BI sample using Open Data Lombardia</a>) we've shown how easy is to perform analytics using Microsoft Data Lake and U-SQL. An alternative to that is to use the Apache Spark engine (<a href="http://spark.apache.org/" target="_blank">http://spark.apache.org/</a>) on top of an HDInsight cluster. Spark on HDInsight is at the time of writing still in preview but usable for testing purposes nonetheless. It also comes with Zeppelin installed (see <a href="http://zeppelin.incubator.apache.org/" target="_blank">http://zeppelin.incubator.apache.org/</a> for further details) which is a powerful notebook capable of interrogating and rendering our data.
<h2>Spark</h2>
Spark is a yarn aware engine built using Scala programming language. Scala itself is a JVM compatible functional and object oriented programming language (see <a href="http://www.scala-lang.org/" target="_blank">http://www.scala-lang.org/</a>). Functional programming is increasingly gaining traction because CPU speeds are not growing as they did few years ago. The solution is increasing the <em>number</em> of CPU (dual-core, quad-core and so on) forcing the developers to think in terms of threads, processes or even servers (as in the case of Hadoop clusters). Functional programming languages, based on the premise of <em>data immutability</em>, handle concurrency problems very well leading to elegant programs that scale horizontally across cores, processes or even machines. Scala, for instance, has Akka actors (<a href="http://akka.io/" target="_blank">http://akka.io/</a>) for this purpose but many other languages and frameworks are available. For example there are <a href="http://fsharp.org/" target="_blank">F#</a>, <a href="https://clojure.org/" target="_blank">Clojure</a> and <a href="https://www.haskell.org/" target="_blank">Haskell</a> (just to name a few). Spark allows your Scala program to be executed on a Yarn cluster that runs in parallel on multiple machines. Since the data is immutable in functional programs Spark gives you the Resilient Distributed Dataset (aka RDD) which is a cached dataset with the ability to <em>regenerate</em> itself. In other words the RDDs can give you the speed of cached data <strong>and</strong> the ability to recover from failures (which in Hadoop clusters is common).
Let's see it in action.
<h2>HDInsight</h2>
Normally provisioning an Hadoop cluster with Scala, Spark and Zeppelin is a long and error prone task. There are precompiled versions but you have to fiddle with dependencies, configuration files, ssh keys and so on. Luckily with Azure this boils down to a few click in the UI <img class="emoji" title=":smile:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f604.png" alt=":smile:" width="20" height="20" align="absmiddle" />.

Just provision an HDInsight cluster and take care to pick <em>Spark</em> as cluster type:

<a href="https://camo.githubusercontent.com/a3b29d8b2298a2ed1fea27257b2ecc7801e0c5c1/687474703a2f2f692e696d6775722e636f6d2f615346694f75782e706e67" target="_blank"><img src="https://camo.githubusercontent.com/a3b29d8b2298a2ed1fea27257b2ecc7801e0c5c1/687474703a2f2f692e696d6775722e636f6d2f615346694f75782e706e67" alt="" /></a>

As usual you have to configure the Data Source and the Credentials:

<a href="https://camo.githubusercontent.com/c46a2ce11c4377b7412dfebf4376f9ef2f6c134a/687474703a2f2f692e696d6775722e636f6d2f7350666945676e2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/c46a2ce11c4377b7412dfebf4376f9ef2f6c134a/687474703a2f2f692e696d6775722e636f6d2f7350666945676e2e706e67" alt="" /></a>

<em>Note</em>: at the moment of writing you won't find Zeppelin in ubuntu-based HDInsight clusters, only in Windows ones so pick accordingly.
<h3>File upload</h3>
You can upload your datasets in many ways. For the sake of this demo I'll be using the Azure PowerShell cmdlet<code>Set-AzureStorageBlobContent</code> like this:

<a href="https://camo.githubusercontent.com/c04b673068b07a8586ab6dcfa61ce1c2bc9518d4/687474703a2f2f692e696d6775722e636f6d2f43625146356c502e706e67" target="_blank"><img src="https://camo.githubusercontent.com/c04b673068b07a8586ab6dcfa61ce1c2bc9518d4/687474703a2f2f692e696d6775722e636f6d2f43625146356c502e706e67" alt="" /></a>

Alternatively you can use Azure Data Lake storage for your datasets.
<h2>Zeppelin</h2>
Once the datasets are upload to Zeppelin notebook we can connect to Zeppelin and start processing them. Zeppelin exposes the implicit<code>SparkContext</code> as the <code>sc</code> variable (more on SparkContext here <a href="http://spark.apache.org/docs/latest/programming-guide.html" target="_blank">http://spark.apache.org/docs/latest/programming-guide.html</a>).
The SparkContext allows us to interact with the Yarn cluster and issue Spark statements (and of course Scala ones). Let's load our file.
<h3>CSV load</h3>
This is simply done by this command:

<script src="https://gist.github.com/MindFlavor/f5aad85ac8d7d147bde6.js"></script>

Where <code>wasb</code> is the URI for Windows Azure Storage Blob.

In order to inspect our file we can use the <code>take n</code> function that will return the first n rows in our file. We can for example print them to our Zeppelin output like this:

<script src="https://gist.github.com/MindFlavor/84905ea25890b7833b04.js"></script>

This is equivalent this more elegant version:

<script src="https://gist.github.com/MindFlavor/8dec4fe77603f184fef3.js"></script>

The output will be like this one:

<script src="https://gist.github.com/MindFlavor/81578038d60f6cf3a041.js"></script>

<a href="https://camo.githubusercontent.com/d4558970c3a99a9dd5b21b30bcf403208a05fbf7/687474703a2f2f692e696d6775722e636f6d2f30784f466632722e706e67" target="_blank"><img src="https://camo.githubusercontent.com/d4558970c3a99a9dd5b21b30bcf403208a05fbf7/687474703a2f2f692e696d6775722e636f6d2f30784f466632722e706e67" alt="" /></a>

As we can see our file has a nice header on top. We want to filter it so let's assign to a constant first and then let's create a <em>dependent</em> dataset without the header:

<script src="https://gist.github.com/MindFlavor/98d92a1858558650bc4f.js"></script>

<a href="https://camo.githubusercontent.com/b9cb05603dd9dec5497ba145454f3689fd85f1f2/687474703a2f2f692e696d6775722e636f6d2f7a444c333974512e706e67" target="_blank"><img src="https://camo.githubusercontent.com/b9cb05603dd9dec5497ba145454f3689fd85f1f2/687474703a2f2f692e696d6775722e636f6d2f7a444c333974512e706e67" alt="" /></a>

<h3>From CSV to case class</h3>

In Spark you generally map your CSV to a <code>case class</code>. This is useful because it gives you the chance to perform type mapping. As we have seen from the previous image we have:

<ol>
	<li>SensorId</li>
	<li>An event time</li>
	<li>Some kind of float value</li>
	<li>A status constant</li>
</ol>

The date field is can be handled in many ways. For this example I'm going to map using a SparkSQL function called <code>to_utc_timestamp</code> (see <a href="https://github.com/apache/spark/blob/master/sql/core/src/test/scala/org/apache/spark/sql/DateFunctionsSuite.scala" target="_blank">DateFunctionsSuite.scala</a>). This function expects a DataFrame - which we don't currently have. Let's create it:

<script src="https://gist.github.com/MindFlavor/254ac05abe5594277514.js"></script>

This code simply defines a case class with the required fields, maps our CSV to the fields and then registers the temporary table in SparkSQL with the name of <code>EventSQL</code>. Notice we did not convert the date time field but we did an in-place conversion for the float field.

Now that we have a temp table (our DataFrame) we can create <em>views</em> on it. We do so in order to convert our DataTime string field to a more usable one:

<script src="https://gist.github.com/MindFlavor/c968a83a0bc057ae025c.js"></script>

This two rows create a new table called Events. We can inspect it directly in Zeppelin by telling it we want to perform a SparkSQL query. In order to do so all we have to do is start the paragraph with the <code>%sql</code> placeholder.

<a href="https://camo.githubusercontent.com/fcb8eec7a959e6db501d8a08a702b58b3cf9f96f/687474703a2f2f692e696d6775722e636f6d2f67703475466b652e706e67" target="_blank"><img src="https://camo.githubusercontent.com/fcb8eec7a959e6db501d8a08a702b58b3cf9f96f/687474703a2f2f692e696d6775722e636f6d2f67703475466b652e706e67" alt="" /></a>

<h3>Graphs in Zeppelin</h3>

Zeppelin can represent your data graphically. It also gives you powerful BI tools. Let's start with something simple:

<script src="https://gist.github.com/MindFlavor/172241a492759ce030f5.js"></script>

<a href="https://camo.githubusercontent.com/43c27a90070ec552043b36d9fe62535774ae6e21/687474703a2f2f692e696d6775722e636f6d2f4f5a536b676e7a2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/43c27a90070ec552043b36d9fe62535774ae6e21/687474703a2f2f692e696d6775722e636f6d2f4f5a536b676e7a2e706e67" alt="" /></a>

Neat. Notice we can inject parameters in our query (the <code>$(ParameterName=DefaultValue)</code> part). Zeppelin will show text boxes allowing our users to customize the query without touching the SQL. This is something very similar of what you can achieve in SQL Server Reporting Services.

Of course the SensorID field not descriptive. We need to join the dimension file to give our dataset more meaning.

<h3>Dimension file</h3>

Creating the dimension table is straightforward. The drill is the same: load the file, split by comma and map the fields to a case class.

<script src="https://gist.github.com/MindFlavor/fcb0cfb4ac23d0e7c93a.js"></script>

<a href="https://camo.githubusercontent.com/2ca60fb5fdb65abb135dab81bf54be148d4ff14c/687474703a2f2f692e696d6775722e636f6d2f3151797a665a472e706e67" target="_blank"><img src="https://camo.githubusercontent.com/2ca60fb5fdb65abb135dab81bf54be148d4ff14c/687474703a2f2f692e696d6775722e636f6d2f3151797a665a472e706e67" alt="" /></a>

This step is a little verbose because we handle the variable column CSV. We first define a function, <code>someOrNull</code>, returning an <code>Option[String]</code>. That means our function can return a <code>String</code> but also return nothing. The <code>Option[T]</code> pattern is an elegant way to express the possibility of not receiving data back from the function. It replaces the conventional <code>null</code> (and the misleading <code>empty string</code>) without exposing your code to nasty <em>NullPointerExceptions</em>.
Notice also we cached the array. Spark being a lazy language will not perform the operation right away but will cache the first execution instead. We will see later in the execution plan how the cached dataset appears.
<h2>BI</h2>
Now we can answer some interesting questions. For example what was the temperature in Milan - Lambrate during 2015, October 10th?

<script src="https://gist.github.com/MindFlavor/cd045c5d55bab10260d6.js"></script>

<a href="https://camo.githubusercontent.com/ea639bf5e2d911d37b546254f10346d1cbda2672/687474703a2f2f692e696d6775722e636f6d2f75656c6e77566b2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/ea639bf5e2d911d37b546254f10346d1cbda2672/687474703a2f2f692e696d6775722e636f6d2f75656c6e77566b2e706e67" alt="" /></a>

Notice how Zeppelin allows us to customize the graph right into the notebook. By selecting the keys and values we get the nice timeline shown above.
<h3>Stacked bars</h3>
Zeppelin has many interesting graph options. We can, for example, show the temperature from two different sensors side-by-side during Christmas:

<script src="https://gist.github.com/MindFlavor/fbbd45bd312b6a419c24.js"></script>

<a href="https://camo.githubusercontent.com/51cdb9dca2f573643afbb11f50380755d55339f2/687474703a2f2f692e696d6775722e636f6d2f7030756e6f795a2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/51cdb9dca2f573643afbb11f50380755d55339f2/687474703a2f2f692e696d6775722e636f6d2f7030756e6f795a2e706e67" alt="" /></a>

This graph tells us Lambrate was generally colder than Via Feltre except in the early afternoon.

Let's compare two different cities:

<script src="https://gist.github.com/MindFlavor/af0b0903c8276d15409f.js"></script>

<a href="https://camo.githubusercontent.com/8c3f32b0c8186f0f8df3085c6c600bf3907c08d6/687474703a2f2f692e696d6775722e636f6d2f3049596b6161532e706e67" target="_blank"><img src="https://camo.githubusercontent.com/8c3f32b0c8186f0f8df3085c6c600bf3907c08d6/687474703a2f2f692e696d6775722e636f6d2f3049596b6161532e706e67" alt="" /></a>

Edolo is noticeably colder. It's to be expected since it's over 750 mt above the sea level. It's interesting how in the evening the two temperatures seem to match though.
Now let's find the location with the biggest thermal excursion in our dataset.

<script src="https://gist.github.com/MindFlavor/80eb32b08701559245da.js"></script>

<a href="https://camo.githubusercontent.com/558cee34e93596c09a3442533fa76b1d0225db6c/687474703a2f2f692e696d6775722e636f6d2f704e69667a31312e706e67" target="_blank"><img src="https://camo.githubusercontent.com/558cee34e93596c09a3442533fa76b1d0225db6c/687474703a2f2f692e696d6775722e636f6d2f704e69667a31312e706e67" alt="" /></a>

What about the biggest thermal excursion during a day? A simple group by will do the trick.

<script src="https://gist.github.com/MindFlavor/c096476bbd7dac53d8d0.js"></script>

<a href="https://camo.githubusercontent.com/911a74ad520b1e0f615fe92ca32f5f204e780dd9/687474703a2f2f692e696d6775722e636f6d2f413872494537732e706e67" target="_blank"><img src="https://camo.githubusercontent.com/911a74ad520b1e0f615fe92ca32f5f204e780dd9/687474703a2f2f692e696d6775722e636f6d2f413872494537732e706e67" alt="" /></a>

Let's plot the first 2 cities (ignoring the different day):


<script src="https://gist.github.com/MindFlavor/9c8b0816543abcdc0fdf.js"></script>

<a href="https://camo.githubusercontent.com/7b743b5e46ff799a119db1840ea48d3350815172/687474703a2f2f692e696d6775722e636f6d2f6854784a6e51442e706e67" target="_blank"><img src="https://camo.githubusercontent.com/7b743b5e46ff799a119db1840ea48d3350815172/687474703a2f2f692e696d6775722e636f6d2f6854784a6e51442e706e67" alt="" /></a>

From this graph it's clear we have spurious data (unless we can accept a sudden temperature drop of more than 20 degrees celsius) so our graphical representation has shown a problem we could have overlooked just by looking at raw data.
<h3>Execution plan</h3>
Behind the curtain our SparkSQL query - along with all its prerequisites - is converted to an execution plan. Yarn shows it for us we want it to. For example, the "biggest thermal excursion during a day" query has this execution plan:

<a href="https://camo.githubusercontent.com/cc51eb58a0b73c20ada50f1cc313e5d8602fa5d0/687474703a2f2f692e696d6775722e636f6d2f41636b4675346d2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/cc51eb58a0b73c20ada50f1cc313e5d8602fa5d0/687474703a2f2f692e696d6775722e636f6d2f41636b4675346d2e706e67" alt="" /></a>

Or, in more SQL-like terms:

<a href="https://camo.githubusercontent.com/b5cd270558e475a7beece575667a68c076244e39/687474703a2f2f692e696d6775722e636f6d2f644442617238342e706e67" target="_blank"><img src="https://camo.githubusercontent.com/b5cd270558e475a7beece575667a68c076244e39/687474703a2f2f692e696d6775722e636f6d2f644442617238342e706e67" alt="" /></a>

Notice the first execution plan has a <em>green</em> dot. This represents the <em>Existing RDD</em> in the second plan. The Existing RDD is the cached version of an RDD. Think about it as a materialized view. Of course since we are in a distributed world, the cached RDD is distributed also. And since the RDD is able to rebuild itself upon need, a change in the HDInsight cluster topology - either due to a failure or an external event - does not invalidate the whole plan. Only the nodes without cached RDD will rebuild their copy.

<strong>Happy coding</strong>,
<a href="mailto:francesco.cogno@outlook.com" target="_blank">Francesco Cogno</a> and <a href="mailto:" target="_blank">Simone Greci</a>

</div>
&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>Azure Data Lake BI sample using Open Data Lombardia</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/azure-data-lake-bi-sample-using-arpa-lombardia-dataset</link>
      <pubDate>Mon, 07 Mar 2016 11:53:56 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/?p=101</guid>
      <description><![CDATA[Azure Data Lake storage and Analytics compose the brand new Big Data solution provided by Microsoft....]]></description>
      <content:encoded><![CDATA[Azure Data Lake storage and Analytics compose the brand new Big Data solution provided by Microsoft. These services are fully managed (PaaS) services built on top of Hadoop, Yarn and many other Apache technologies. This diagram shows the high-level architecture:

<a href="https://camo.githubusercontent.com/23be90440d5c23f7c1b42f0226b2a0850c8f209b/68747470733a2f2f61636f6d2e617a757265636f6d63646e2e6e65742f3830433537442f63646e2f6376742d383264623635633861386662653131343461326363373831633738353466643662363933616334656437663335393839326365333665346137336337353333352f696d616765732f706167652f736f6c7574696f6e732f646174612d6c616b652f646174612d6c616b652d6469616772616d2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/23be90440d5c23f7c1b42f0226b2a0850c8f209b/68747470733a2f2f61636f6d2e617a757265636f6d63646e2e6e65742f3830433537442f63646e2f6376742d383264623635633861386662653131343461326363373831633738353466643662363933616334656437663335393839326365333665346137336337353333352f696d616765732f706167652f736f6c7574696f6e732f646174612d6c616b652f646174612d6c616b652d6469616772616d2e706e67" alt="https://acom.azurecomcdn.net/80C57D/cdn/cvt-82db65c8a8fbe1144a2cc781c7854fd6b693ac4ed7f359892ce36e4a73c75335/images/page/solutions/data-lake/data-lake-diagram.png" width="600" /></a>.

Unique in this diagram is the U-SQL language. U-SQL is a Microsoft new language. It allows you to interact with semi-structured and structured data with a SQL-like syntax. As with every yarn client the U-SQL tasks can be parallelized easily, achieving unparalleled query speeds. Don't be fooled by SQL part of U-SQL though: underneath everything is C#. This means that you can - <em>if necessary</em> - use the expressiveness of C# to handle your data. This also means your U-SQL scripts will be compiled to native code before execution. Last but not least you can use Visual Studio for the authoring, execution <strong>and</strong> debugging phase.
<h2>Getting started with Azure Data Lake store</h2>
Azure data lake store, once created, is a file system accessible as URL and the new URI scheme <em>adl</em>:

<a href="https://camo.githubusercontent.com/a0cffba50fdbf8303954377de4c50ff682e570ae/687474703a2f2f692e696d6775722e636f6d2f414351714839692e706e67" target="_blank"><img src="https://camo.githubusercontent.com/a0cffba50fdbf8303954377de4c50ff682e570ae/687474703a2f2f692e696d6775722e636f6d2f414351714839692e706e67" alt="" width="600" /></a>

The Azure portal shows the file system like this:

<a href="https://camo.githubusercontent.com/42eb2daaad167a42fd0489c303527c082e11fc8b/687474703a2f2f692e696d6775722e636f6d2f4a6931323743432e706e67" target="_blank"><img src="https://camo.githubusercontent.com/42eb2daaad167a42fd0489c303527c082e11fc8b/687474703a2f2f692e696d6775722e636f6d2f4a6931323743432e706e67" alt="" width="600" /></a>

You can create folders and upload files directly from the portal. Notice that we don't have to specify awkward Hadoop parameters. Everything is handled behind the scenes. PaaS magic.
<h2>Open Data Lombardia</h2>
In order to show you some U-SQL we need a dataset. I choose to use the Open Data Regione Lombardia datasets accessible here: <a href="https://www.dati.lombardia.it/" target="_blank">https://www.dati.lombardia.it/</a>. The site gives access to very interesting datasets, including sensor data. I've downloaded some weather data (stored in a file called <code>sensori_arpa_2015.csv</code>, ~250 MB) and related dimension dataset (called <code>Stazioni_Meteorologiche.csv</code> ~90KB) for this demo. The data is provided under the <strong>Italian Open Data License v2.0 </strong>available here: <a title="http://www.dati.gov.it/iodl/2.0/" href="http://www.dati.gov.it/iodl/2.0/">http://www.dati.gov.it/iodl/2.0/</a>.

To upload the files to Azure Data lake you can use the portal. You can, among other methods, use PowerShell too:
<div class="highlight highlight-source-powershell">
<pre style="padding-left: 30px">AzureRmDataLakeStoreItem <span class="pl-k">-</span>Account <span class="pl-k">&lt;</span>account<span class="pl-k">&gt;</span> <span class="pl-k">-</span>Path <span class="pl-k">&lt;</span>local_path<span class="pl-k">&gt;</span> <span class="pl-k">-</span>Destination <span class="pl-k">&lt;</span>remote_path<span class="pl-k">&gt;</span></pre>
</div>
One cool feature available in the portal is the file preview. Azure tries to interpret your file and, if successful, will show you the tabular data. This is handy because we get to see the columns in our datasets and we can inspect the data type.

<a href="https://camo.githubusercontent.com/6e12145af29e3a93e3b6039f78d7303d7101bb1c/687474703a2f2f692e696d6775722e636f6d2f586c4b566458672e706e67" target="_blank"><img src="https://camo.githubusercontent.com/6e12145af29e3a93e3b6039f78d7303d7101bb1c/687474703a2f2f692e696d6775722e636f6d2f586c4b566458672e706e67" alt="" width="600" /></a>

As you can see, our file comes with the first row as header. While explanatory it does pose a problem while parsing the actual data. At the moment of writing this post there is no way of programmatically skip the header. The feature will come in the future (see <a href="https://feedback.azure.com/forums/327234-data-lake/suggestions/11500386-skip-header-in-extractor" target="_blank">https://feedback.azure.com/forums/327234-data-lake/suggestions/11500386-skip-header-in-extractor</a>). For the time being we just re-upload the files without the header (in a following blog post I'll show you how to handle headers in Spark).
<h2>First job</h2>
Azure Data lake jobs can be authored in the Azure portal directly or using the free Visual Studio extension. I suggest you the latter as it comes with a local simulator (the free Visual Studio extension works on the Visual Studio Community edition, which is also free). Either way we want to perform the simplest possible task: read the data and copy it as it is in another file.

This can be accomplished with this very simple U-SQL script:

<script src="https://gist.github.com/MindFlavor/b7f1be3e7b959f94bf96.js"></script>Here worth noting are:

<ol>
	<li>The Csv and Tsv SerDe. In U-SQL terminology we call them <em>Extractors</em> and <em>Outputters</em>. So we extract from extractors and output to outputters.</li>
	<li>We can specify the data type directly in the extractor. This is great: we don't have to parse the type ourselves as long as its string representation is parsable in the specified type. In case of problems we can instruct Azure Data Lake to either throw an error - which we can debug directly in VS - or to ignore the offending row. Sometimes, especially when munching trillions of rows for statistical analysis, handling a mis-formatted row is simply not worth the effort.</li>
</ol>

We can submit the job and it will give us this trivial execution plan (click on the image to see a larger version):

<a href="https://camo.githubusercontent.com/472ec05d03bb9b1fdf637909ca155556459a4111/687474703a2f2f692e696d6775722e636f6d2f5479344b65416e2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/472ec05d03bb9b1fdf637909ca155556459a4111/687474703a2f2f692e696d6775722e636f6d2f5479344b65416e2e706e67" alt="" width="600" /></a>

This is just an image but if you submit it with Visual Studio you will see the data flowing real-time. Notice that the first operator has read 233 MB (that's unsurprising since the file size if 233 MB) but written 137 MB. This means the data is serialized in a different, more efficient, fashion. We copied 7,2 million rows in our destination file that will be present in Data Lake under the output subfolder (U-SQL jobs create the folders for you as long as you have the rights to do so). 

<h2>Aggregate, enter BI</h2>

One typical task is to count the occurrences of a specific entry (being dollars, tweets, or <em>provolone slices</em>). The SQL syntax makes this super-easy:<script src="https://gist.github.com/MindFlavor/0bb25ffd1f52e9ab570f.js"></script>

Please note we are ordering the resultset in the OUTPUT task and not in the SELECT. Attempting to do so would cause this error:
<p style="padding-left: 30px"><span style="color: #ff0000"><code>An ORDER BY clause used outside of an OUTPUT statement must have a FETCH subclause.</code>. </span></p>
Basically if we sort an intermediate resultset we must limit its cardinality. This makes sense as the sort is a very expensive operation. Of course we can sort the final resultset as done above.

<a href="https://camo.githubusercontent.com/fef64c13d9ac4f6aed399ffad9e2df4780a0db66/687474703a2f2f692e696d6775722e636f6d2f4e446e555444692e706e67" target="_blank"><img src="https://camo.githubusercontent.com/fef64c13d9ac4f6aed399ffad9e2df4780a0db66/687474703a2f2f692e696d6775722e636f6d2f4e446e555444692e706e67" alt="" width="600" /></a>

Notice we have read 233 MB again but this time we have serialized only 28 MB. This is good (great actually) because it means Azure Data lake is pushing the cardinality-minimizing operators down the execution plan (well, up in this case as the execution plan is from top to bottom :)).
<h2>Join to denormalize</h2>
As stated previously there are two datasets. One for the dimensions and the other for the measures. This is common in DWH scenarios but for querying purposes sometimes we have denormalize these two datasets. Fortunately a simple join handles the issue:

<script src="https://gist.github.com/MindFlavor/10b466b5fc6ddf3faf20.js"></script>Note one little thing here. Since the expressions are C# evaluated we must use the double equal sign to check for equality, like this:

<div class="highlight highlight-source-sql">
<pre style="padding-left: 30px"><span class="pl-c1">e</span>.<span class="pl-c1">SensorId</span> <span class="pl-k">==</span> <span class="pl-c1">s</span>.<span class="pl-c1">SensorId</span></pre>

 If we were to specify a single equal sign, as we do in T-SQL, the parser would interpret it as an <em>assignment</em> and the join would error out.
</div>

<a href="https://camo.githubusercontent.com/597fe06ebdc22b71c97a2b32b29ff3429446ee3c/687474703a2f2f692e696d6775722e636f6d2f56514e4e5334542e706e67" target="_blank"><img src="https://camo.githubusercontent.com/597fe06ebdc22b71c97a2b32b29ff3429446ee3c/687474703a2f2f692e696d6775722e636f6d2f56514e4e5334542e706e67" alt="" width="600" /></a>

The execution plan is more interesting. Note that our denormalized data is almost 1 GB. Also note that we are storing the same number of rows read from the event dataset. This is expected since we used a <code>LEFT OUTER JOIN</code>.

<h2>Insight!</h2>

Our dataset is ready to be analysed. We have sensor data and now we know what sensors mean. All we have to do is project this dataset in a meaningful way. Let's answer this business requirement:

<blockquote>
show me the temperature evolution of one specific sensor: the one in Lambrate, Milan.
</blockquote>

<script src="https://gist.github.com/MindFlavor/0be2993f3e0a0fb4d8c7.js"></script>

Here I have read the starting datasets again but we could have used the pre-calculated denormalized one instead.

Once the job completes we can render it using the PowerBI connector in Excel:

<a href="https://camo.githubusercontent.com/207c8c6d2ae9a492529cc87b097b4d8db6524701/687474703a2f2f692e696d6775722e636f6d2f734155595145772e706e67" target="_blank"><img src="https://camo.githubusercontent.com/207c8c6d2ae9a492529cc87b097b4d8db6524701/687474703a2f2f692e696d6775722e636f6d2f734155595145772e706e67" alt="" width="600" /></a>

Not surprisingly, the temperature drops from october to dicember (our whole time span). Also it's interesting to note that in the 2015 the temperature has gone below 0°C only a few days (global warming and such).

The execution plan is this one:

<a href="https://camo.githubusercontent.com/311dc9dcc7e42d418c8347cd693b076098fc57fa/687474703a2f2f692e696d6775722e636f6d2f734b34454c72482e706e67" target="_blank"><img src="https://camo.githubusercontent.com/311dc9dcc7e42d418c8347cd693b076098fc57fa/687474703a2f2f692e696d6775722e636f6d2f734b34454c72482e706e67" alt="" width="600" /></a>
<h2>Going on</h2>
Two other info before closing this long post.
1. The publish to PowerBI feature is coming. With that feature we will be able to generate graphs like the one above directly in the web. Also, the graphs will update <strong>automatically</strong>.
2. Did I mention you can create <strong>tables</strong> in Azure Data Lake? It's very easy and useful if you plan to reuse the data in later jobs. Here is how to store the denormalized data in a table:

<script src="https://gist.github.com/MindFlavor/d5090ed435a79ce29daf.js"></script>

&nbsp;

Rember, the types are C# here, not ANSI-SQL. So in order to specify a nullable column ve must use the <em>question mark </em>C# syntax (see here <a title="https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx" href="https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx">https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx</a> for more details). In short, whenever we see <em>&lt;type&gt;?</em> we should interpret as <em>&lt;type&gt; NULL</em>. Also remember: unless explicitly <em>NULL</em>able, all fields are <em>NOT NULL</em>able!

Happy coding,
<strong>Francesco Cogno</strong>]]></content:encoded>
    </item>
    <item>
      <title>IoT: Send events to Azure Event Hub using Rust</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/iot-send-events-to-azure-event-hub-using-rust</link>
      <pubDate>Mon, 25 Jan 2016 02:58:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/2016/01/25/iot-send-events-to-azure-event-hub-using-rust/</guid>
      <description><![CDATA[IoT: Send events to Azure Event Hub using Rust
Azure Event Hub
Microsoft Azure offers a very...]]></description>
      <content:encoded><![CDATA[<span style="font-family: verdana, geneva"><span style="font-size: 2em">IoT: </span><span style="font-size: 2em">Send events to Azure Event Hub using Rust</span></span>
<h3><span style="font-family: verdana, geneva">Azure Event Hub</span></h3>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Microsoft Azure offers a very appealing IoT service. It's called Event Hubs (<a href="https://azure.microsoft.com/en-us/services/event-hubs/">https://azure.microsoft.com/en-us/services/event-hubs/</a>). Basically it gives you and endpoint in which you can send your events. The events are stored for a retention period and can be retrieved in a FIFO manner by consumers. Each consumer, optionally, can have its own "location" so you can consume your events at different pace. The event hub, therefore, is perfect for the IoT devices as it will unburden them of the <em>store</em> requirement: just collect your data and send it to your event hub for later processing.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">The following image depicts the architecture. As you can see the Event Hub is a declination of the Service Bus Azure service.</span></p>
<span style="font-family: verdana, geneva"><a href="https://camo.githubusercontent.com/90c2c58a6444d1e3ce9735fc68fc0d6f1dfff969/68747470733a2f2f61636f6d2e617a757265636f6d63646e2e6e65742f3830433537442f63646e2f6d6564696168616e646c65722f646f6361727469636c65732f6470736d656469612d70726f642f617a7572652e6d6963726f736f66742e636f6d2f656e2d75732f646f63756d656e746174696f6e2f61727469636c65732f6576656e742d687562732d6f766572766965772f32303135313232333035343731332f69633734313138382e706e67" target="_blank"><img style="margin-left: auto;margin-right: auto" src="https://camo.githubusercontent.com/90c2c58a6444d1e3ce9735fc68fc0d6f1dfff969/68747470733a2f2f61636f6d2e617a757265636f6d63646e2e6e65742f3830433537442f63646e2f6d6564696168616e646c65722f646f6361727469636c65732f6470736d656469612d70726f642f617a7572652e6d6963726f736f66742e636f6d2f656e2d75732f646f63756d656e746174696f6e2f61727469636c65732f6576656e742d687562732d6f766572766965772f32303135313232333035343731332f69633734313138382e706e67" alt="" /></a></span>
<h3><span style="font-family: verdana, geneva">Rust</span></h3>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Rust is a - relatively - new system language that allows you to create fast applications that compile with minimal (or no) runtime. It doesn't have a garbage collector so you don't have the processing hiccups and the memory bloat typical of GCs languages. What makes it so special, compared to C/C++, is a series of features (lifetimes, borrow checker, default immutability and so on) created to ensure thread safety and memory safety. Last but not least the community is great and helpful regardless of your programming skill. You can get everything you need to start programming in Rust from here: <a href="https://www.rust-lang.org">https://www.rust-lang.org/</a> so don't take my word for it and start playing with Rust: it will be a rewarding experience.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Personal considerations aside, you can see how Rust is a good candidate for IoT devices: low processing power and scarce memory are constraints better handled by system languages. There are excellent blog posts on how to cross-compile Rust code to work with various IoT devices so I will not cover that point. There are also many libraries already built enabling you to interact with low level hardware (without having to ASM yourself) so you can start collecting data from your sensors with ease.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">But what about sending it to Azure Event Hub?</span></p>

<h3><span style="font-family: verdana, geneva">REST</span></h3>
<p style="text-align: justify"><span style="font-family: verdana, geneva">As there is no official Azure SDK for Rust yet you might wonder how to access the great functionalities without resorting to external languages (i.e. Python or C#). It turns out the Azure platform exposes most functionalities as REST endpoints. So it's just a matter to post to the right URL. Here is the documentation: <a href="https://msdn.microsoft.com/en-us/library/azure/dn790664.aspx">https://msdn.microsoft.com/en-us/library/azure/dn790664.aspx</a>.</span></p>
<span style="font-family: verdana, geneva">The documentation tells us to POST to <code>https://{serviceNamespace}.servicebus.windows.net/{eventHubPath}/messages</code> with the following header:</span>
<table border="2">
<thead>
<tr>
<th><span style="font-family: verdana, geneva">Request Header</span></th>
<th><span style="font-family: verdana, geneva">Description</span></th>
</tr>
</thead>
<tbody>
<tr>
<td><span style="font-family: verdana, geneva">Authorization</span></td>
<td><span style="font-family: verdana, geneva">SAS token</span></td>
</tr>
</tbody>
</table>
<p style="text-align: justify"><span style="font-family: verdana, geneva">The body will contain the event data.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">With Rust is fairly easy to perform a POST request. For this example I will be using the <a href="https://crates.io/crates/hyper/">Hyper crate</a>. The only difficulty is how to encode the <code>Authorization</code> header: without it Azure will reject our events with 401 Unauthorized. The header requires a SAS token (SAS being <em>Shared Access Signature</em>) in a specific format.</span></p>

<h4><span style="font-family: verdana, geneva">SAS Token</span></h4>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This post helps us to build our SAS token: <a href="https://azure.microsoft.com/en-us/documentation/articles/service-bus-shared-access-signature-authentication/">Shared Access Signature Authentication with Service Bus</a>. Long story short we need to encode the URL and the Expiry attribute with the HMAC SHA256 based on our shared key. The server will perform the same operation (it knows the URL and the expiry attribute because we will pass them in the request) with the same key (shared) and if the result matches it will allow the request.</span></p>
<span style="font-family: verdana, geneva">The following diagram depicts what we should do in detail:</span>
<h1><span style="font-family: verdana, geneva"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/6170.image00.png"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/6170.image00.png" alt="" border="0" /></a></span></h1>
<span style="font-family: verdana, geneva">Let's see how to do it in RUST code.</span>
<h3><span style="font-family: verdana, geneva">RUST's way to Azure Event Hub</span></h3>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Let's start with the transposition of above diagram. Here I will show extracts of the code. You can of course grab the complete project from GitHub (<a href="https://github.com/MindFlavor/pusheventhub">https://github.com/MindFlavor/pusheventhub</a>) and compile try it yourself.</span></p>

<h4><span style="font-family: verdana, geneva">generate_signature</span></h4>
<script src="https://gist.github.com/MindFlavor/f6384bfbc6f4f3074f77.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Here we use a lot of external crates. The code follows closely our diagram. Note that we are using the <code>timestamp</code> method of <code>hrono::datetime::DateTime</code> (<a href="https://lifthrasiir.github.io/rust-chrono/chrono/datetime/struct.DateTime.html">https://lifthrasiir.github.io/rust-chrono/chrono/datetime/struct.DateTime.html</a>) since it will give us exactly what we need: number of non-leap seconds from Jan 1st, 1970. Notice that here, for the sake of simplicity, we are initializing the Hmac each time we call the method. This is far from optimal as we should cache it and just reinitialize it with <code>reset</code>. You should keep that in mind if you plan to write an optimized IoT code.</span>

<h4><span style="font-family: verdana, geneva">submit_event</span></h4>

<span style="font-family: verdana, geneva">Now that we have the correct <code>Authorization</code> header all we need to do is to perform our request using <code>Hyper</code>.</span>

<script src="https://gist.github.com/MindFlavor/529bc2eaccf6e06516e9.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Worth noting here is the <code>event_body</code> parameter: it is a tuple with a Reader and the expected length. You can use a struct here - it would be better - I used the tuple because I'm lazy <img class="emoji" title=":wink:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f609.png" alt=":wink:" width="20" height="20" align="absmiddle" />. Also to note the expected HTTP Result code: 201 (Created). Anything else we treat as failure and send back to the caller in the <code>AzureError</code> enum (not shown here because boring, please refer the <a href="https://github.com/MindFlavor/pusheventhub">GitHub project</a> for it at <a href="https://github.com/MindFlavor/pusheventhub/blob/master/src/azure_error.rs">azure_error.rs</a>).</span></p>

<h3><span style="font-family: verdana, geneva">Conclusion</span></h3>
<p style="text-align: justify"><span style="font-family: verdana, geneva">I hope this will get started with Rust and Azure Event Hub. These two exciting technologies will allow you to start playing with the IoT world with minimum investment. But, hey, now that I've got my device data in the Event Hub what can I do? This is something for another blog post; in the meantime, check out a previous post of mine that explains how to consume Event Hub events, analyse them in a streaming manner using Stream Analytics and to generate intelligence with PowerBI: <a href="http://bit.ly/1A2fQiI">SQL Server intrusion detection using Azure Event Hub, Azure Stream Analytics and PowerBI</a>.</span></p>
<span style="font-family: verdana, geneva"><strong>Happy coding,</strong></span>

<span style="font-family: verdana, geneva"><strong>Francesco Cogno</strong></span>

<!-- This document was created with MarkdownPad, the Markdown editor for Windows (http://markdownpad.com) -->]]></content:encoded>
    </item>
    <item>
      <title>SQL Server 2016 and Azure SQL Database Always Encrypted feature in action</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/sql-server-2016-and-azure-sql-database-always-encrypted-feature-in-action</link>
      <pubDate>Wed, 21 Oct 2015 08:34:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/2015/10/21/sql-server-2016-and-azure-sql-database-always-encrypted-feature-in-action/</guid>
      <description><![CDATA[SQL Server 2016 and Azure SQL database from v12 onwards offer a new security functionality called...]]></description>
      <content:encoded><![CDATA[<p style="text-align: justify"><span style="font-family: verdana, geneva"><span style="font-size: 12px">SQL Server 2016 and Azure SQL database from v12 onwards offer a new security functionality called </span><em style="font-size: 12px">Always encrypted </em><span style="font-size: small">(*SQL Database will support in Preview the feature within the next month)</span><span style="font-size: 12px">. Let's see what it does with a simple example. </span></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Always encrypted feature promises you to protect your data from prying eyes and does that simply by storing the encrypted form only. SQL Server is totally unaware of the plain text data so nobody, not even sysadmins, can read your data. This is good because this separates the duties from sysadmin - who handles the SQL instance - and data admin - who handles the data consistency.</span></p>

<div style="text-align: justify">
<h2><span style="font-family: verdana, geneva">Enhanced ADO.net library</span></h2>
</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">You might wonder: if the data is always encrypted, how can we get the unencrypted form? Must we write the cryptographic code ourselves? </span>
<span style="font-family: verdana, geneva"> The magic here is done by the Enhanced ADO.net library (from .Net 4.6 on). The library will handle the decryption/encryption automagically without special code: we will create our queries without worrying about encryption and the library will take care of everything. We don't even need to be <strong>aware</strong> of encrypted columns since the library discovers them at runtime. </span>
<span style="font-family: verdana, geneva"> Isn't it cool? Let's see it in action.</span></p>

<div style="text-align: justify">
<h2><span style="font-family: verdana, geneva">Sensitive data</span></h2>
</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">For my example we are about to create very simple weight log table:</span></p>
<script src="https://gist.github.com/MindFlavor/004913ca10dd964d12a4.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva"> </span>

<div style="text-align: justify">
<pre><span style="font-family: verdana, geneva"> </span></pre>
</div>

<span style="font-family: verdana, geneva">Selecting the data will give away your dieting efforts:</span>

 <a href="http://i.imgur.com/jy8xCug.png"><img src="http://i.imgur.com/jy8xCug.png" alt="" border="0" /></a>

<span style="font-family: verdana, geneva">Of course we want our data to be kept private so we consider reversible encryption (especially if we are above the recommended weight ;)). Where do we store the certificate? SQL Server has all the necessary tools to support encryption and decryption. The problem is, if we store the encryption certificate in SQL Server any sysadmin can retrieve it and decrypt our data. </span>
<span style="font-family: verdana, geneva"> The solution is to encrypt the data offline and then store it in SQL Server: <a title="https://msdn.microsoft.com/en-us/library/mt163865.aspx" href="https://msdn.microsoft.com/en-us/library/mt163865.aspx">https://msdn.microsoft.com/en-us/library/mt163865.aspx</a>. </span>

<div style="text-align: justify">
<h2><span style="font-family: verdana, geneva">Certificate</span></h2>
</div>

<span style="font-family: verdana, geneva">The first step is to select the encryption certificate. You can use the handy SSMS wizard (note: these screenshots are from SQL Server 2016 CTP 2.4 so are bound to be different from RTM):</span>

 <a href="http://i.imgur.com/r38VKAe.png"><img src="http://i.imgur.com/r38VKAe.png" alt="" border="0" /></a>

<span style="font-family: verdana, geneva">If you don't have a valid certificate you can generate a self-signed one clicking on the specific button.</span>

<span style="font-family: verdana, geneva">This wizard is equivalent to the following T-SQL:</span>

<script src="https://gist.github.com/MindFlavor/2219622a2bde00e55cab.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Of course your thumbprint will be different. Note that we can specify a custom key store provider (more on this here: <a href="https://msdn.microsoft.com/en-us/library/mt147923.aspx">https://msdn.microsoft.com/en-us/library/mt147923.aspx</a>): here we are accepting the windows certificate store. Also note that we are not storing the certificate in SQL Server, we are merely storing its address in the certificate store.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">After we have created the column master key definition we must create the Column encryption key:</span></p>
<p style="text-align: justify"> <a href="http://i.imgur.com/SGVU3Pa.png"><img src="http://i.imgur.com/SGVU3Pa.png" alt="" border="0" /></a></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This will generate something like this:</span></p>
<script src="https://gist.github.com/MindFlavor/ca294196776615e30b3a.js" type="text/javascript"></script>

<div style="text-align: justify">
<h2><span style="font-family: verdana, geneva">Table creation</span></h2>
</div>

<span style="font-family: verdana, geneva">Now that we have everything in place all we need to do is to create the encrypted field table:</span>

<script src="https://gist.github.com/MindFlavor/8d4de93208007e91cc33.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This table is virtually the same as before but here we are specyfing the COLUMN_ENCRYPTION_KEY and the ENCRYPTION_TYPE. COLUMN_ENCRYPTION_KEY specifies the encryption key (so, yes, you can pick a different key for each field) and ENCRYPTION_TYPE specifies whether the encryption will be deterministic or not.</span></p>

<h3 style="text-align: justify"><span style="font-family: verdana, geneva">Deterministic or not?</span></h3>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Deterministic encryption will give the same ciphertext from the same data. </span>
<span style="font-family: verdana, geneva"> So, for example, if we encrypt "<span style="font-family: 'courier new', courier">OliveOil</span>" once and we get the encrypted string "<span style="font-family: 'courier new', courier">Bassaeedd33543aaa</span>" we will <em>always</em> get "<span style="font-family: 'courier new', courier">Bassaeedd33543aaa</span>" for "<span style="font-family: 'courier new', courier">OliveOil</span>". </span>
<span style="font-family: verdana, geneva"> This is good because we can write a query like this: <span style="font-family: 'courier new', courier"><code>SELECT * FROM encTable WHERE food="Bassaeedd33543aaa"</code></span> and benefit from index seeks. It's bad because we could infer from other rows the unencrypted data.</span>
<span style="font-family: verdana, geneva"> So if security is paramount we must use the randomized - ie non-deterministic - encryption and filter our data client-side.</span></p>

<div style="text-align: justify">
<h2><span style="font-family: verdana, geneva">Data insert</span></h2>
</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">We cannot insert rows using SSMS with a simple:</span></p>
<script src="https://gist.github.com/MindFlavor/8e6e40eedf1e964d41d3.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Because we would get this error:</span>

 <a href="http://i.imgur.com/S9yOqdb.png"><img src="http://i.imgur.com/S9yOqdb.png" alt="" border="0" /></a>

<span style="font-family: verdana, geneva">In order to interact with this table we can use the new ADO.net library. The library handles everything on its own provided we add <span style="font-family: 'courier new', courier"><code>Column Encryption Setting=enabled</code></span> to the connection string. Aside from that it's just plain old Ado.net code:</span>

<script src="https://gist.github.com/MindFlavor/679d80112a266170151a.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Some restrictions apply (<a href="https://msdn.microsoft.com/en-us/library/mt163865.aspx">https://msdn.microsoft.com/en-us/library/mt163865.aspx</a>). The most notable is the need to use parametrized queries... but you are not using concatenated tsql anyway, right ;)?</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">As you can see this code is fairly standard: the library will inspect the table (using <span style="font-family: 'courier new', courier;font-size: medium"><code>sys.sp_describe_parameter_encryption</code></span> system SP) and if it finds encrypted fields will look for the relative certificate, encrypt the value in the parameter and send the ciphertext. If you are worried about the performance impact of this operation you might want to fine tune its behaviour using the relevant SqlCommand overload (see <a href="https://msdn.microsoft.com/en-us/library/mt147923.aspx">https://msdn.microsoft.com/en-us/library/mt147923.aspx</a>).</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">The full program code is in this <a href="https://gist.github.com/MindFlavor/0a5302058a19ddc99105">gist</a>. You can clone, compile and execute with:</span>
<span style="font-family: verdana, geneva"> 1. clone with: <span style="font-family: 'courier new', courier;font-size: medium"><code>git clone https://gist.github.com/MindFlavor/0a5302058a19ddc99105</code></span></span>
<span style="font-family: verdana, geneva"> 2. Compile it: <span style="font-family: 'courier new', courier;font-size: medium"><code>csc .a5302058a19ddc99105\Program.cs</code></span></span>
<span style="font-family: verdana, geneva"> 3. Execute it (pass your SQL instance as parameter): <span style="font-family: 'courier new', courier;font-size: medium"><code>Program.exe &lt;your_instance_here&gt;</code></span></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">It will go like this:</span></p>
<p style="text-align: justify"><a href="http://i.imgur.com/0H2t636.png"><img src="http://i.imgur.com/0H2t636.png" alt="" border="0" /></a></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">If you get:</span></p>

<div style="text-align: left"><span style="font-family: 'courier new', courier;font-size: small;color: #ff0000">Failed to decrypt a column encryption key using key store provider: 'MSSQL_CERTIFICATE_STORE'.  The last 10 bytes of the encrypted column encryption key are: '20-53-22-8E-69-67-F1-08-1D-A4'.  Certificate with thumbprint '775FCBC49A4B9240BD51D2AED40BEC07077187A0' not found in certificate store 'My' in certificate location 'CurrentUser'.  Verify the certificate path in the column master key definition in the database is correct, and the certificate has been imported correctly into the certificate location/store. Parameter name: masterKeyPath</span></div>
&nbsp;
<p style="text-align: justify"><span style="font-family: verdana, geneva">it's because you forgot to import the certificate in the local machine's certificate store (or in current user, depending of the configuration). Also note that you need the private key so if you have imported the public key only you will get something like this:</span></p>

<div style="text-align: justify"><span style="font-family: 'courier new', courier;font-size: small;color: #ff0000">Failed to decrypt a column encryption key using key store provider: 'MSSQL_CERTIFICATE_STORE'.  The last 10 bytes of the encrypted column encryption key are: '20-53-22-8E-69-67-F1-08-1D-A4'.  Certificate specified in key path 'CurrentUser/My/775FCBC49A4B9240BD51D2AED40BEC07077187A0' does not have a private key to decrypt a column encryption key.  Verify the certificate is imported correctly. Parameter name: masterKeyPath</span></div>
<div style="text-align: justify">

&nbsp;
<h2><span style="font-family: verdana, geneva">Encrypted data in SQL</span></h2>
</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Are you curious on what a sysadmin will find on SQL Server?</span>
<span style="font-family: verdana, geneva"> Let's try it out:</span></p>
<p style="text-align: justify"><a href="http://i.imgur.com/eOKG60T.png"><img src="http://i.imgur.com/eOKG60T.png" alt="" border="0" /></a></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Now my weight log is safely encrypted. Bear in mind that sysadmin can always modify the data so don't forget to audit the table access. Audit should always complement other security features.</span></p>
<p style="text-align: justify"><strong><span style="font-family: verdana, geneva">Happy coding,</span></strong>
<span style="font-family: verdana, geneva"> <a href="mailto:francesco.cogno@microsoft.com">Francesco Cogno</a></span></p>


<hr />

<script src="https://gist.github.com/MindFlavor/0a5302058a19ddc99105.js" type="text/javascript"></script>]]></content:encoded>
    </item>
    <item>
      <title>Parallel DBCC CheckDB using GOlang</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/parallel-dbcc-checkdb-using-golang</link>
      <pubDate>Tue, 29 Sep 2015 01:15:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/2015/09/29/parallel-dbcc-checkdb-using-golang/</guid>
      <description><![CDATA[Parallel DBCC CheckDB in GOlang
In this post I will show you how to use the concurrent features of...]]></description>
      <content:encoded><![CDATA[<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Parallel DBCC CheckDB in GOlang</strong></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">In this post I will show you how to use the concurrent features of the GO (ie GOlang) language in order to perform some maintenance tasks in parallel. This is just a showcase of features so don't expect a enteprise-ready functionality <img class="emoji" title=":wink:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f609.png" alt=":wink:" width="20" height="20" align="absmiddle" />. The problem we address in this case is the repetitive task of checking our databases for consistency. Internet is full of great quality scripts to address the issue. I will only show an alternative way of doing it as an excuse to show how easy is to reach SQL Server from GO and how to use its excellent concurrent features.</span></p>

<div style="text-align: justify">

<span style="font-family: verdana, geneva"><strong>Setup</strong></span>

</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">First of all, you need to install GO in your environment. Please go here <a href="https://golang.org/">https://golang.org/</a> and install the required binaries. Next you need to set one very important environmental variable called GOPATH: it will store all your source code (well, that's note exactly true but it's enough for here). Select a convenient folder for it (for example C:\dev\go), open the system settings pa<span style="font-family: verdana, geneva">nel and select <em>Advanced system settings</em>:</span></span></p>
 <a href="http://i.imgur.com/YNoceCC.png"><img style="margin-left: auto;margin-right: auto" src="http://i.imgur.com/YNoceCC.png" alt="" border="0" /></a>
<p style="text-align: justify"><span style="font-family: verdana, geneva">From here, click <em>Environmental variables</em>:</span></p>
<a href="http://i.imgur.com/fy1zmWT.png"><img style="margin-left: auto;margin-right: auto" src="http://i.imgur.com/fy1zmWT.png" alt="" border="0" /></a>
<p style="text-align: justify"><span style="font-family: verdana, geneva">And add your GOPATH variable, either to your account (better) or system-wide.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">To check your configuration just open a command prompt and issue <span style="font-family: 'courier new', courier;font-size: small">go version</span>. If everything is ok you should see the version installed</span><span style="font-family: verdana, geneva">:</span></p>
<a style="font-family: verdana, geneva" href="http://i.imgur.com/ic1IxTU.png"><img style="margin-left: auto;margin-right: auto" src="http://i.imgur.com/ic1IxTU.png" alt="" border="0" /></a>

<span style="text-align: justify;font-family: verdana, geneva">Just to check, type also </span><span style="font-family: 'courier new', courier;font-size: small">ECHO %GOPATH%</span><span style="text-align: justify;font-family: verdana, geneva"> you should see your previously selected folder.</span>
<div style="text-align: justify">

<span style="font-family: verdana, geneva"><strong>Querying SQL Server</strong></span>

</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">In order to connect to SQL Server there are many options available. The most straightforward way is to use the ODBC driver, but for the sake of this post we will use the excellent open source implementation by <em>denisenkom</em>. You can find it here: <a href="https://github.com/denisenkom/go-mssqldb">https://github.com/denisenkom/go-mssqldb</a>. Wait, you don't need to clone his repository yourself. All you have to do is issue <span style="font-family: 'courier new', courier;font-size: small">go get "github.com/denisenkom/go-mssqldb"</span> and the go runtime will clone the package for you and install it in your GOPATH folder. </span>
<span style="font-family: verdana, geneva"> GOlang drivers allow you to code without tying yourself to a specific implementation. You can switch to another driver simply changing the driver signature. Please note that Microsoft does not support these open source drivers: you will need to contact the authors for support.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Open connection</strong></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Let's see how it's done:</span></p>
<script src="https://gist.github.com/MindFlavor/99c8ffb106161e984391.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Here the sql package is the standard package <span style="font-family: 'courier new', courier;font-size: small">database/sql</span>. You are telling it to use the <span style="font-size: small;font-family: 'courier new', courier">"mssql"</span> driver which has injected itself simply by anonymous import:</span>

<script src="https://gist.github.com/MindFlavor/4c094c8e0ac191be21c4.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Query preparation</strong></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Once we have a valid connection (ie without err) you must prepare your statement using the Prepare method of the receiver <span style="font-family: 'courier new', courier;font-size: small">*sql.DB</span>:</span></p>
<script src="https://gist.github.com/MindFlavor/7fa8b5c9b31c6e2e442b.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Here we are simply retrieving the database list - projecting only two fields. If we were to specify parameters we would use the ODBC syntax typing a question mark. For example:</span>

<script src="https://gist.github.com/MindFlavor/0713397aa23d7f40e630.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Here the question mark is our parameter. You don't need to specify the contents right now as you will be doing it in the next step.</span>
<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Query execution</strong></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Now we can call the <span style="font-family: 'courier new', courier;font-size: small">Query()</span> method. This method is peculiar because can accept and arbitrary number of parameters. As you might have guessed, these are the query parameters defined before. So in the case of <span style="font-family: 'courier new', courier;font-size: small">SELECT database_id, name FROM sys.databases</span> (no parameters) all we have to do is:</span></p>
<script src="https://gist.github.com/MindFlavor/9591d918eb533cc8ff86.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">To pass a parameter all you have to do is:</span>

<script src="https://gist.github.com/MindFlavor/d4a9611d7187803c068f.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Data retrieval</strong></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This function returns the row collection as first parameter. All we have to do is to enumerate it and extract the data calling the Scan method of <span style="font-family: 'courier new', courier;font-size: small">*sql.Rows</span>:</span></p>
<script src="https://gist.github.com/MindFlavor/d8338e988f52ee8224ac.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">You need to supply to the exact number of fields in the <span style="font-family: 'courier new', courier;font-size: small">Scan</span> method as parameters. If you don't know in advance how many there will be you can look at the <span style="font-family: 'courier new', courier;font-size: small">rows.Columns()</span> getter (see <a title="https://golang.org/pkg/database/sql/#Rows.Columns" href="https://golang.org/pkg/database/sql/#Rows.Columns">https://golang.org/pkg/database/sql/#Rows.Columns</a> for more details) which will give you the fields in the recordset along with their names. In my case I know them in advance so I've prepared a struct to hold them:</span>

<script src="https://gist.github.com/MindFlavor/440a6355f31fe497a3d0.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Note</strong>: <span style="font-family: 'courier new', courier;font-size: small">DBCC CHECKDB WITH TABLERESULTS </span>is undocumented, unsupported and different between SQL Server versions. It's shown here just as an example.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">The <span style="font-family: 'courier new', courier;font-size: small">Scan</span> code becomes:</span></p>
<script src="https://gist.github.com/MindFlavor/76e2ad07b45b75ec4ffb.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Worth noting is the use of strings. GO does not allow <span style="font-family: 'courier new', courier;font-size: small">nil</span> strings. The default string is an empty string. In SQL Server there is a huge differenct between an empty string an <span style="font-family: 'courier new', courier;font-size: small">NULL</span>: you can test it in SQL Server Management Studio executing:</span>

<script src="https://gist.github.com/MindFlavor/084cd3fbf4515742f205.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Which will give you <em>different</em> <img class="emoji" title=":wink:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f609.png" alt=":wink:" width="20" height="20" align="absmiddle" />.</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">So in order to tell this difference you have to pass to <span style="font-family: 'courier new', courier;font-size: small">Scan </span>a <em>pointer to a pointer to a string</em> (that is <span style="font-family: 'courier new', courier;font-size: small">*(*string)</span>) so in case of <span style="font-family: 'courier new', courier;font-size: small">NULL </span>the pointer will point to <span style="font-family: 'courier new', courier;font-size: small">nil</span>, in case of an empty string the pointer will point to "". Don't worry, you cannot forget this because you will get a runtime error if your pass a simple <em>pointer to string</em> (that is <span style="font-family: 'courier new', courier;font-size: small">*string</span>).</span></p>

<div style="text-align: justify">

<span style="font-family: verdana, geneva"><strong>defer</strong></span>

</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">You might have spotted in the previous snippets the <span style="font-family: 'courier new', courier;font-size: small">defer </span>statement. It basically tells the compiler to call your function as soon as the exit of the scope. The defer is smart enough to be LIFO so if you do:</span></p>

<ol>
	<li><span style="font-family: verdana, geneva">open DB</span></li>
	<li><span style="font-family: verdana, geneva">defer close DB</span></li>
	<li><span style="font-family: verdana, geneva">open query</span></li>
	<li><span style="font-family: verdana, geneva">defer close query</span></li>
	<li><span style="font-family: verdana, geneva">open row</span></li>
	<li><span style="font-family: verdana, geneva">defer close row</span></li>
</ol>
<p style="text-align: justify"><span style="font-family: verdana, geneva">You are actually telling this:</span></p>

<ol>
	<li><span style="font-family: verdana, geneva">open DB</span></li>
	<li><span style="font-family: verdana, geneva">open query</span></li>
	<li><span style="font-family: verdana, geneva">open row</span></li>
	<li><span style="font-family: verdana, geneva">close row</span></li>
	<li><span style="font-family: verdana, geneva">close query</span></li>
	<li><span style="font-family: verdana, geneva">close DB</span></li>
</ol>
<p style="text-align: justify"><span style="font-family: verdana, geneva">That is what we want. The defer statement is handy because allows you to logically link the open and close operations without scattering them in your code in reverse order.</span></p>

<div style="text-align: justify">

<span style="font-family: verdana, geneva"><strong>go functions</strong></span>

</div>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This special statement starts a <em>concurrent</em> function. The function can be anything and will be scheduled by the runtime without you having to do it manually. This is excellent for long running blocking operations such as database calls. So suppose we have our long running function; we can do:</span></p>
<script src="https://gist.github.com/MindFlavor/876165f36b71f4b8b940.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Two things happen here. First we are declaring an anonymous function that requires a string parameter called <span style="font-family: 'courier new', courier;font-size: small">connectionString</span>. This function just calls the <span style="font-family: 'courier new', courier;font-size: small">ProcessInstance </span>function so it's very simple. Then we are calling <span style="font-family: 'courier new', courier;font-size: small">go function(connectionString)</span> for each connection string in our slice. Now, depending on the GO configuration, the machine cores and so on the functions will be processed concurrently. But wait, if the functions will go on their own, how can we be informed when they end?</span>
<span style="font-family: verdana, geneva"> There are may ways to do that, we can create <em>mutexes </em>(ok, but hard to maintain), shared objects (don't do that! <img class="emoji" title=":-1:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f44e.png" alt=":-1:" width="20" height="20" align="absmiddle" />) or use <em>channels</em>.</span>

<span style="font-family: verdana, geneva"><strong>GO Channels</strong></span>

<span style="font-family: verdana, geneva">Go channels are a thread safe data sinks. It other words you can send a receive data in different threads (or, better, go functions) without fear of concurrent access.</span>
<span style="font-family: verdana, geneva"> GO channels are blocking so if you try to get an item from an empty channel you will be blocked until it becomes available (you can override this behaviour, of course, but is not needed now). </span>
<span style="font-family: verdana, geneva"> We can ask each go func to put an item in the channel as soon as it is finished. Since we know how many go func we have started we know how many items we must receive.</span>

<script src="https://gist.github.com/MindFlavor/87cfb0ce68c132de735e.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">The <span style="font-family: 'courier new', courier;font-size: small">cEnd := make(chan int)</span> creates the channel (empty). The function will add an item when it's done (the syntax is <span style="font-family: 'courier new', courier;font-size: small">cEnd &lt;- &lt;item&gt;</span>). Notice how the go func can access the channel even if it's declared outside its scope and not passed as parameter. This is possible since this functions are <em>closures</em>. </span>
<span style="font-family: verdana, geneva"> Now from outside we just need to get from the channel a number of items equal the number of <em>go funcs</em> started:</span></p>
<script src="https://gist.github.com/MindFlavor/28d946653344f5a461b8.js" type="text/javascript"></script>

<span style="font-family: verdana, geneva">Since we don't care of what value we get from the channel we just discard it.</span>

<div style="text-align: justify">
<span style="font-family: verdana, geneva"><strong>Putting al together</strong></span>
</div>

<span style="font-family: verdana, geneva">With these notions it's easy to create our parallel check db script. You can get the code from this gist: </span>

<script src="https://gist.github.com/MindFlavor/290cbd4945c9d22b667f.js" type="text/javascript"></script>
<p style="text-align: justify"><span style="font-family: verdana, geneva">What we do is:</span>
<span style="font-family: verdana, geneva"> 1. For each command line parameter start a go func</span>
<span style="font-family: verdana, geneva"> 2. For each go func:</span>
<span style="font-family: verdana, geneva">3. Open the connection</span>
<span style="font-family: verdana, geneva">4. Get the database list</span>
<span style="font-family: verdana, geneva">5. For each database:</span>
<span style="font-family: verdana, geneva">6. Perform DBCC CHECKDB</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This will execute steps 3-6 in parallel (that's what we wanted in the first place).</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">This is a sample execution with 3 servers as parameter:</span></p>
<a href="http://i.imgur.com/JRG8a8j.png"><img style="margin-left: auto;margin-right: auto" src="http://i.imgur.com/JRG8a8j.png" alt="" border="0" /></a>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Notice how the different executions are interleaved. Each server processes the entries without waiting for the others (as expected).</span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva"><strong>Going on</strong></span></p>
<p style="text-align: justify"><span style="font-family: verdana, geneva">Well as you have guessed we still lack the proper interpretation of the CheckDB response. Right now we just tell the user that the CheckDB has started and has completed but we should also tell him if his databases are corrupt or not <img class="emoji" title=":wink:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f609.png" alt=":wink:" width="20" height="20" align="absmiddle" />. I'll leave to you this task with a hint. There are two very useful packages you might want to import: <a href="https://golang.org/pkg/strings/">strings</a> and <a title="regexp" href="https://golang.org/pkg/regexp/">regexp</a>.</span></p>
<p style="text-align: justify"></p>
<p style="text-align: justify"><strong><span style="font-family: verdana, geneva">Happy coding,</span></strong>
<span style="font-family: verdana, geneva"> <a href="mailto:francesco.cogno@microsoft.com">Francesco Cogno</a></span></p>
<p style="text-align: justify"></p>]]></content:encoded>
    </item>
    <item>
      <title>SQL Server intrusion detection using Azure Event Hub, Azure Stream Analytics and PowerBI</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/sql-server-intrusion-detection-using-azure-event-hub-azure-stream-analytics-and-powerbi</link>
      <pubDate>Wed, 13 May 2015 08:51:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/2015/05/13/sql-server-intrusion-detection-using-azure-event-hub-azure-stream-analytics-and-powerbi/</guid>
      <description><![CDATA[Intro
A couple of days ago I was asked this question:

As a DBA, what can Stream Analytics do for...]]></description>
      <content:encoded><![CDATA[<h2 style="text-align: justify"><span style="font-family: verdana,geneva">Intro</span></h2>
<p style="text-align: justify"><span style="font-size: small;font-family: verdana,geneva">A couple of days ago I was asked this question:</span></p>

<blockquote><span style="font-size: small;font-family: verdana,geneva">As a DBA, what can Stream Analytics do for my on-premise SQL Server?</span></blockquote>
<p style="text-align: justify"><span style="font-size: small;font-family: verdana,geneva">The answer is easy to come by: to handle the ERRORLOG. SQL Server has its own <em>streaming</em> log: it's called <code>ERRORLOG</code> (yes, the capitalization is intended) and gives us a cartload of information. DBAs look for it when asked questions like: "what the heck happened? <img class="emoji" title=":smile:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f604.png" alt=":smile:" width="20" height="20" align="absmiddle" />". Since SQL Server 2005 it's also the standard output of the login auditing feature <a href="https://technet.microsoft.com/en-us/library/ms175850.aspx">https://technet.microsoft.com/en-us/library/ms175850.aspx</a>. In a nutshell, SQL Server logs entries like</span></p>

<div style="overflow: scroll;font-size: 8pt">

<span style="font-size: small;font-family: verdana,geneva"><code>2015-05-13 11:15:57.25 Logon Login failed for user 'crack'. Reason: Could not find a login matching the name provided. [CLIENT: &lt;local machine&gt;]</code></span>

</div>
<p style="text-align: justify"><span style="font-size: small;font-family: verdana,geneva">The problem is, in order to detect malicious attacks we should be able to tolerate scattered failures. We don't want to raise an alarm if a users mistypes a password once in a month. In other word, we need to detect failed login attempts in a custom timespan. If we detect, for example, 40 failed logins from a specific IP within 5 minutes we should definitely raise an alarm. Another example is to detect whenever there are 5 failed logins for the same account in 1 minute. For the purpose of this post we will implement the latter example; I'll leave up to you to modify it in order to detect IP-based attacks.</span></p>

<h2 style="text-align: justify"><span style="font-family: verdana,geneva">What we need to do</span></h2>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">We need to:</span></p>

<ol style="text-align: justify">
	<li><span style="font-family: verdana,geneva;font-size: small">Scan the <code>ERRORLOG</code> file and extract login entries.</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Store the entries in a persistent, scalable event store.</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Group those entries using a tumbling window of 1 minute. Pick only the failed logins and group them by login name.</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Identify the entries whose count is greater than 5.</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Create a dynamic dashboard to show the alert.</span></li>
</ol>
<h2 style="text-align: justify"><span style="font-family: verdana,geneva">Azure to the rescue</span></h2>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Luckily most tasks are addressed by a specific Azure feature. We will use, respectively:</span></p>

<ol style="text-align: justify">
	<li><span style="font-family: verdana,geneva;font-size: small">Some custom C# code (will show in a bit).</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Azure Event Hub (<a href="http://azure.microsoft.com/en-us/services/event-hubs/">http://azure.microsoft.com/en-us/services/event-hubs/</a>).</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Azure Stream Analytics (<a href="http://azure.microsoft.com/en-us/services/stream-analytics/">http://azure.microsoft.com/en-us/services/stream-analytics/</a>).</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">Azure Stream Analytics.</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">PowerBI (<a href="https://powerbi.microsoft.com/">https://powerbi.microsoft.com/</a>).</span></li>
</ol>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">So what we'll end up having is:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/db40cd6da131ee647fc7b19be1c50c4436805a64/687474703a2f2f692e696d6775722e636f6d2f6a73326c474a462e706e67" target="_blank"><img src="https://camo.githubusercontent.com/db40cd6da131ee647fc7b19be1c50c4436805a64/687474703a2f2f692e696d6775722e636f6d2f6a73326c474a462e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Let's start creating the event hub collector.</span></p>

<h3 style="text-align: justify"><span style="font-family: verdana,geneva">Event hub</span></h3>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Create the event hub using the New... button in the <a href="https://manage.windowsazure.com">Azure portal</a>:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/65de99d929991c68d7284a72ee1e70180d791c61/687474703a2f2f692e696d6775722e636f6d2f76386b6d5168412e706e67" target="_blank"><img src="https://camo.githubusercontent.com/65de99d929991c68d7284a72ee1e70180d791c61/687474703a2f2f692e696d6775722e636f6d2f76386b6d5168412e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Make sure to create a consumer group for your event hub:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/515583351b89086a098937e7e6c12f4bdb7092e9/687474703a2f2f692e696d6775722e636f6d2f785850346668492e706e67" target="_blank"><img src="https://camo.githubusercontent.com/515583351b89086a098937e7e6c12f4bdb7092e9/687474703a2f2f692e696d6775722e636f6d2f785850346668492e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Create the event hub policy (it will allow our client to send data):</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/8043726d5cf22467d98d9ff87ad600014430705d/687474703a2f2f692e696d6775722e636f6d2f714241334977302e706e67" target="_blank"><img src="https://camo.githubusercontent.com/8043726d5cf22467d98d9ff87ad600014430705d/687474703a2f2f692e696d6775722e636f6d2f714241334977302e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">The dashboard should now contain the connection string. Copy it for later.</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/bb688e4573333c88eb29e87966fcb00378df3b6a/687474703a2f2f692e696d6775722e636f6d2f4b57305543544a2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/bb688e4573333c88eb29e87966fcb00378df3b6a/687474703a2f2f692e696d6775722e636f6d2f4b57305543544a2e706e67" alt="" /></a></span></p>

<h3 style="text-align: justify"><span style="font-family: verdana,geneva">C# code</span></h3>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">I will not dwell long here on the ERRORLOG scanner code. You can get it from github here <a href="https://github.com/MindFlavor/StreamFromErrorlog">https://github.com/MindFlavor/StreamFromErrorlog</a>. In order for it to work on your environment make sure to configure the <code>App.config</code> file.</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">I will only highlight how to connect to Event Hub.</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">First you need an instance of <a href="https://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.eventhubclient.aspx">EventHubClient</a> class:</span></p>

<div class="highlight highlight-c#">
<pre><span style="font-family: verdana,geneva">_eventHub = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);</span></pre>
</div>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Here the <code>connectionString</code> is the one you got from the Azure portal before. The <code>eventHubName</code> is, well, the event hub name <img class="emoji" title=":smirk:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f60f.png" alt=":smirk:" width="20" height="20" align="absmiddle" /> .</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Now to send an event you just have to call the <code>Send</code> method. I've picked JSON as message format:</span></p>

<div style="overflow: scroll;font-size: 8pt">
<pre><span style="color: #800000;font-weight: bold">string</span> ser <span style="color: #808030">=</span> JsonConvert<span style="color: #808030">.</span>SerializeObject<span style="color: #808030">(</span>le<span style="color: #808030">)</span><span style="color: #800080">;</span>

EventData ed <span style="color: #808030">=</span> <span style="color: #800000;font-weight: bold">new</span> EventData<span style="color: #808030">(</span>Encoding<span style="color: #808030">.</span>UTF8<span style="color: #808030">.</span>GetBytes<span style="color: #808030">(</span>ser<span style="color: #808030">)</span><span style="color: #808030">)</span>
<span style="color: #800080">{</span>
    PartitionKey <span style="color: #808030">=</span> le<span style="color: #808030">.</span>Client
<span style="color: #800080">}</span><span style="color: #800080">;</span>
</pre>
</div>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Very easy. In case you're wondering, the <code>PartitionKey</code> is just a way to spread your messages in different partitions. The Azure framework will dynamically change the partitioning function based of the number of available partitions.</span></p>

<h3 style="text-align: justify"><span style="font-family: verdana,geneva">Stream Analytics</span></h3>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Now get back to the portal and create a new Stream Analytic job:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/6b0f56a4b820c5f9207c08f3eccbf4482c815975/687474703a2f2f692e696d6775722e636f6d2f48766c7577744c2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/6b0f56a4b820c5f9207c08f3eccbf4482c815975/687474703a2f2f692e696d6775722e636f6d2f48766c7577744c2e706e67" alt="" /></a></span></p>

<h3 style="text-align: justify"><span style="font-family: verdana,geneva">Input</span></h3>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Now add your event hub input:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/dcfcaa974974738df00ff91137fe693963cb5fb1/687474703a2f2f692e696d6775722e636f6d2f57735548676d522e706e67" target="_blank"><img src="https://camo.githubusercontent.com/dcfcaa974974738df00ff91137fe693963cb5fb1/687474703a2f2f692e696d6775722e636f6d2f57735548676d522e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">You can download some sample data if you want to check it. Make sure to grab some as it will help during the query design phase:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/13c6afa6873a02b9c867dac31149de21628dc56c/687474703a2f2f692e696d6775722e636f6d2f6e56617731354d2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/13c6afa6873a02b9c867dac31149de21628dc56c/687474703a2f2f692e696d6775722e636f6d2f6e56617731354d2e706e67" alt="" /></a></span></p>

<h4 style="text-align: justify"><span style="font-family: verdana,geneva">Query</span></h4>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Remember we wanted to find the failed logins attempt on the same username in a 5 minute timespan. We just have to use the <a href="https://msdn.microsoft.com/en-us/library/azure/dn835055.aspx">Tumbling Window</a> function like this:</span></p>

<div style="overflow: scroll;font-size: 8pt">
<pre><span style="color: #800000;font-weight: bold">SELECT</span>
    <span style="color: #800000;font-weight: bold">System</span><span style="color: #808030">.</span><span style="color: #800000;font-weight: bold">Timestamp</span> <span style="color: #800000;font-weight: bold">as</span> WindowEnd<span style="color: #808030">,</span>
    login<span style="color: #808030">,</span> <span style="color: #bb7977;font-weight: bold">COUNT</span><span style="color: #808030">(</span><span style="color: #808030">*</span><span style="color: #808030">)</span>
<span style="color: #800000;font-weight: bold">INTO</span>
    <span style="color: #808030">[</span>elpowerbi<span style="color: #808030">]</span>
<span style="color: #800000;font-weight: bold">FROM</span>
    <span style="color: #808030">[</span>errorloginput<span style="color: #808030">]</span>
<span style="color: #800000;font-weight: bold">TIMESTAMP</span> <span style="color: #800000;font-weight: bold">BY</span> 
    EventTime
<span style="color: #800000;font-weight: bold">WHERE</span>
    <span style="color: #808030">[</span>failed<span style="color: #808030">]</span> <span style="color: #808030">=</span> <span style="color: #008c00">1</span>
<span style="color: #800000;font-weight: bold">GROUP</span> <span style="color: #800000;font-weight: bold">BY</span> TUMBLINGWINDOW<span style="color: #808030">(</span>mi<span style="color: #808030">,</span> <span style="color: #008c00">5</span><span style="color: #808030">)</span><span style="color: #808030">,</span> login
<span style="color: #800000;font-weight: bold">HAVING</span> <span style="color: #bb7977;font-weight: bold">COUNT</span><span style="color: #808030">(</span><span style="color: #808030">*</span><span style="color: #808030">)</span> <span style="color: #808030">&gt;</span> <span style="color: #008c00">3</span>
</pre>
</div>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Make sure to specify in the <code>FROM</code> clause the input name you've chosen in the previous step. The <code>INTO</code> clause must match the output name (we haven't created it yet).</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">If you click <code>Test</code> and supply the sample data you can make sure the query works as expected:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/c546c93f417dda7cc72e7f2820c8a53d5800624b/687474703a2f2f692e696d6775722e636f6d2f445656446d6f5a2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/c546c93f417dda7cc72e7f2820c8a53d5800624b/687474703a2f2f692e696d6775722e636f6d2f445656446d6f5a2e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">As you can see, in my sample data there are 4 failed attempt to authenticate as username <em>crack</em>.</span></p>

<h4 style="text-align: justify"><span style="font-family: verdana,geneva">Output</span></h4>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Add now an output and pick PowerBI as destination. Remember to name it as the <code>INTO</code> clause of your query. The dataset name will be the dataset created in PowerBI. <strong>Be warned</strong>: if a dataset with the same name exists in your PowerBI subscription your existing data will be lost.</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/af15c1bff06d7b96405910d1cdd752b0eb2aa147/687474703a2f2f692e696d6775722e636f6d2f3478445537796a2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/af15c1bff06d7b96405910d1cdd752b0eb2aa147/687474703a2f2f692e696d6775722e636f6d2f3478445537796a2e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">When done start your stream analytics job. If everything goes as expected you will see the status of the job going to <em>running</em> (or <em>idle</em> when the data has been processed):</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/2a39288b5e8d08e54b0c61368562d60795949ab6/687474703a2f2f692e696d6775722e636f6d2f414e3650744d4c2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/2a39288b5e8d08e54b0c61368562d60795949ab6/687474703a2f2f692e696d6775722e636f6d2f414e3650744d4c2e706e67" alt="" /></a></span></p>

<h3 style="text-align: justify"><span style="font-family: verdana,geneva">PowerBI</span></h3>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">The last task is to create the dashboard in PowerBI. You will find there the newly created dataset (<em>note</em>: if there's no data there will be no dataset <img class="emoji" title=":smile:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f604.png" alt=":smile:" width="20" height="20" align="absmiddle" />):</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/e2be04e11b2ff2f6cbb610732b29f01089c7b75a/687474703a2f2f692e696d6775722e636f6d2f4e70596d78474e2e706e67" target="_blank"><img src="https://camo.githubusercontent.com/e2be04e11b2ff2f6cbb610732b29f01089c7b75a/687474703a2f2f692e696d6775722e636f6d2f4e70596d78474e2e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Click on it and create some graphical representation of your liking. In my case I've created this dashboard:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/0adfc829cc0fdc33e96acca4f9d8a106bd559124/687474703a2f2f692e696d6775722e636f6d2f455573323156572e706e67" target="_blank"><img src="https://camo.githubusercontent.com/0adfc829cc0fdc33e96acca4f9d8a106bd559124/687474703a2f2f692e696d6775722e636f6d2f455573323156572e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Here I can clearly see that I had three different account failing to authenticate: <em>crack</em>, <em>kkk</em> and <em>NT AUTHORITY\SYSTEM</em>. This is just what we wanted. But! More magic! <strong>The PowerBI dashboard is completely automatic</strong>! In few moments the graphs updated themselves into this:</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva"><a href="https://camo.githubusercontent.com/83f715603d48b4eaaa3bc7ed7b3f681f9ef5b813/687474703a2f2f692e696d6775722e636f6d2f4c6b49485643322e706e67" target="_blank"><img src="https://camo.githubusercontent.com/83f715603d48b4eaaa3bc7ed7b3f681f9ef5b813/687474703a2f2f692e696d6775722e636f6d2f4c6b49485643322e706e67" alt="" /></a></span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">I can see in a glance that:</span></p>

<ul style="text-align: justify">
	<li><span style="font-family: verdana,geneva;font-size: small">The <em>kkk</em> failed logins stopped happening. Since it happened just a few times I can infer it was a simply human error.</span></li>
	<li><span style="font-family: verdana,geneva;font-size: small">The <em>crack</em> failed logins keep happening at the same rate. This smells as machine generated and could be a brute force attack indeed <img class="emoji" title=":thumbsup:" src="https://assets-cdn.github.com/images/icons/emoji/unicode/1f44d.png" alt=":thumbsup:" width="20" height="20" align="absmiddle" />!.</span></li>
</ul>
<h2 style="text-align: justify"><span style="font-family: verdana,geneva">Conclusion</span></h2>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">This is just a sample but you can grasp the power of this solution. With just a simple query you can extract streaming information and visualize it with a dynamic dashboard. You can collect all your SQL Servers logs in the event hub and create an enterprise wide dashboard (with drill down, too). The events will shape themselves and animate your dashboard without <span style="text-decoration: underline">having to write a single line of code</span>.</span></p>
<p style="text-align: justify"><span style="font-family: verdana,geneva;font-size: small">Azure magic!</span></p>
<span style="font-family: verdana,geneva;font-size: small"><strong>Happy coding</strong>,</span>
<span style="font-family: verdana,geneva;font-size: small"> <a href="mailto:francesco.cogno@microsoft.com">Francesco Cogno</a></span>]]></content:encoded>
    </item>
    <item>
      <title>HandsOn - SQL Database Row-Level Security</title>
      <link>https://docs.microsoft.com/archive/blogs/frcogno/handson-sql-database-row-level-security</link>
      <pubDate>Fri, 30 Jan 2015 07:20:00 GMT</pubDate>
      <dc:creator><![CDATA[Francesco Cogno]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/frcogno/2015/01/30/handson-sql-database-row-level-security/</guid>
      <description><![CDATA[Few days ago we released, in preview, a new cool feature for SQL Database: row-level security. This...]]></description>
      <content:encoded><![CDATA[<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Few days ago we released, in preview, a new cool feature for SQL Database: row-level security. This feature opens new security patterns, particularly coupled with the upcoming data obfuscation feature. In this post I’ll show you how to get started with a viable pattern; for more details please refer to the <a title="Row-Level Security Preview" href="https://msdn.microsoft.com/library/7221fa4e-ca4a-4d5c-9f93-1b8a4af7b9e8.aspx">Row-Level Security Preview</a> page on MSDN.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">First and foremost, remember this is just a preview feature so it could change in the future.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Now, what is row-level security? Basically it’s an application transparent custom row filter.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">In other words you now have the power to decide which row to show right after it has been fetched from a table. </span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Let me show you an example. You have a table with 5 rows, as shown below:</span></p>
&nbsp;
<p align="center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/4530.sampletable2.jpg"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/4530.sampletable2.jpg" alt="" border="0" /></a></span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Up until now, depending of your permission set, you are either query the table or you don’t. In other words, the recordset composition is entirely dependent of the search predicate. Since we don’t have WHERE arguments all the rows are returned. Using row-level security we can choose which row to return adding a custom filter to every query performed against our table. So, for our example, we could filter the “private” rows returning only the public rows:</span></p>
<p style="text-align: center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1460.sampletable_filter2.jpg"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1460.sampletable_filter2.jpg" alt="" border="0" /></a></span></p>
<p style="text-align: center"></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">The other rows are still in the database, they're just filtered.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">All you have to do is provide SQL Database with a function SQL will call for each row fetched from the table. If your function returns a value SQL will not filter the row. If your function returns an empty recordset the row will be filtered out.</span></p>
<p style="text-align: center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/2744.draw1.jpg"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/2744.draw1.jpg" alt="" border="0" /></a></span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Simple isn't it?</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">In truth you have to perform two steps. Beside our filter function you have to tell SQL Database which table to filter. This is accomplished with a new statement: <a href="https://msdn.microsoft.com/library/dn765135.aspx">CREATE SECURITY POLICY</a>. Given that security policy, SQL is able to call your function for each access to the specific table automatically.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Here <a href="https://msdn.microsoft.com/library/7221fa4e-ca4a-4d5c-9f93-1b8a4af7b9e8.aspx">https://msdn.microsoft.com/library/7221fa4e-ca4a-4d5c-9f93-1b8a4af7b9e8.aspx</a> you can find some simple examples to get started.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Note however some important details: these filters <span style="text-decoration: underline">are in query phase only</span>. There is nothing preventing you to insert rows you would not be able to query afterwards.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">From now on I'll use another, more realistic, example (full source code is available here: <a title="https://gist.github.com/MindFlavor/61bf05e357cddbeffb02" href="https://gist.github.com/MindFlavor/61bf05e357cddbeffb02">https://gist.github.com/MindFlavor/61bf05e357cddbeffb02</a>). </span><span style="font-family: tahoma, arial, helvetica, sans-serif;font-size: small">Suppose we have a table with sensitive information. Each row has a clearance level needed to retrieve it. Your users have a specific clearance level. You want to let each user retrieve only the rows he’s allowed to.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">So we have a table specifying the username and the granted security level (let's call it <em>[Sec].</em><em>[securitylevel]</em>):</span></p>
<p style="text-align: center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1007.tbl1.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1007.tbl1.png" alt="" border="0" /></a></span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">(here GrantedLevel specifies the “<em>security clearance</em>” for the user). And a table like this:</span></p>
<p style="text-align: center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/8322.tbl2.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/8322.tbl2.png" alt="" border="0" /></a></span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">(Here RequiredLevel is the minimum “<em>security clearance</em>” needed to fetch the row).</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">We have to create our custom function. Note that it <span style="text-decoration: underline">must be an inline table value function</span>. You cannot use multi statement table value functions here. This is good performance-wise. Our function should receive the required clearance level in input and, checking the current user, tell SQL if it should return the row examined.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">This is easy. All we have to do is to query our <em>[Sec].[securitylevel]  </em>table to see if the currently context user has the required security level:</span></p>
 <span style="color: blue">CREATE</span><span style="font-family: 'Courier New';font-size: 12pt"> </span><span style="color: blue">FUNCTION</span><span style="font-family: 'Courier New';font-size: 12pt"> </span><span style="color: maroon">[Sec]</span><span style="color: silver">.</span><span style="color: #ff0080"><strong>[Fn_testsecuritylevel]</strong></span><span style="color: maroon">(</span><span style="color: #8000ff">@RequiredSecurityLevel</span><span style="font-family: 'Courier New';font-size: 12pt"> </span><span style="color: blue">AS</span><span style="font-family: 'Courier New';font-size: 12pt"> </span><span style="color: black"><em>INT</em></span><span style="color: maroon">)</span>
<div style="overflow: scroll;font-size: 12pt"><span style="font-family: 'Courier New'"><span style="font-family: 'Courier New'"><span style="color: maroon">returns</span> <span style="color: blue">TABLE</span>
<span style="color: blue">WITH</span> <span style="color: maroon">schemabinding</span>
<span style="color: blue">AS</span>
<span style="color: blue">RETURN</span>
<span style="color: blue">SELECT</span> <span style="color: black">1</span> <span style="color: blue">AS</span> <span style="color: red">'Result'</span>
<span style="color: blue">FROM</span>   <span style="color: maroon">[Sec]</span><span style="color: silver">.</span><span style="color: maroon">[securitylevel]</span>
<span style="color: blue">WHERE</span>  <span style="color: maroon">(</span> <span style="color: maroon">[username]</span> <span style="color: silver">=</span> <span style="color: fuchsia"><em>User_name</em></span><span style="color: maroon">(</span><span style="color: maroon">)</span>
<span style="color: blue">AND</span> <span style="color: #8000ff">@RequiredSecurityLevel</span> <span style="color: silver">&lt;</span> <span style="color: maroon">[grantedlevel]</span> <span style="color: maroon">)</span>
<span style="color: blue">OR</span> <span style="color: maroon">(</span> <span style="color: fuchsia"><em>User_name</em></span><span style="color: maroon">(</span><span style="color: maroon">)</span> <span style="color: silver">=</span> <span style="color: red">'dbo'</span> <span style="color: maroon">)</span><span style="color: silver">;</span></span></span><span style="color: maroon">go</span>

</div>
<span style="font-family: tahoma, arial, helvetica, sans-serif;font-size: small">It’s good practice to allow unrestricted access to <em>dbo</em>: it would have it anyway and it will only cause confusion (and don’t tell me your application relies on <em>dbo</em>! ;)). </span>

<span style="font-family: tahoma, arial, helvetica, sans-serif;font-size: small;text-align: justify">With the function in place all we have to do is to create the SECURITY POLICY:</span>
<div style="overflow: scroll;font-size: 12pt"><span style="font-family: 'Courier New'"> CREATE <span style="color: maroon">security</span> <span style="color: maroon">policy</span> <span style="color: maroon">[Sec]</span><span style="color: silver">.</span><span style="color: maroon">[PrivilegeBasedTableFilter]</span> <span style="color: blue">ADD</span> <span style="color: maroon">filter</span> <span style="color: maroon">predicate</span> <span style="color: maroon">[Sec]</span><span style="color: silver">.</span><span style="color: maroon">[fn_testSecurityLevel]</span><span style="color: maroon">(</span><span style="color: maroon">requiredlevel</span><span style="color: maroon">)</span> <span style="color: blue">ON</span> <span style="color: maroon">[Sec]</span><span style="color: silver">.</span><span style="color: maroon">[PrivilegeBasedTable]</span> <span style="color: blue">WITH</span> <span style="color: maroon">(</span><span style="color: maroon">state</span> <span style="color: silver">=</span> <span style="color: blue">ON</span><span style="color: maroon">)</span><span style="color: silver">;</span> </span></div>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Note how we linked the function to our table. Also note that the function will receive the RequiredLevel field for each row to evaluate. Think about it as an implicit CROSS APPLY function.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">If we query the table (as <em>dbo</em>):</span></p>
<span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/8561.select%20dbo.png"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/8561.select%20dbo.png" alt="" border="0" /></a></span>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">We receive 10 rows, 1 for each security clearance.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Now look at the execution plan: instead of a simple clustered index scan we find:</span><span style="text-align: center"> </span></p>
<p style="text-align: center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/5582.plan_simple.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/5582.plan_simple.png" alt="" border="0" /></a></span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">The join operator is our inline function predicate:</span></p>
<span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/3286.plan_join.png"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/3286.plan_join.png" alt="" border="0" /></a></span>
<p style="text-align: justify"><span style="font-family: tahoma, arial, helvetica, sans-serif;font-size: small">So you can clearly see how SQL Database injected our filtering function in the statement above.</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Now if we were to create 3 users:</span></p>

<ol style="text-align: justify">
	<li><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">VIP user with clearance level 10.</span></li>
	<li><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">AverageGuy with clearance level 5.</span></li>
	<li><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">PowerlessGuy with clearance level 1.</span></li>
</ol>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">We could test our filtering function just changing execution context. For example PowerlessGuy will only see 1 row:</span></p>
<p style="text-align: center"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1373.powerless.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1373.powerless.png" alt="" border="0" /></a></span></p>
<p style="text-align: justify"></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">While AverageGuy will get 5 rows. Note how <em>COUNT</em> works consistently:</span></p>
<span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1185.average.png"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1185.average.png" alt="" border="0" /></a></span>
<p style="text-align: justify"> <span style="font-family: tahoma, arial, helvetica, sans-serif;font-size: small">Moreover, since SQL injects our filtering function down in the execution tree, join expressions get filtered too as expected:</span></p>
<span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/3058.join_res.png"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/3058.join_res.png" alt="" border="0" /></a> </span>
<p style="text-align: justify"></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">With this execution plan:</span></p>
<span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"> <a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1300.join_plan.png"><img style="margin-left: auto;margin-right: auto" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/68/05/1300.join_plan.png" alt="" border="0" /></a></span>
<p style="text-align: justify"></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif">Happy coding,</span></p>
<p style="text-align: justify"><span style="font-size: small;font-family: tahoma, arial, helvetica, sans-serif"><strong><a title="Francesco Cogno" href="mailto:francesco.cogno@microsoft.com">Francesco Cogno</a></strong></span></p>
&nbsp;

<script src="https://gist.github.com/MindFlavor/61bf05e357cddbeffb02.js" type="text/javascript"></script>]]></content:encoded>
    </item>
  </channel>
</rss>