<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>AlexPeta.ro</title><link>http://www.alexpeta.ro</link><description>Welcome to AlexPeta.ro , the online home of Alex Peta : programmer, bodybuilder , web enthusiast.</description><lastBuildDate>7/16/2015</lastBuildDate><language>en-us</language><generator>Alex Peta Blog 2.0</generator><managingEditor>alex@alexpeta.ro</managingEditor><webMaster>alex@alexpeta.ro</webMaster><item><title>Vintage, Fashion and Non Recursive Hierarchical SQL Queries</title><link>http://www.alexpeta.ro/article/vintage,-fashion-and-non-recursive-hierarchical-sql-queries/</link><description>&lt;p&gt;First of all , glad to say : &lt;font size="6"&gt;I’m back!!!&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Want to start off with 2 things really quickly before I begin with the topic : &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;been &lt;strong&gt;extremely&lt;/strong&gt; busy the last couple of months and will detail what I’ve been doing in a later blog post. 
&lt;li&gt;I’ve upgraded the blog comment system to use Disqus.&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;Now to begin our topic.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Fashion&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;I’ve been assigned about a week ago to work on a really old nasty project , .NET 2.0 ASP Classic if you want to know the details, and my job was to upgrade and make it IE10 compatible.&amp;nbsp; I’m going to spare you the agony of reading the implementation details (hacks) and we agree not to speak about it. :-). I’m going to be fair here, this isn’t a job I was looking forward to.&lt;/p&gt;
&lt;p&gt;And it all has to do with &lt;em&gt;Fashion&lt;/em&gt;. That’s right. If you didn’t see by now, programmers are fashionable people when it comes to writing code. We are superficial, we care a lot about the looks! Also like in fashion, we follow and start trends, we gather at presentations and see how others write code and when it comes to “modeling”, coding is the place where you see them all :-)&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Vintage&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;But unlike the fashion industry, besides all the resemblances, we have one thing that we don’t agree on&amp;nbsp; : vintage. Fashion says its cool, we say its old and smells. &lt;/p&gt;
&lt;p&gt;Vintage will never be a trend in programming. &lt;/p&gt;
&lt;p&gt;That’s because we always are interested in the new, the faster, the better technologies. &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Non Recursive Hierarchical SQL Queries&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;And this is how I started struggling with the project to make it work. The more I struggled the more I had to dive deeper and understand what was going on there and with each breakpoint set I was getting closer to something I did not expect……(insert tension / drumroll here)&lt;/p&gt;
&lt;p&gt;The app was showing a report&amp;nbsp; with a lot of rows based on a tree class and I was curious to see how the tree was populated so when I saw the implementation I felt like discovering a piece of gold inside a piece of &lt;strike&gt;crap &lt;/strike&gt;dirt. &lt;/p&gt;
&lt;p&gt;Here is our example hierarchy :&amp;nbsp; a simple basket that has fruits and vegetables in it.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://alexpeta.ro/Content/Images/hierarchy.png"&gt;&lt;img src="http://alexpeta.ro/Content/Images/hierarchy.png" title="hierarchy" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="hierarchy" src="$hierarchy5.png" width="592" height="271"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The result that we want to achieve is to get a sub tree from this large tree as quickly as possible and not recursively. &lt;/p&gt;
&lt;p&gt;The answer : pre-compute the data before inserting it into a different representation then the “parentId” foreign key usual representation. &lt;/p&gt;
&lt;p&gt;Now its time to “mark” all the nodes by doing a “Depth-first” search in the tree by adding 2 values for each node:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;left side index – meaning start point 
&lt;li&gt;right side index – meaning leaving point&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Here is the tree after it has been marked:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://alexpeta.ro/Content/Images/marked_hierarchy.png"&gt;&lt;img src="http://alexpeta.ro/Content/Images/marked_hierarchy.png" title="marked_hierarchy" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="marked_hierarchy" src="$marked_hierarchy5.png" width="582" height="275"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Let’s see how our end result table will look like with the data inserted from the marked tree:&lt;/p&gt;
&lt;table cellspacing="0" cellpadding="2" width="637" border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td valign="top" width="179"&gt;Name&lt;/td&gt;
&lt;td valign="top" width="198"&gt;LeftIndex&lt;/td&gt;
&lt;td valign="top" width="258"&gt;RightIndex&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="181"&gt;Basket&lt;/td&gt;
&lt;td valign="top" width="198"&gt;1&lt;/td&gt;
&lt;td valign="top" width="258"&gt;16&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Fruits&lt;/td&gt;
&lt;td valign="top" width="198"&gt;2&lt;/td&gt;
&lt;td valign="top" width="258"&gt;9&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Apple&lt;/td&gt;
&lt;td valign="top" width="198"&gt;3&lt;/td&gt;
&lt;td valign="top" width="258"&gt;4&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Cherry&lt;/td&gt;
&lt;td valign="top" width="198"&gt;5&lt;/td&gt;
&lt;td valign="top" width="258"&gt;6&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Banana&lt;/td&gt;
&lt;td valign="top" width="198"&gt;7&lt;/td&gt;
&lt;td valign="top" width="258"&gt;8&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Veggies&lt;/td&gt;
&lt;td valign="top" width="198"&gt;10&lt;/td&gt;
&lt;td valign="top" width="258"&gt;15&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Tomato&lt;/td&gt;
&lt;td valign="top" width="198"&gt;11&lt;/td&gt;
&lt;td valign="top" width="258"&gt;12&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" width="182"&gt;Onion&lt;/td&gt;
&lt;td valign="top" width="198"&gt;13&lt;/td&gt;
&lt;td valign="top" width="258"&gt;14&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Now lets see some queries in action :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Get all the fruits sub-tree: &lt;/li&gt;&lt;/ul&gt;&lt;pre class="prettyprint"&gt;SELECT LeftIndex as start, RightIndex as end FROM table where Name = “Fruits”
&lt;/pre&gt;&lt;pre class="prettyprint"&gt;SELECT * FROM table WHERE LeftIndex &amp;gt; start AND RightIndex&amp;nbsp; &amp;lt; end
&lt;/pre&gt;
&lt;p&gt;First I am getting the startIndex (left) and endIndex(right) for the subtree that&amp;nbsp; I want to retrieve and then I am doing the actual query just by comparing values that are in my expected interval.&lt;/p&gt;
&lt;p&gt;And we can continue like this to get all the sub-trees that we want, you got the big picture.&lt;/p&gt;
&lt;p&gt;Now lets write some code that will represent our tree in C#. We will need a node first of all :&lt;/p&gt;&lt;pre class="prettyprint"&gt;&lt;p&gt;namespace NonRecursiveHierarchicalSQLQueries.DataStructures.Concrete&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class Node&amp;lt;T&amp;gt; &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; where T : INode&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #region Properties&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public int LeftIndex { get; set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public int RightIndex { get; set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public T Value { get; private set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public List&amp;lt;Node&amp;lt;T&amp;gt;&amp;gt; Children { get; private set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #endregion Properties&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #region Constructors&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public Node(T nodeValue)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.Value = nodeValue;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Children = new List&amp;lt;Node&amp;lt;T&amp;gt;&amp;gt;();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #endregion Constructors&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #region Public Methods&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public virtual void InsertChild(Node&amp;lt;T&amp;gt; child)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Children.Add(child);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void MarkTree(ref int index)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; LeftIndex = index++;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (var child in this.Children)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; child.MarkTree(ref index);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; RightIndex = index;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void Visit(Action&amp;lt;Node&amp;lt;T&amp;gt;&amp;gt; action)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; action(this);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (var child in Children)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; child.Visit(action);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; #endregion Public Methods&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/p&gt;
&lt;/pre&gt;
&lt;p&gt;This is a quick generic implementation of a tree node. It has a Value property that can be any T where T is an INode and also 2 more numeric properties LeftIndex and StartIndex&amp;nbsp; that we are using to insert in our table columns in the database.&lt;/p&gt;
&lt;p&gt;I’ve also create a Mark method that is the method to call when marking each node and setting the left and right indexes.&lt;/p&gt;
&lt;p&gt;And finally we have a Visit method that accepts a action with the current node and passes this action recursively to its “children” – this is to offer different flexible actions to do on the tree.&lt;/p&gt;
&lt;p&gt;Now lets use this generic node to create a concrete implementation :&lt;/p&gt;&lt;pre class="prettyprint"&gt;&lt;p&gt;public class MyDataHolder : INode&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public string Name { get; private set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public MyDataHolder(string name)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Name = name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/p&gt;
&lt;p&gt;public class SimpleTreeNode : Node&amp;lt;MyDataHolder&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public SimpleTreeNode(MyDataHolder value) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; : base(value)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;br&gt;&lt;/p&gt;
&lt;/pre&gt;
&lt;p&gt;After we got our concrete implementations, its time to create a tree and mark it and check if our Depth-first implementation works ok.&lt;/p&gt;&lt;pre class="prettyprint"&gt;&lt;p&gt;class Program&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main(string[] args)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //Creating the tree&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode root = new SimpleTreeNode(new MyDataHolder("Basket"));&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode fruitsNode = new SimpleTreeNode(new MyDataHolder("Fruits"));&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode appleNode = new SimpleTreeNode(new MyDataHolder("Apple"));&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode cherryNode = new SimpleTreeNode(new MyDataHolder("Cherry"));&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode bananaNode = new SimpleTreeNode(new MyDataHolder("Banana"));&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fruitsNode.InsertChild(appleNode);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fruitsNode.InsertChild(cherryNode);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fruitsNode.InsertChild(bananaNode);&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; root.InsertChild(fruitsNode);&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode veggies = new SimpleTreeNode(new MyDataHolder("Veggies"));&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode tomato = new SimpleTreeNode(new MyDataHolder("Tomato"));&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; SimpleTreeNode onion = new SimpleTreeNode(new MyDataHolder("Onion"));&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; veggies.InsertChild(tomato);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; veggies.InsertChild(onion);&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; root.InsertChild(veggies);&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //mark the tree left and right indexes&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int start = 0;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; root.MarkTree(ref start);&lt;/p&gt;
&lt;p&gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //create a visit action delegate that will print to console&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //because the visit allows us to add any action delegate here&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; //this is the place where we could create an action that inserts in our database.&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Action&amp;lt;Node&amp;lt;MyDataHolder&amp;gt;&amp;gt; consoleWriteAction = (node) =&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine("{0}\tl={1} r={2}", node.Value.Name, node.LeftIndex, node.RightIndex);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; root.Visit(consoleWriteAction);&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.ReadLine();&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/p&gt;
&lt;/pre&gt;
&lt;p&gt;You can probably tell that instead of my consoleWriteAction I could have easily used a action to insert the values in the database and this would be exactly what we were looking for.&lt;/p&gt;
&lt;p&gt;Of course this isn’t optimized in any way. We could eventually make a “IsDirty” property for each node so that we can insert/update only the necessary nodes not all at once etc.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Conclusion&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Working with legacy code is ugly and undesirable. No product manager/client would ever spend one development hour on refactoring. The logic that they use all the time is : “so we have the same functionality but better, what’s in it for me?”. &lt;/p&gt;
&lt;p&gt;..BUT sometimes it is worth it! really seldom, you come across pieces of code like this and see that great/smart code has been done even in the early days of building apps.&lt;/p&gt;
&lt;p&gt;&lt;font size="4"&gt;&lt;strong&gt;Note&lt;/strong&gt;&amp;nbsp;&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;Be sure to check out all the code here back over on Github : &lt;a href="https://github.com/alexpeta/Blog/tree/master/NonRecursiveHierarchicalSQLQueries"&gt;https://github.com/alexpeta/Blog/tree/master/NonRecursiveHierarchicalSQLQueries&lt;/a&gt;&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/vintage,-fashion-and-non-recursive-hierarchical-sql-queries/</guid></item><item><title>Localizing your Views in ASP MVC</title><link>http://www.alexpeta.ro/article/localizing-your-views-in-asp-mvc/</link><description>&lt;p&gt;Today at work I had to do an interesting thing to do : localize all the views in a controller. There is a legacy app that was build in classic ASP with each .aspx file having its own translations as resources and my task here was to migrate this to ASP MVC.&lt;/p&gt;
&lt;p&gt;The following pic illustrates my project structure.&lt;/p&gt;&lt;img style="border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-top-width: 0px" align="center" src="http://www.alexpeta.ro/Content/images/resourcemanagermvc.png"&gt; 
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The particular thing to notice here is that the resource file names are exactly like the view names. So my job here was that each time an Action method was called, I had to create a ResourceManager class that would initialize with the appropriate resource file based on the routed action name, and provide translations.&lt;/p&gt;
&lt;p&gt;First I created a ResourceManger singleton:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="prettyprint"&gt; public sealed class ResourceManagerHelper
  {
    #region Private Members
    private static ResourceManager mInstance = new ResourceManager(Constants.NamespaceEnum.CResourcesDefaultNamespace, typeof(ResourceManagerHelper).Assembly);
    private static readonly object mSyncLock = new object();
    #endregion Private Members

    #region Constructors
    private ResourceManagerHelper()
    {
    }
    static ResourceManagerHelper()
    {
    }
    #endregion Constructors

    #region Public Methods
    public static ResourceManager GetResourceManagerInstance([CallerMemberNameAttribute] string resourceName = null)
    {
      lock (mSyncLock)
      {
        if (!string.IsNullOrWhiteSpace(resourceName))
        {
          mInstance = new ResourceManager(string.Format("{0}{1}",Constants.NamespaceEnum.CResourcesPartialNamespace, resourceName), typeof(ResourceManagerHelper).Assembly);
        }
        else
        {
          mInstance = new ResourceManager(Constants.NamespaceEnum.CResourcesDefaultNamespace, typeof(ResourceManagerHelper).Assembly);
        }

        return mInstance;
      }
    }
    #endregion Public Methods

  }
&lt;/pre&gt;
&lt;p&gt;The interesing bit here is the GetResourceManagerInstance() method that accepts the resource file name passes it to the ResourceManager constructor.&lt;/p&gt;
&lt;p&gt;Another trick that is available in .NET 4.5 is the [CallerMemberNameAttribute] parameter attribute that returns the calling method name (I think behind the scenes its done by reflection) – I added this in case I would call this method directly in the ActionResult body and to add more flexibily.&lt;/p&gt;
&lt;p&gt;Next I started work on a wrapper class around the default controller class. This is the place that I will all the stuff that my views need to have access to, and this will serve as the base controller for all my pages – the ResourceManager and other stuff&lt;/p&gt;&lt;pre class="prettyprint"&gt; public class MVCBaseController : Controller
  {
    #region Private Members
    private ResourceManager mResourceManager;
    private IUnitOfWork mUnitOfWork;
    #endregion Private Members
    
    #region Protected Properties
    protected ResourceManager ResourceManager
    {
      get { return mResourceManager; }
      set { mResourceManager = value; }
    }
    protected IUnitOfWork UnitOfWork
    {
      get { return mUnitOfWork; }
      set { mUnitOfWork = value; }
    }
    #endregion Protected Properties

    #region Constructors
    /// &lt;summary&gt;
    /// constructor injection for UnitOfWork implementation
    /// &lt;/summary&gt;
    public MVCBaseController()
      : this(new UnitOfWork())
    {
    }
    public MVCBaseController(IUnitOfWork unitOfWork)
    {
      UnitOfWork = unitOfWork;
    }
    #endregion Constructors

    #region Overrides
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
      base.Initialize(requestContext);
      InitializeResourceManager();
    }
    #endregion Overrides

    #region Private Methods
    /// &lt;summary&gt;
    /// Method that initializes the resource manager based on the RouteData action method
    /// to get the appropriate resource for the currenct action view.
    /// &lt;/summary&gt;
    private void InitializeResourceManager()
    {
      string callingMemberName = string.Empty;
      if (RouteData != null &amp;amp;&amp;amp; RouteData.Values != null)
      {
        var routeValue = this.RouteData.Values["action"];
        if (routeValue != null)
        {
          callingMemberName = routeValue.ToString();
        }
      }
      ResourceManager = Helpers.ResourceManagerHelper.GetResourceManagerInstance(callingMemberName);
    }
    #endregion Private Methods
  }
&lt;/pre&gt;
&lt;p&gt;The things to highlight here the override Initialize() method. This is the method after which , the "&lt;strong&gt;RouteData&lt;/strong&gt;” property of each controller is initialized, so if I wanted the first place that I would be able to access RouteData for the current request to know which ActionMethod / View was called by user, this is the place to search. So Im overriding the default implementation, and right after the base implementation is called Im calling my InitializeResourceManager method that looks up the “Action” name in the RouteData dictionary and then initializes the ResourceManager instance.&lt;/p&gt;
&lt;p&gt;The result is the following :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the user navigates to : /home/index 
&lt;li&gt;Controller base controller is called 
&lt;li&gt;MVCBaseController is called 
&lt;li&gt;the derived Initialize method is called , getting the RouteData and initializing the ResourceManager with the correct namespace 
&lt;li&gt;the public ActionMethod Index() is called now having access to the MVCBaseController class and its ResourceManager with translations&lt;/li&gt;&lt;/ul&gt;</description><guid>http://www.alexpeta.ro/article/localizing-your-views-in-asp-mvc/</guid></item><item><title>Calculating the Distance Between two GPS Coordinates</title><link>http://www.alexpeta.ro/article/calculating-the-distance-between-two-gps-coordinates/</link><description>&lt;p&gt;Although this article is still related to the Windows Phone App series, I think it is stand alone subject.&lt;/p&gt;
&lt;p&gt;Ok, so I had to calculate the distance between 2 GPS positions. &lt;/p&gt;
&lt;p&gt;My first intention was to go with the basic formula that &lt;a href="http://www.purplemath.com/modules/distform.htm" rel="nofollow" target="_blank"&gt;you learn in school.&lt;/a&gt; But it isn’t right. This is ok for a 2D space, not for GPS positions where we have to take in consideration the curvature of the Earth as well.&lt;/p&gt;
&lt;p&gt;After searching the problem a bit,I struck gold &lt;a title="Harvesine Formula" href="http://en.wikipedia.org/wiki/Haversine_formula" rel="nofollow" target="_blank"&gt;The Harvesine Formula&lt;/a&gt; and its implementation : &lt;a title="http://www.movable-type.co.uk/scripts/latlong.html" href="http://www.movable-type.co.uk/scripts/latlong.html"&gt;http://www.movable-type.co.uk/scripts/latlong.html&lt;/a&gt; – this is the best reference with explanations and sample code written in JavaScript. &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;TheHarvesine Formula&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;
&lt;table&gt;
&lt;tbody&gt;
&lt;tr id="haversine"&gt;
&lt;td class="label"&gt;Haversine&lt;br&gt;formula:&lt;/td&gt;
&lt;td class="formula"&gt;a = sin²(?f/2) + cos(f&lt;sub&gt;1&lt;/sub&gt;) * cos(f&lt;sub&gt;2&lt;/sub&gt;) * sin²(??/2)&lt;br&gt;c = 2 * atan2(v&lt;span class="radicand"&gt;a&lt;/span&gt;, v&lt;span class="radicand"&gt;(1-a)&lt;/span&gt;)&lt;br&gt;d = R * c&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td class="label align-right"&gt;where&lt;/td&gt;
&lt;td&gt;&lt;i&gt;f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km)&lt;/i&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&amp;nbsp;&lt;/td&gt;
&lt;td&gt;&lt;i&gt;note that angles need to be in radians to pass to trig functions!&lt;/i&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/p&gt;
&lt;p&gt;All I had to do migrate this in C# and test it out.&lt;/p&gt;
&lt;p&gt;I’m going to this the fancy way around because I have been brainwashed with OOP :)&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;A simple GPSPoint strunct that will hold the coordinates&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;namespace AlexPetaBlog.GPSDistanceCalculator
{
    public struct GPSPoint
    {
        #region Private Members
        private double _latitude;
        private double _longitude;
        #endregion Private Members

        #region Public Properties
        public double Latitude
        {
            get { return _latitude; }
            set { _latitude = value; }
        }
        public double Longitude
        {
            get { return _longitude; }
            set { _longitude = value; }
        }
        #endregion Public Properties

        #region Constructors
        public GPSPoint(double latitude, double longitude)
        {
            _latitude = latitude;
            _longitude = longitude;
        }
        #endregion Constructors

        #region NullObject Pattern
        private static GPSPoint _empty = new GPSPoint(0, 0);
        public static GPSPoint NullPoint = _empty;
        #endregion NullObject Pattern
    }
}
&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;The GPSDistanceHelper class&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;namespace AlexPetaBlog.GPSDistanceCalculator
{
    /// &lt;summary&gt;
    /// This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points (ignoring any hills, of course!).
    /// &lt;/summary&gt;
    public class GPSDistanceHelper
    {

        #region Private Members
        //represents the radius of the Earth in KM
        private readonly int R = 6371;
        private GPSPoint _start;
        private GPSPoint _end;
        private double _distance;
        #endregion Private Members

        #region Public Properties
        public GPSPoint Start
        {
            get { return _start; }
            set { _start = value; }
        }
        public GPSPoint End
        {
            get { return _end; }
            set { _end = value; }
        }
        public double Distance
        {
            get
            {
                return _distance;   
            }
            set
            {
                _distance = value;
            }
        }
        #endregion Public Properties

        #region Constructors
        public GPSDistanceHelper(): this(GPSPoint.NullPoint,GPSPoint.NullPoint)
        {
        }
        public GPSDistanceHelper(GPSPoint start,GPSPoint end)
        {
            Start = start;
            End = end;

            CalculateDistance();
        }
        #endregion Constructors



        #region Statics
        public static  double DegreesToRadians(double degrees)
        {
            return degrees * (Math.PI / 180);
        }
        #endregion Statics

        #region Private Methods
        private void CalculateDistance()
        {
            double dLat = GPSDistanceHelper.DegreesToRadians(End.Latitude - Start.Latitude);
            double dLon = GPSDistanceHelper.DegreesToRadians(End.Longitude - Start.Longitude);

            double lat1 = GPSDistanceHelper.DegreesToRadians(Start.Latitude);
            double lat2 = GPSDistanceHelper.DegreesToRadians(End.Latitude);

            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);

            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            this.Distance = R * c;
        }
        #endregion Private Methods
    }
}
&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;And of course now we need to test this out with some unit tests.&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;namespace AlexPetaBlog.GPSDistanceCalculator.Tests
{
    [TestClass]
    public class GPSCalculatorTests
    {
        #region Private Members
        private GPSDistanceHelper _distanceHelper;

        private GPSPoint _bucharest;
        private GPSPoint _centralPark;

        #endregion Private Members

        [TestInitialize]
        public void Setup()
        {
            _distanceHelper = new GPSDistanceHelper();
            _bucharest = new GPSPoint(44.4269D, 026.1025D);
            _centralPark = new GPSPoint(40.7939D, -073.9571D);
        }

        [TestCleanup]
        public void TearDown()
        {
            _distanceHelper = null;
            _bucharest = GPSPoint.NullPoint;
            _centralPark = GPSPoint.NullPoint;
        }
        

        [TestMethod]
        public void GPSDistanceHelper_ToRadians_ReturnsCorrectResult()
        {
            //Arrange
            double expected = 0.174532925D;
            double delta = 0.000000001D;

            //Act
            double result = GPSDistanceHelper.DegreesToRadians(10);
            
            //Assert
            Assert.AreEqual(expected, result, delta);
        }

        [TestMethod]
        public void GPSDistanceHelper_Calculate_ReturnsCorrectResult()
        {
            //Arrange
            double expected = 7641D;
            double result = 0D;
            double delta = 0.9D;

            GPSDistanceHelper helper = new GPSDistanceHelper(start : _bucharest, end :_centralPark);

            //Act
            result = helper.Distance;

            //Assert
            Assert.AreEqual(expected, result,delta);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;And the results :&lt;/p&gt;
&lt;p&gt;&lt;img style="float: none; margin-left: auto; display: block; margin-right: auto" src="http://alexpeta.ro/content/images/gpshelper_tests.png" width="459" height="230"&gt; &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Conclusion&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;You can see the full source code in action on &lt;a title="GPSDistanceHelper" href="https://github.com/alexpeta/GPSDistanceHelper" rel="nofollow" target="_blank"&gt;Github&lt;/a&gt;.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/calculating-the-distance-between-two-gps-coordinates/</guid></item><item><title>My First Windows Phone App Location Based Notifications Part 1</title><link>http://www.alexpeta.ro/article/my-first-windows-phone-app-location-based-notifications-part-1/</link><description>&lt;p&gt;I will be starting a series of posts regarding my recent interest in Windows Phone 8 development. Then end goal is to build a simple application all they way from File &amp;gt; New Application up to having it ready for end users via the Windows Phone Marketplace (at least I hope I will finish it)&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The idea and disclaimer&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;&amp;nbsp;&lt;/strong&gt;Well I don’t think it’s original, I’m pretty sure it has already been implemented on other platforms, I didn’t check if something already exists for Windows Phone 8 because I will do it anyway : location based notification using the built-in phone GPS to track user location and show reminders if the phone is near a desired location.&lt;/p&gt;
&lt;p&gt;You can follow along my progress by reading this series as well as visiting &lt;a title="LocationBasedReminderWP8" href="https://github.com/alexpeta/LocationBasedReminderWP8" rel="nofollow" target="_blank"&gt;the dedicated Github repo&lt;/a&gt; with the full code version.&lt;/p&gt;
&lt;p&gt;Because the UI/UX and all the other delicious eye candy visuals will be the last thing that I will focus on I am starting the series from the “bottom” up , that is&amp;nbsp; in tech language translated to starting with the data layer.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Data Layer&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The data layer that I have created has 2 parts&amp;nbsp; Model and Data Access.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Model : BaseModel class&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;namespace LocationBasedNotifications
{
    public abstract class BaseModel : INotifyPropertyChanged,INotifyPropertyChanging
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        public event PropertyChangingEventHandler PropertyChanging;

        protected void NotifyPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if(handler != null)
            {
                handler(this,new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void NotifyPropertyChanging(string propertyName)
        {
            var handler = PropertyChanging;
            if (handler != null)
            {
                handler(this, new PropertyChangingEventArgs(propertyName));
            }
        }
        #endregion INotifyPropertyChanged

        protected virtual bool IsValid()
        {
            throw new NotImplementedException();
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;As you can notice my base class implements as expected INotifyPropertyChanged as well as INotifyPropertyChanging (it seems this is a good thing to do performance wise when it comes to WP8)&lt;/p&gt;&lt;pre class="prettyprint"&gt;namespace LocationBasedNotifications
{
    [Table]
    public class Location : BaseModel
    {
        #region Properties
        private int _locationId;

        [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
        public int LocationId
        {
            get { return _locationId; }
            set { _locationId = value; }
        }
        
        private string _name;

        [Column]
        public string Name
        {
            get { return _name; }
            set 
            {
                if (_name == value)
                {
                    return;
                }

                NotifyPropertyChanging("Name");
                _name = value;
                NotifyPropertyChanged("Name");
            }
        }

        private double _latitude;

        [Column]
        public double Latitude
        {
            get { return _latitude; }
            set 
            {
                if (_latitude == value)
                {
                    return;
                }

                NotifyPropertyChanging("Latitude");
                _latitude = value;
                NotifyPropertyChanged("Latitude");
            }
        }

        private double _longitude;

        [Column]
        public double Longitude
        {
            get { return _longitude; }
            set 
            {
                if (_longitude == value)
                {
                    return;
                }

                NotifyPropertyChanging("Longitude");
                _longitude = value;
                NotifyPropertyChanged("Longitude");
            }
        }

        private string _description;

        [Column]
        public string Description
        {
            get { return _description; }
            set 
            {
                if (_description == value)
                {
                    return;
                }

                NotifyPropertyChanging("Description");
                _description = value;
                NotifyPropertyChanged("Description");
            }
        }

        // Version column aids update performance.
        [Column(IsVersion = true)]
        private Binary _version;
        #endregion Properties

        #region Constructors
        public Location() : this(string.Empty,0D,0D,string.Empty)
        {
        }
        public Location(string name, double latitude, double longitude, string description)
        {
            Name = name;
            Latitude = latitude;
            Longitude = longitude;
            Description = description;
        }
        #endregion Constructors

    }
}
&lt;/pre&gt;
&lt;p&gt;This is the Location entity that inherits the above BaseModel. As you noticed all of the public properties are are decorated with attributes from the &lt;strong&gt;System.Data.Linq.Mapping&lt;/strong&gt; namespace. The reason for this is that Windows&amp;nbsp; Phone 8 uses as persistent storage &lt;a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202860(v=vs.105).aspx" rel="nofollow" target="_blank"&gt;Linq to SQL via the DataContext on the isolated storage database.&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Data Access&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Now we need to implement the DataContext&amp;nbsp; and the repository interface contracts:&lt;/p&gt;&lt;pre class="prettyprint"&gt;namespace LocationBasedNotifications.Contracts
{
    public interface IRepository&lt;t&gt;
        where T : BaseModel
    {
        IEnumerable&lt;t&gt; GetInMemoryLocations();
        bool AddItem(T itemToAdd);
        bool RemoveItem(T itemToRemove);
        void Save(IEnumerable&lt;t&gt; list);
    }
}
&lt;/pre&gt;
&lt;p&gt;The DataContext&lt;/p&gt;&lt;pre class="prettyprint"&gt;namespace LocationBasedNotifications.Repository
{
    public class LocalStorageRepository : IRepository&lt;location&gt;
    {
        #region Private Members
        private ReminderDataContext _db;
        #endregion Private Members

        #region Constructors
        public LocalStorageRepository()
        {
            _db = App.LocalDB;
        }
        #endregion Constructors

        #region IRepository
        public IEnumerable&lt;location&gt; GetInMemoryLocations()
        {
            var results = from d in _db.Locations
                          select d;

            return results;
        }

        public bool AddItem(Location itemToAdd)
        {
            if (itemToAdd == null)
            {
                throw new ArgumentNullException("location cant be null");
            }

            try
            {
                _db.Locations.InsertOnSubmit(itemToAdd);
                _db.SubmitChanges();
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public bool RemoveItem(Location itemToRemove)
        {
            if (itemToRemove == null)
            {
                throw new ArgumentNullException("location cant be null");
            }

            try
            {
                _db.Locations.DeleteOnSubmit(itemToRemove);
                _db.SubmitChanges();
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public void Save(IEnumerable&lt;location&gt; list)
        {
            throw new NotImplementedException();
        }
        #endregion IRepository
        
    }
}
&lt;/pre&gt;
&lt;p&gt;And finally we need to initialize the storage. This is done in the App.xaml.cs constructor&lt;/p&gt;&lt;pre class="prettyprint"&gt;    private void InitializeDatabase()
    {
        ReminderDataContext db = new ReminderDataContext(Constants.DBConnectionString);
        if (!db.DatabaseExists())
        {
            db.CreateDatabase();
        }
        _localDB = db;
    }
&lt;/pre&gt;
&lt;p&gt;Afte the initialization im keeping a reference to the DataContext in the App object via the _localDB property that I will be using throughout the whole application.&lt;/p&gt;
&lt;p&gt;A think to note here is the format of the connection string. Because I don’t like hardcoded strings, I have created a utility class that stores constants and this is where I have defined my connection string. It looks like this:&lt;/p&gt;
&lt;p&gt;“Data Source=isostore:/LocationBasedReminders.sdf” where isostore si the root location of the path and it basically represents the local folder previously known as isolated storage.&lt;/p&gt;
&lt;p&gt;Mode details about how connection strings are in Windows Phone 8 can be found &lt;a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202861(v=vs.105).aspx" rel="nofollow" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This is it for this first post in the series.I have shown today how to have a data layer up and running for Windows Phone 8. If you wish to see it in action check out the Github project page.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/my-first-windows-phone-app-location-based-notifications-part-1/</guid></item><item><title>Unit Testing JavaScript with QUnit</title><link>http://www.alexpeta.ro/article/unit-testing-javascript-with-qunit/</link><description>&lt;blockquote&gt;
&lt;p&gt;Introduction to QUnit&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;QUnit is an easy-to-use JavaScript unit test suite developed and used by the jQuery team. You can find all the details here : &lt;a title="http://qunitjs.com/" href="http://qunitjs.com/" rel="nofollow" target="_blank"&gt;http://qunitjs.com/&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;What do you need to get started:&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;QUnit consists of two small files:&lt;strong&gt; qunit.css&lt;/strong&gt; and&lt;strong&gt; qunit.js&lt;/strong&gt;. You would also need a html web page to run the code and show you the results that needs to load the files and have 2 divs with the ids &lt;em&gt;qunit-fixture&lt;/em&gt; and &lt;em&gt;qunit&lt;/em&gt;. Im naming this file &lt;em&gt;test-runner.html&lt;/em&gt;. Here is the how the test runner looks like:&lt;/p&gt;&lt;pre class="prettyprint"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset="utf-8"&amp;gt;
  &amp;lt;title&amp;gt;QUnit Example&amp;lt;/title&amp;gt;
  &amp;lt;link rel="stylesheet" href="qunit.css"&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div id="qunit"&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;div id="qunit-fixture"&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;script src="qunit.js"&amp;gt;&amp;lt;/script&amp;gt;
  
  &amp;lt;script src="code_to_test.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script src="tests.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;
&lt;p&gt;We are going to add all of our tests in a javascript file named &lt;em&gt;tests.js&lt;/em&gt;. and the code that we will test will be in the file &lt;em&gt;code_to_test.js&lt;/em&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The code to test&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Due to the lack on imagination and out of pure laziness, I’ll be testing a function that adds two numbers together and also I’ve defined a custom exception that I am throwing:&lt;/p&gt;&lt;pre class="prettyprint"&gt;/*	
  custom ArgumentException
*/
function ArgumentException(message)
{
  this.Message = message;
  this.Name = "ArgumentException";
}
/*
  Method to test
*/
function Sum(a,b)
{
  if(typeof(a) !== "number" || typeof(b) !== "number")	
  {
    throw new ArgumentException("Function only accepts number params.");
  }
  return a+b;
}
&lt;/pre&gt;
&lt;p&gt;And here are the tests : the first one is a test for the logic of the function and the second tests the parameters if the method throws correctly an exception when non-numeric parameters are passed. I’m using the same AAA(arange,act,assert) pattern for the tests&lt;/p&gt;&lt;pre class="prettyprint"&gt;module("Sum_Tests");
test("Sum_Returns_CorrectSumAndType", function()
{
  //Arrange
  //Act
  var result = Sum(5,6);
  var expected = 11;

  //Assert
  equal(typeof(result),"number");
  equal(result,expected);
});

test("Sum_ThrowsExpWhenArgIsNotNumber", function(){  
  //Arrange  
  //Act 
  
  //Assert  
  throws(function()
  {
    var result = Sum("4","7");
  },
  ArgumentException,
  "raised error is an instance of ArgumentException");
});
&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Conclusion&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Although this example isnt something too complex, its here to get help you get started on how you can write less error prone JavaScript code using QUnit. I think any project that is either a single page app or relies heavily on JavaScript to save the day needs to implement some kind of testing framework.&lt;/p&gt;
&lt;p&gt;&lt;a title="download code sample" href="http://www.alexpeta.ro/blog/download/unit-testing-with-qUnit.zip" rel="nofollow"&gt;Download the sample code here&lt;/a&gt;&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/unit-testing-javascript-with-qunit/</guid></item><item><title>Real Time web applications in ASP MVC 4 with SignalR RONUA Presentation Part 2</title><link>http://www.alexpeta.ro/article/real-time-web-applications-in-asp-mvc-4-with-signalr-ronua-presentation-part-2/</link><description>&lt;p&gt;I held my presentation yesterday @RONUA and I have to say I was really happy to see 20+ people despite the cold weather outside and the meeting place change (our new meetingplace is now Ubisoft’s headquarters) present and I just want to say thank you for coming! I hope I wasn’t too boring and I promise that next time I will try to do better and present more interesting stuff.&lt;/p&gt;
&lt;p&gt;About the code presented, the small chat app I think isn’t that valuable by itself and if you got the idea about how things are working then I advise you to visit &lt;a title="https://github.com/alexpeta/TicTacToeSignalR" href="https://github.com/alexpeta/TicTacToeSignalR" rel="nofollow"&gt;my Github repo for the TicTacToe Game&lt;/a&gt; and &lt;strong&gt;download&lt;/strong&gt;/&lt;strong&gt;fork&lt;/strong&gt; the code there and test it out or if you want to add changes I’ll be happy to accept&amp;nbsp; your &lt;strong&gt;pull&lt;/strong&gt; &lt;strong&gt;requests&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If you want to take the game for a spin, its already hosted on AppHarbor at &lt;a title="http://tictactoe-8.apphb.com/" href="http://tictactoe-8.apphb.com/"&gt;http://tictactoe-8.apphb.com/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As for the slides, I have uploaded a .zip &lt;a title="Real Time web apps in ASP MVC 4 with SignalR at RONUA" href="/blog/download/ronua-signalr.zip" rel="nofollow"&gt;archive for you to download here.&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note&lt;/em&gt;: its made in html+css3 , with &lt;a href="http://lab.hakim.se/reveal-js/#/" rel="nofollow"&gt;reveal.js&lt;/a&gt; and &lt;a title="animate.css" href="http://daneden.me/animate/" rel="nofollow"&gt;animate.css&lt;/a&gt; so for full compatibility, open it in a modern browser (I suggest Chrome).&lt;/p&gt;
&lt;p&gt;Now let me just point out&amp;nbsp; a few things I’ve learned by doing this presentation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Its always the small projects that are the most fun;&lt;/li&gt;
&lt;li&gt;Note to self : I should repeat the demo at least twice before doing it live in front of an audience;&lt;/li&gt;
&lt;li&gt;You should take on a challenge like doing presentations regularly because you will benefit from it by learning something new and sharing it with others;&lt;/li&gt;
&lt;li&gt;Started working with Git on Github;&lt;/li&gt;
&lt;li&gt;Found out about AppHarbour&lt;/li&gt;&lt;/ul&gt;</description><guid>http://www.alexpeta.ro/article/real-time-web-applications-in-asp-mvc-4-with-signalr-ronua-presentation-part-2/</guid></item><item><title>Real Time web applications in ASP MVC 4 with SignalR RONUA Presentation</title><link>http://www.alexpeta.ro/article/real-time-web-applications-in-asp-mvc-4-with-signalr-ronua-presentation/</link><description>&lt;p&gt;I will be holding a short presentation at the local .NET user group on Tuesday, the 8th of January 2013. &lt;/p&gt;
&lt;p&gt;The official event announcement is here : &lt;a title="http://ronua.ro/CS/groups/ronua-bucuresti/default.aspx" href="http://ronua.ro/CS/groups/ronua-bucuresti/default.aspx" rel="nofollow"&gt;http://ronua.ro/CS/groups/ronua-bucuresti/default.aspx&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;My talk will be about how to build real-time web applications in &lt;a href="http://www.asp.net/mvc" rel="nofollow"&gt;ASP.MVC 4&lt;/a&gt; using the newly integrated &lt;a href="http://signalr.net/" rel="nofollow"&gt;SignalR&lt;/a&gt; framework. &lt;/p&gt;
&lt;p&gt;As an example, I have coded a small Tic Tac Toe game, I will showcase it and present the source code.I was hoping to do live coding of the whole application, but if its too much to code in the hour+ given, maybe I will do a different short project to show how to get started.&lt;/p&gt;
&lt;p&gt;See you there!&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/real-time-web-applications-in-asp-mvc-4-with-signalr-ronua-presentation/</guid></item><item><title>Bodybuilding and High Intensity Training</title><link>http://www.alexpeta.ro/article/bodybuilding-and-high-intensity-training/</link><description>&lt;p&gt;I’ve been keen on starting to write about my bodybuilding experience and that I have learned since first days in the gym up until now and I want to start this series of blog posts by posting a video here about High Intensity Training (HIT).&lt;/p&gt;
&lt;p&gt;The guy presenting is Drew Baye, I haven’t heard much of him up until lately but his explanations really nails it (from my point of view) when it comes to intense training and getting results.&lt;/p&gt;
&lt;p&gt;Enjoy :&lt;/p&gt;
&lt;center&gt;&lt;iframe height="315" src="http://www.youtube.com/embed/4rNm4kSl3Og" frameborder="0" width="560" allowfullscreen&gt;&lt;/iframe&gt;&lt;/center&gt;</description><guid>http://www.alexpeta.ro/article/bodybuilding-and-high-intensity-training/</guid></item><item><title>Exporting a Cangeset in Team Foundation Server TFS using Team Foundation Power Tools TFPT Part 2</title><link>http://www.alexpeta.ro/article/exporting-a-cangeset-in-team-foundation-server-tfs-using-team-foundation-power-tools-tfpt-part-2/</link><description>&lt;p&gt;As mentioned &lt;a title="Exporting a changeset in Team Foundation Server TFS using Team Foundation Power Tools TFPT" href="http://www.alexpeta.ro/article/exporting-a-changeset-in-team-foundation-server-tfs-using-team-foundation-power-tools-tfpt/"&gt;in my first post about Team Foundation Server and Team Foundation Power Tools&lt;/a&gt; I was working on making a Console Application to leverage tftp.exe and export a range of changesets.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt; : &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;team foundation power tools installed. 
&lt;li&gt;a directory mapped to your team foundation server.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;&lt;font color="#333333"&gt;Note&lt;/font&gt;&lt;/strong&gt;: run compiled executable file INSIDE a mapped directory to your TF Server.&lt;/p&gt;
&lt;p&gt;Lets skip right to a bunch of code:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Timer Class – is used to time the whole operation&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;public static class Timer
{
    public static void GetElapsedTime(Action methodToTime)
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        methodToTime.Invoke();
        sw.Stop();
        Console.WriteLine(string.Format("Total duration : {0} ms", sw.ElapsedMilliseconds));
        Logger.WriteEntry(string.Format("Total duration : {0} ms", sw.ElapsedMilliseconds));
    }
}
&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Logger Class – small logging utility class&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;public class Logger
{
    #region Private Members
    public static bool HasEncounteredError = false;
    private static FileInfo _file;
    #endregion

    #region Constants
    public static string LogName = "ExportChangesetLog";
    public static string LogFullPath = string.Format("{0}\\{1}.log",Environment.GetFolderPath(Environment.SpecialFolder.Desktop),Logger.LogName);
    #endregion

    #region Constructors
    public Logger()
    {
        if (!LogFileExists())
        {
            CreateLogFile();
        }
    }
    #endregion

    #region Private Methods
    private bool LogFileExists()
    {
        try
        {
            FileInfo logFile = new FileInfo(Logger.LogFullPath);
            if (logFile.Exists)
            {
                _file = logFile;
                return true;
            }
            return false;
        }
        catch
        {
            Console.WriteLine("-- Could not check if file exists. Logging will be disabled.");
            return false;
        }
    }

    private void CreateLogFile()
    {
        try
        {
            if (_file == null)
            {
                FileInfo file = new FileInfo(Logger.LogFullPath);
                FileStream _fileStream = file.Create();
                _file = file;
                _fileStream.Close();
            }
        }
        catch (Exception)
        {
            Console.WriteLine("-- Could not create log file. Logging will be disabled.");
            Logger.HasEncounteredError = true;
        }
    }
    #endregion

    #region Statics
    public static void WriteEntry(string entry)
    {
        if (!string.IsNullOrEmpty(entry) &amp;amp;&amp;amp; !Logger.HasEncounteredError)
        {
            try
            {
                if (_file != null)
                {
                    using (var writer = _file.AppendText())
                    {
                        writer.WriteLine();
                        writer.WriteLine("-----------------------------");
                        writer.WriteLine(string.Format("{0}", DateTime.Now));
                        writer.WriteLine(entry);
                        writer.WriteLine("-----------------------------");
                        writer.WriteLine();
                    }
                }
            }
            catch
            {
                Console.WriteLine("-- Error writing to log file. Logging will be disabled.");
                Logger.HasEncounteredError = true;
            }
        }
    }
    #endregion
}
&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Main Application Body – includes checking user inputs and handling the export&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;class Program
{
    private static int startChangesetNumber = 0;
    private static int endChangesetNumber = 0;

    static void Main(string[] args)
    {
        Timer.GetElapsedTime(() =&amp;#62;
            {
                //init logger
                Logger logger = new Logger();

                //check for command line args
                if (!HasCommandLineArgs(args))
                {
                    //check user inputs
                    GetUserInputChangesets();

                    //export
                    Export();
                }
            });  
    }

    #region Private Methods
    private static void GetUserInputChangesets()
    {
        string firstUserInput = string.Empty;
        do
        {
            Console.WriteLine("First changeset number :");
            firstUserInput = Console.ReadLine();
        }
        while (!ValidInput(firstUserInput, out startChangesetNumber));

        string secondUserInput = string.Empty;
        do
        {
            Console.WriteLine("Second changeset number :");
            secondUserInput = Console.ReadLine();
        }
        while (!ValidInput(secondUserInput, out endChangesetNumber));
    }

    private static void Export()
    {
        Console.WriteLine("===============================================");
        Console.WriteLine(System.Environment.NewLine);
        Logger.WriteEntry("-- Starting Export...");

        int currentChangeset = startChangesetNumber;
        while (currentChangeset &amp;#60;= endChangesetNumber)
        {
            try
            {
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = "tfpt.exe";
                process.StartInfo.Arguments = string.Format(" getcs /changeset:{0} /overwrite",currentChangeset);
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                Console.WriteLine(output);
                Logger.WriteEntry("------------------------------");
                Logger.WriteEntry(output);
                Logger.WriteEntry("------------------------------");
                Logger.WriteEntry("--");                    
            }
            catch (Exception e)
            {
                Console.WriteLine("Error when exporting changeset {0} : {1}",currentChangeset,e.Message);
                Logger.WriteEntry(string.Format("Error when exporting changeset {0} : {1}", currentChangeset, e.Message));
                break;
            }
            currentChangeset++;
        }

        Logger.WriteEntry("-- Export finished..");
        Console.WriteLine("===============================================");
    }

    private static bool ValidInput(string input,out int param)
    {
        param = 0;

        if (string.IsNullOrWhiteSpace(input)) return false;

        if (startChangesetNumber == 0)
        {
            return int.TryParse(input, out param);
        }
        else
        {
            if (int.TryParse(input, out param) &amp;&amp; param &amp;#62;= startChangesetNumber)
            {
                return true;
            }
            else
            {
                param = 0;
                return false;
            }
        }
    }

    private static bool HasCommandLineArgs(string[] args)
    {
        if (args.Count() != 2) return false;

        return ValidInput(args[0].ToString(), out startChangesetNumber) &amp;&amp;
                ValidInput(args[1].ToString(), out startChangesetNumber);
    }
    #endregion
}
&lt;/pre&gt;
&lt;p&gt;
 &lt;strike&gt;Will upload this also to Codeplex.&lt;/strike&gt;
&lt;/p&gt;
&lt;p&gt;
  Code is at your disposal at : &lt;a href="https://exporttfschangesets.codeplex.com/" rel="nofollow"&gt;https://exporttfschangesets.codeplex.com/&lt;/a&gt;
&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/exporting-a-cangeset-in-team-foundation-server-tfs-using-team-foundation-power-tools-tfpt-part-2/</guid></item><item><title>Building a Pinterest like Image Crawler</title><link>http://www.alexpeta.ro/article/building-a-pinterest-like-image-crawler</link><description>&lt;p&gt;Social networking sites are looking for newer ways to involve their users more, make them share and exchange information as quickly as possible with as littlest effort as possible from the user, from any platform and any device. Some even go even beyond the “moral” boundaries as to collect information without the user being informed (cookie collection).&lt;/p&gt;
&lt;p&gt;But leaving this aside, I’m writing today about the Pinterest share button, it has an interesting feature, you can drag&amp;amp;drop it to your browser’s bookmarks bar and on every site, when clicking that specific button, it scans the HTML and asks the user which of the site images he wants to “pin” on his profile.&lt;/p&gt;
&lt;p&gt;So our goal today is to provide a proof of concept of&amp;nbsp; how this is done, so let’s get coding.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;First, the user goodies : the bookmark button.&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Let’s all agree now what browser bookmarks are. They are character strings saved and executed when clicked. Good. Combine this piece of information with the fact that instead of URL’s, in a anchor tag we can also run Javascript instead of the HREF attribute, then we can conclude that we can run Javascript from the toolbar.&lt;/p&gt;
&lt;p&gt;Our bookmark button is an anchor tag withe the following HREF attribute :&lt;/p&gt;&lt;pre class="prettyprint"&gt;javascript:void((function(){var%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://alexpeta.ro/scripts/imageCrawler.js?r='+Math.random()*99999999);document.body.appendChild(e)})());" onclick="alert('Drag and drop this button to your browser bookmarks toolbar.'); return false;
&lt;/pre&gt;
&lt;p&gt;This piece of code does the following things :&lt;/p&gt;
&lt;ul&gt;
&lt;ul&gt;
&lt;li&gt;creates a new script tag html element 
&lt;li&gt;sets the script tag type to javascript 
&lt;li&gt;sets the charset attribute 
&lt;li&gt;gets the javascript that will be injected in target page by setting the SRC attribute (note : I have added here after the file name a random number to prevent the browser from getting the file from cache, and force it to get a new file each time) 
&lt;li&gt;append the formed SCRIPT tag to the document (another thing to note here is how browsers behave : each time they “see” an “IMG” or “SCRIPT” tag, they look for the SRC path attribute and perfom a GET operation) – this will trigger the browser to run the javascript. &lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;The imageCraler&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;var imageCrawler = {
	containerName : 'imageCrawlerContainer',
	GenerateContainer :  function() {
		return '&amp;lt;div class="imageCrawler-container" id="'+imageCrawler.containerName+'"&amp;gt;&amp;lt;table&amp;gt;&amp;lt;tr&amp;gt; &amp;lt;td&amp;gt; &amp;lt;span&amp;gt;Hey Joe, here are the images :&amp;lt;/span&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;td style="width:160px;padding-top:5px;"&amp;gt;&amp;lt;a href="javascript:imageCrawler.SaveBookmark();" title="Add to ImageCrawler"&amp;gt;Add To ImageCrawler&amp;lt;/a&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&amp;lt;tr&amp;gt;'+
		'&amp;lt;td&amp;gt;&amp;lt;table&amp;gt;'+imageCrawler.InsertImages()+'&amp;lt;/table&amp;gt;&amp;lt;/td&amp;gt;'+
		'&amp;lt;/tr&amp;gt;&amp;lt;/table&amp;gt;&amp;lt;/div&amp;gt;';
	},
	DeleteContainer : function(){
		var element = document.getElementById(imageCrawler.containerName);
		var body = document.getElementsByTagName('body')[0];
		body.removeChild(element);
	},
	HasJquery : function(){
	   	try
		{
			var jqueryIsLoaded=jQuery;
			jQueryIsLoaded=true;
		}
		catch(err)
		{
			var jQueryIsLoaded=false;
		}

		if(jQueryIsLoaded)
		{
			return true;
		}	
		else
		{
			return false;
		}
	},
	SaveBookmark : function() {
		alert('Saving images ....etc..! Done!');
		var t = setTimeout("imageCrawler.DeleteContainer()","2000");
	},
	InsertImages : function(){
    	var imagesArr = document.getElementsByTagName('img');

    	if(imagesArr == null || imagesArr.length==0)
    	{
    		return '&amp;lt;tr&amp;gt;&amp;lt;td&amp;gt;&amp;lt;span style=""&amp;gt;No Images found :(&amp;lt;/span&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;';
    	}
        else
        {
	    	for(var i=0;i&amp;lt;imagesArr.length;i++)
	    	{
	    		if(imagesArr[i].src != null &amp;amp;&amp;amp; imagesArr[i].src != '')
	    		{
	    			return '&amp;lt;tr&amp;gt;&amp;lt;td&amp;gt;&amp;lt;img src="'+imagesArr[i].src+'"/&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;';
	    		}
	    	}
    	}
	},
	InitCrawler : function(){
		 document.body.insertAdjacentHTML('afterBegin', imageCrawler.GenerateContainer());
	}
};

 (function(){
 	setTimeout("imageCrawler.InitCrawler()", 50);
 })();

&lt;/pre&gt;
&lt;p&gt;And to comment a bit the code above:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Im creating here an imageCrawler object that has a couple of methods from which the main ones are :&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;GenerateContainer – this will generate the HTML that will be showed to the user the the Bookmark is clicked.&lt;/li&gt;
&lt;li&gt;InsertImages – this method is the one that “scans” the page for images and builds the strings that will be displayed to the user.&lt;/li&gt;
&lt;li&gt;the last 3 rows represent a self executing function that will trigger the InitCrawler to show the HTML.&lt;/li&gt;&lt;/ul&gt;&lt;/ul&gt;
&lt;p&gt;To test this out , you can &lt;a href="https://imagecrawlerjs.codeplex.com/" rel="nofollow"&gt;download the full source over on Codeplex : https://imagecrawlerjs.codeplex.com/&lt;/a&gt;.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/building-a-pinterest-like-image-crawler</guid></item><item><title>Exporting a changeset in Team Foundation Server TFS using Team Foundation Power Tools TFPT</title><link>http://www.alexpeta.ro/article/exporting-a-changeset-in-team-foundation-server-tfs-using-team-foundation-power-tools-tfpt/</link><description>&lt;p&gt;Sometime it is necessary to export just the files from the specific changeset (commit version number) from a code repository. 
&lt;p&gt;In my case, this is a repetitive task , done weekly, as I need to sync code between teams in different countries that are not on the same server. 
&lt;p&gt;This info already exists on the web, but spread out through different pages and blogs. I didn’t find a step-by-step post on how to accomplish this, so my goal here is to have the info centralized. 
&lt;p&gt;First of all note that this feature doesn’t come "out of the box" with TFS 2010, we need an extension named "Team Foundation Server Power Tools" (December 2011 release at the time I’m writing this post). 
&lt;p&gt;Download and install the extension&amp;nbsp; : &lt;a href="http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f" rel="nofollow"&gt;http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f&lt;/a&gt; 
&lt;p&gt;Open a CMD window and run &lt;strong&gt;tfpt.exe&lt;/strong&gt; and you will see all available options , but we are just interested in &lt;strong&gt;GETCS&lt;/strong&gt;. 
&lt;p&gt;It has the following syntax : 
&lt;blockquote&gt;
&lt;p&gt;tfpt getcs /changeset:changesetnum [/force] [/overwrite]&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;where "changesetnum" is the changeset it that we wish to export the other two directives in square brackets are optional. 
&lt;p&gt;Example : If I wish to export changeset number 77 I would issue : 
&lt;blockquote&gt;
&lt;p&gt;tfpt getcs /changeset:77&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Now, if you would try to run this command directly , you would probably get an error with the following message : “Unable to determine the workspace”. 
&lt;p&gt;After searching a bit, it seems that Team Foundation Power Tools need to be run via CMD in a directory that is Mapped as being under source control with TFS. 
&lt;p&gt;&lt;strong&gt;NOTE :&lt;/strong&gt; if you would run the command against the existing mapped folder, lets say you have a MAIN branch folder somewhere on your hdd, you will not see just the changes from the requested changeset, because you will see all the existing solution. 
&lt;p&gt;Create a new folder, open Team Explorer , add a branch to your current solution and map it against your newly created folder. 
&lt;p&gt;&lt;strong&gt;When you will be prompted to download the solution , click NO,&lt;/strong&gt;this way you will obtain a clean mapped folder but without any code in it. 
&lt;p&gt;Run the command in your clean new mapped folders, and “Voila” this will bring you your changeset results. 
&lt;p&gt;&lt;strong&gt;UPDATE &lt;/strong&gt;
&lt;p&gt;The info above works fine , but what happens when you want to export a lot of changesets, when changes are commited by&amp;nbsp; a team of developers. Running this command 50 times over and over is cumbersome and this task could be automated. 
&lt;p&gt;I wrote a small quick and dirty batch script that executes this command: &lt;/p&gt;&lt;pre class="prettyprint"&gt;REM Export Changesets Bat
REM 

SET startChangeset=45
SET endChangeset=66


FOR /l %%x in (%startChangeset%, 1, %endChangeset%) DO (
	ECHO Getting Changeset - %%x
    tfpt.exe getcs /changeset:%%x /overwrite
) 
&lt;/pre&gt;
&lt;p&gt;I’m currently writing a Console application in C# that leverages &lt;a title="System.Diagnostics.Process" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" rel="nofollow" target="_blank"&gt;System.Diagnostics.Process&lt;/a&gt; class, and accepts command line parameters for startChangeset or endChangeset or waits for user input in the console for the given parameters.Will update when finished.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/exporting-a-changeset-in-team-foundation-server-tfs-using-team-foundation-power-tools-tfpt/</guid></item><item><title>Unit Testing your ASP MVC HtmlHelper Methods</title><link>http://www.alexpeta.ro/article/unit-testing-your-asp-mvc-htmlhelper-methods/</link><description>&lt;p&gt;Unit testing has been my focus lately, and even at work it seems that this is the main focus for most of the guys there.&amp;nbsp; And this whole testing stuff started to grow on me and I can say that I really enjoy it so what better to do than write a blog post.&lt;br&gt;The focus of this post is how to test your HtmlHelper methods in ASP MVC , and I will be using the Microsoft Testing Framework inside Visual Studio 2012 RTM (ultimate) at the moment.&lt;/p&gt;
&lt;p&gt;Sure enough its a well pro fact that ASP MVC was designed with unit testing and TDD in mind.&lt;br&gt;&lt;/p&gt;
&lt;p&gt;Lets start off with our code that we want to test. I am testing one of the helpers used on this very blog, named BlogStatisticsHelper that generates this region here :&lt;/p&gt;
&lt;p&gt;&lt;a href="$statistis_helper_rendered2.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="statistis_helper_rendered" border="0" alt="statistis_helper_rendered" src="http://alexpeta.ro/content/images/statistics_helper_rendered.png" width="184" height="64"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;And the code for it is the following :&lt;/p&gt;&lt;pre class="prettyprint"&gt;public static HtmlString BlogStatistics(this HtmlHelper helper, IBlogRepository repository = null)
{
    int totalArticles = 0;
    int totalViews = 0;
    int totalComments = 0;
    StringBuilder sb = new StringBuilder();

    if (repository == null)
    {
        repository = new BlogRepository();
    }


    using (repository)
    {
        totalArticles = repository.TotalArticles();
        totalViews = repository.TotalViews();
        totalComments = repository.TotalComments();
    }
     sb.Append(string.Format(@"&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;{0}&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;posts&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;{1}&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;views&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;{2}&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;comm&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;",
     totalArticles.ThousandK(),
     totalViews.ThousandK(),
     totalComments.ThousandK()
     ));

    return MvcHtmlString.Create(sb.ToString());
}
&lt;/pre&gt;
&lt;p&gt;I am using the &lt;a href="http://msdn.microsoft.com/en-us/library/ff649690.aspx" rel="nofollow" target="_blank"&gt;Repository Pattern&lt;/a&gt; for loose coupling between my data layer,business and presentation layers. &lt;/p&gt;
&lt;p&gt;Because this helper method is called in my _Layout.cshtml view(master page equivalent for web forms guys) , I need to provide it with a BlogRepository object to query my entities for result sets and in order to unit test it , I am providing the data access via an interface parameter : IBlogRepository.&lt;/p&gt;
&lt;p&gt;This interface is implemented both on my real data BlogRepository class, and in my FakeRepository in memory class created specially for unit testing, and I can switch between the two of them.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Setting up the Context.&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;In order to instantiate a new HtmlHelper class, &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx" rel="nofollow" target="_blank"&gt;it’s constructor expects 2 parameters&lt;/a&gt; : a ViewContext and IViewDataContainer. I am also creating a fake HttpContext for other future test scenarios ;).&lt;/p&gt;&lt;pre class="prettyprint"&gt;public class FakeContext
{
  public class FakeHttpContext : HttpContextBase
  {
    public Dictionary&amp;lt;object, object&amp;gt; _dictionary = new Dictionary&amp;lt;object, object&amp;gt;();
    public virtual System.Collections.IDictionary Item { get { return _dictionary; } }
  }
  public class FakeIView : IViewDataContainer
  {
    private ViewDataDictionary _viewdata = new ViewDataDictionary();
    public ViewDataDictionary ViewData
    {
      get { return _viewdata; }
      set { _viewdata = value; }
    }
  }
}
&lt;/pre&gt;
&lt;p&gt;Now, let’s write some tests :&lt;/p&gt;&lt;pre class="prettyprint"&gt;namespace AlexPeta_2.Tests
{
    [TestClass]
    public class HelperMethodsTests
    {

        private HttpContextBase _httpContext = null;
        private IViewDataContainer _IView = null;
        private ViewContext _viewContext = null;

        private IBlogRepository _repository;

        [TestInitialize]
        public void SetupContext()
        {
            //necessary for building the HTML Helpers
            _httpContext = new Models.FakeContext.FakeHttpContext();
            _IView = new Models.FakeContext.FakeIView();
            _viewContext = new ViewContext();
            _repository = new FakeRepository();
        }

        [TestCleanup]
        public void CleanContext()
        {
            //housekeeping
            _httpContext = null;
            _IView = null;
            _viewContext = null;
            _repository = null;
        }

        [TestMethod]
        public void BlogStatisticsHelperIsNotNull()
        {
            //Arrange
            HtmlHelper helper = new HtmlHelper(_viewContext, _IView);

            //Act
            string helperHtmlResult = AlexPeta_2.Helpers.BlogHelpers.BlogStatistics(helper, _repository).ToString();

            //Assert
            Assert.IsNotNull(helperHtmlResult);
        }

        [TestMethod]
        public void BlogStatisticsHelperReturnsExpectedHtmlWhenRepositoryIsEmpty()
        {
            //Arrange
            HtmlHelper helper = new HtmlHelper(_viewContext, _IView);
            string expectedResult = @"&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;0&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;posts&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;0&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;views&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;0&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;comm&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;";

            //Act
            string helperHtmlResult = AlexPeta_2.Helpers.BlogHelpers.BlogStatistics(helper, _repository).ToString();

            //Assert
            Assert.AreEqual(expectedResult, helperHtmlResult);
        }


        [TestMethod]
        public void BlogStatisticsHelperReturnsExpectedHtml()
        {
            //Arrange
            _repository = new FakeRepository(false);
            Article newArticle = new Article
            {
                Title = "New Article",
                Text = "Content Goes Here",
                Views = 1345,
                Comments = null,
                Published = true
            };
          
            //Act
            _repository.AddArticle(newArticle);
            HtmlHelper helper = new HtmlHelper(_viewContext, _IView);
            string expectedResult = @"&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;1&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;posts&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;1.3K&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;views&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;0&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;comm&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;";

            string helperHtmlResult = AlexPeta_2.Helpers.BlogHelpers.BlogStatistics(helper, _repository).ToString();

            //Assert
            Assert.AreEqual(expectedResult, helperHtmlResult);
        }

        [TestMethod]
        public void BlogStatisticsHelperReturnsOnlyPublishedArticles()
        {
            //Arrange
            _repository = new FakeRepository(false);
            Article newArticle = new Article
            {
                Title = "New Article",
                Text = "Content Goes Here",
                Views = 1345,
                Comments = null,
                Published = false
            };
            Article secondArticle = new Article
            {
                Title = "Second Article",
                Text = "Content Goes Here",
                Views = 3342,
                Comments = null,
                Published = false
            };

            //Act
            _repository.AddArticle(newArticle);
            HtmlHelper helper = new HtmlHelper(_viewContext, _IView);
            string expectedResult = @"&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;0&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;posts&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;1.3K&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;views&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div class=""views""&amp;gt;&amp;lt;div class=""mini-counts""&amp;gt;0&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;comm&amp;lt;/div&amp;gt;&amp;lt;/div&amp;gt;";

            string helperHtmlResult = AlexPeta_2.Helpers.BlogHelpers.BlogStatistics(helper, _repository).ToString();

            //Assert
            Assert.AreEqual(expectedResult, helperHtmlResult);
        }

    }
}
&lt;/pre&gt;
&lt;p&gt;As you expected, these are are just a few tests that make simple string comparisons to check if your helper returns the desired HTML.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://alexpeta.ro/content/images/unit-tests-success.png" width="772" height="187"&gt;&lt;/p&gt;
&lt;p&gt;After we see that all the test ran smoothly (indicated by a green&amp;nbsp; colored icon)( I have a few more tests in the print screen then coded above) we need to check the Test Coverage Tab – this will show us the percentage that our tests covered against our HtmlHelper. &lt;/p&gt;
&lt;p&gt;Multi-select the tests that you want to check the coverage for, Right Click and choose “Analyze Code Coverage” and then select the Code Coverage Results tab as shown in the print screen below.&lt;/p&gt;
&lt;p&gt;&lt;img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://alexpeta.ro/content/images/show-code-coverage.png" width="771" height="265"&gt;&lt;/p&gt;
&lt;p&gt;This will show you the percentage results that you can further investigate with a double-click on the result set row.&lt;/p&gt;
&lt;p&gt;&lt;img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://alexpeta.ro/content/images/code-coverage-results.png"&gt;&lt;/p&gt;
&lt;p&gt;For this example, 80%+ will suffice :) (yeah I know I’m lazy).&lt;/p&gt;
&lt;p&gt;Just to explain why 11% is not covered, well this is because of the &lt;strong&gt;if&lt;/strong&gt; &lt;strong&gt;block&lt;/strong&gt; inside the helper that tests if the repository interface parameter is null, it will assign the database BlogRepository if no parameter is passed and in neither of our tests we arranged for the test to enter this &lt;em&gt;If block&lt;/em&gt;. &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Conclusion&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Even if you think your HtmlHelpers has little &lt;strike&gt;or no &lt;/strike&gt;logic you should include them when you unit test your code. &lt;/p&gt;
&lt;p&gt;When writing this post and testing my HtmlHelpers I discovered bugs in my old posts with HtmlHelpers so, as an assignment, I will leave you, dear reader, to unit test my code and find out what bugs I have introduced in my non tested HtmlHelpers from my blogroll archive :).&lt;/p&gt;
&lt;p&gt;UPDATE : My code needed correction. After using the TestInitialize method, although this would prevent my context objects from keeping state from one test method to another because before each test, my context objects would get generated all over again, still, you should also clean after your self with the TestCleanup method.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/unit-testing-your-asp-mvc-htmlhelper-methods/</guid></item><item><title>Adding Watermark to an image using C# in ASP MVC</title><link>http://www.alexpeta.ro/article/adding-watermark-to-an-image-using-C%23-in-asp-mvc/</link><description>&lt;p&gt;Hit and run post.&lt;/p&gt;
&lt;p&gt;I found out a cool class today that helps with adding watermarks images. The class is &lt;a href="http://msdn.microsoft.com/en-us/library/gg538506(v=vs.99)" rel="nofollow" target="_blank"&gt;&lt;em&gt;WebImage&lt;/em&gt;&lt;/a&gt; found in the&lt;em&gt; &lt;a href="http://msdn.microsoft.com/en-us/library/gg547802(v=vs.99)" rel="nofollow" target="_blank"&gt;System.Web.Helpers namespace&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;It has a lot of cool methods that you can use that can help in image processing like : rotate, flip, crop, resize etc and you can find all of that on MSDN but I will focus today on the &lt;strong&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.webimage.addtextwatermark(v=vs.99)" rel="nofollow" target="_blank"&gt;AddTextWatermark method&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Lets begin:&lt;/p&gt;
&lt;p&gt;I have created a folder named “Images” in my root ASP MVC project directory and added the image there. I made sure read/write permissions are available.&lt;/p&gt;
&lt;p&gt;To process the image, here is how my “Home” controller’s Index method looks like :&lt;/p&gt;&lt;pre class="prettyprint"&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace WatermarkImages.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";


            WebImage supermanImage = new WebImage(Server.MapPath("~/Images/superman.jpg"));

            supermanImage.AddTextWatermark("image by alexpeta.ro", "White", 20, "Regular", "Consolas", "Right", "Bottom", 70, 5);

            supermanImage.Save(Server.MapPath("~/Images/newSuperman.jpg"));
            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;Simple in 2 lines of code. First calling the &lt;strong&gt;AddTextWatermark&lt;/strong&gt; to process the image, and the saving it to the disk by calling &lt;strong&gt;Save&lt;/strong&gt; method.&lt;/p&gt;
&lt;p&gt;Now, a new file was added in the “Images” folder named “newSuperman.jpg”. To note, Save() overrides an image with the same name.&lt;/p&gt;
</description><guid>http://www.alexpeta.ro/article/adding-watermark-to-an-image-using-C%23-in-asp-mvc/</guid></item><item><title>Internet Explorer CSS Rotations and Transformation starting with 5.5</title><link>http://www.alexpeta.ro/article/internet-explorer-css-rotations-and-transformation-starting-with-5.5/</link><description>
 &lt;p&gt;Everybody knows that the World Wide Web today is a different place that it was back in IE 6 days. And because of the issues and lack of innovation that Microsoft put in their browser back in the day, its name a became joke that web enthusiasts&amp;nbsp; like to make when speaking about correct standard implementations and still the negative image surrounds the latest versions today although my personal opinion is that IE 9 is a great browser and It still has a long future ahead.&lt;/p&gt;
&lt;p&gt;Todays new stars , CSS3 and HTML5 are on the lips of every designer that wants to impress with his early adoption skill set, but rotations, filters and transformations have been around in IE since the 5.5 version.&lt;/p&gt;
&lt;p&gt;That’s right, you could have rotated , animated, blurred and applied many more filters all back in the day, and I’m going to present just how &lt;strike&gt;simple&lt;/strike&gt; ok it was.&lt;/p&gt;
&lt;p&gt;The idea that stands at the root of rotations for example is the &lt;a href="http://en.wikipedia.org/wiki/Matrix_transformations" rel="nofollow"&gt;Matrix Transformation&lt;/a&gt; (a more complete and &lt;a title="Matrix Transformations" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms536397(v=vs.85).aspx" rel="nofollow"&gt;visual explanation was done by Microsoft here&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Leaving the theory aside, this transformation&amp;nbsp; was integrated in IE using the &lt;a href="http://msdn.microsoft.com/en-us/library/ms533014(v=VS.85).aspx" rel="nofollow"&gt;Matrix Filter&lt;/a&gt;. (on the left side of the documentation you can see a list of all available filters and transformations that you can check out).&lt;/p&gt;
&lt;p&gt;Let's assume i have a class to rotate an image at a specific angle.The CSS filter achieve this is :&lt;/p&gt;&lt;pre class="prettyprint"&gt;.rotation {
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand',
    M11=0.9876883625984192, M12=0.15643446147441864,
    M21= -0.15643446147441864, M22=0.9876883625984192);
}
&lt;/pre&gt;
&lt;p&gt;where M11, M12, M21, M22 represent calculated values like in the Matrix Transformation spec&amp;nbsp; that need to be calculated :&lt;/p&gt;
&lt;p&gt;Lets say we want to rotate clockwise 10 degrees.&lt;/p&gt;
&lt;ol&gt;
&lt;ol&gt;
&lt;li&gt;Transform 10 degrees to &lt;a href="http://en.wikipedia.org/wiki/Radian" rel="nofollow"&gt;Radians&lt;/a&gt;. 
&lt;li&gt;10 degrees = 10 * (PI / 180) , where PI is the constant number &lt;a href="http://en.wikipedia.org/wiki/Pi" rel="nofollow"&gt;PI&lt;/a&gt;, resulting 0.174532925&amp;nbsp; radians. This will represent theta. 
&lt;li&gt;M11 = cos(theta) = cos(0.174532925 ) =&lt;strong&gt; 0.98480775305&lt;/strong&gt; 
&lt;li&gt;M12 = minus sin(theta) = –sin(0.174532925 ) =&amp;nbsp; &lt;strong&gt;-0.173648177&lt;/strong&gt; 
&lt;li&gt;M21 = sin(theta) = sin(0.174532925 ) =&lt;strong&gt; 0.173648177&lt;/strong&gt; 
&lt;li&gt;M22 = M11 = cos(theta) = cos(0.174532925 ) =&lt;strong&gt; 0.98480775305.&lt;/strong&gt;&lt;/li&gt;&lt;/ol&gt;&lt;/ol&gt;
&lt;p&gt;So our 10 degrees matrix filter would become&lt;/p&gt;&lt;pre class="prettyprint"&gt;.tenDegreesRotaion
{
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand',
    M11= 0.98480775305, M12=-0.173648177,
    M21= 0.173648177, M22= 0.98480775305);
}
&lt;/pre&gt;
&lt;p&gt;Go ahead, try in in IE, see for yourself ;).&lt;/p&gt;
&lt;p&gt;Ok, now that you are convinced let me show that there is thankfully an easier way to calculate these transformations. &lt;a href="http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/filters/matrix.htm" rel="nofollow"&gt;MSFT made a special page&lt;/a&gt; where you can input your desired rotation angle and you will get all these coordinates.&lt;/p&gt;
&lt;p&gt;To conclude the post today, and to prove a &lt;a href="http://siderite.blogspot.com/" rel="nofollow"&gt;point to a friend&lt;/a&gt; about what we discussed at a beer yesterday :) IE did actually do good things even back in IE6 time ,&amp;nbsp; and rotations and filters aren’t new things just invented , just old things re-marketed.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/internet-explorer-css-rotations-and-transformation-starting-with-5.5/</guid></item><item><title>Presenting a ASP MVC user notification Widget at RONUA</title><link>http://www.alexpeta.ro/article/presenting-a-asp-mvc-user-notification-widget-at-ronua/</link><description>&lt;p&gt;Today I was one of those days to look&amp;nbsp; back at and feel good about. &lt;/p&gt;
&lt;p&gt;It was my first presentation at &lt;a href="http://ronua.ro/CS/groups/ronua-bucuresti/default.aspx" rel="nofollow"&gt;RONUA&lt;/a&gt; and was a pleasure to present along side my friend &lt;a href="http://blog.andrei.rinea.ro/" rel="nofollow"&gt;Andrei Rinea&lt;/a&gt; who spoke about some new interesting features in SQL Server 2012.&lt;/p&gt;
&lt;p&gt;It all started with a post a &lt;a href="http://www.alexpeta.ro/article/building-a-user-notification-helper/" rel="nofollow"&gt;wrote a while back&lt;/a&gt; about a User Notification helper, which &lt;a href="http://serviciipeweb.ro/iafblog/" rel="nofollow"&gt;Andrei Ignat&lt;/a&gt; considered to be a viable topic to present and I personally thought it would be a good idea to start presenting although I had my doubts about the content its self, in the sense that it’s lacking substance and it should be more complex.&lt;/p&gt;
&lt;p&gt;But I was very happy about the feedback and about that I started presenting. Of course next time I would try be more relaxed, not so up-tight but I guess this will come with experience.&lt;/p&gt;
&lt;p&gt;Keeping this post short, as it’s kind of late and I am tired , here are the goodies:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://notificationswidget.codeplex.com/" rel="nofollow"&gt;Link to the code I had presented on Codeplex&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://notificationswidget.codeplex.com/SourceControl/changeset/changes/18191" rel="nofollow"&gt;Link to my presentation&lt;/a&gt; (word of advice – its made with &lt;a href="http://bartaz.github.com/impress.js/" rel="nofollow"&gt;impress.js&lt;/a&gt;, so open it in Chrome ;)&lt;/li&gt;&lt;/ul&gt;</description><guid>http://www.alexpeta.ro/article/presenting-a-asp-mvc-user-notification-widget-at-ronua/</guid></item><item><title>Leave your comfort zone</title><link>http://www.alexpeta.ro/article/leave-your-comfort-zone</link><description>&lt;p&gt;The topic that I will share with you today is a more of a personal note. I have decided to make a significant change to my life and career and hope to prove my intuition proved me right.
&lt;p&gt;So the elephant in the room is me leaving my 4 year employment at &lt;a href="http://www.oracle.com"&gt;Oracle&lt;/a&gt;. 
&lt;p&gt;Started working out of my second year in college as a business analyst, doing basically business stuff, and after that the later 3 years as a technical consultant, meaning writing PL/SQL code in &lt;a href="http://apex.oracle.com"&gt;Oracle Application Express&lt;/a&gt; framework to build internal used applications.
&lt;p&gt;The corporation &lt;a href="http://en.wikipedia.org/wiki/Mirage"&gt;mirage&lt;/a&gt; got me. I felt back then that I had reached a peak and I have made it big time, no need to be hungry anymore, no need to explore, experiment more and as time passed by I realized that the decision to settle and quiet down was no the best one for me.
&lt;p&gt;I guess you already know the famous Steve Jobs quote from his Stanford speech about “&lt;a href="http://www.youtube.com/watch?v=D1R-jKKp3NA"&gt;stay hungry, stay foolish&lt;/a&gt;”, well I completely resonate with it now.
&lt;p&gt;If after 1 year, or two your job becomes routine as in the sense of nothing really new, interesting, nobody to push things and you to pass your limits then its just burned out wall clock time that you simply will not replace. And this mirage is achieved so well with two corporate “benefits” – working from home when you please to and non strict schedule. 
&lt;p&gt;Sure all these plus the guys at work who sure enough in 4 years some of them really become your friends add up to the "don’t settle for more, this is the best I can do” factor. It isn’t. It’s the same desert mirage we see in the movies where you’re in an oasis (corporation) in the middle of the desert (job market during economic recession) and it’s the best stable thing out there.
&lt;p&gt;Well I can prove that wrong now, tomorrow will be my second day at my new non-corporate life and from what I can say, things are looking really nice from where I’m viewing them and changing the comfort zone was one those life changing decisions that I really feel good about.
</description><guid>http://www.alexpeta.ro/article/leave-your-comfort-zone</guid></item><item><title>Recursive SQL in TSQL and Oracle</title><link>http://www.alexpeta.ro/article/recursive-sql-in-tsql-and-oracle/</link><description>&lt;blockquote&gt;
&lt;p&gt;The problem&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Recently I faced the following report task : to produce&amp;nbsp; a simple report that had 2 columns the count of subscribers per day &lt;em&gt;for each day&lt;/em&gt; and the day in which the subscribers registered to be able to see a trend/the evolution of subscriptions, this in the context of MS SQL Server 2008.&lt;/p&gt;
&lt;p&gt;Table name : [dbo].Subscribers&lt;/p&gt;
&lt;p&gt;Columns : &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;SubsriberId (PK, int) 
&lt;li&gt;Email (varchar(200)) 
&lt;li&gt;CreatedDate (datetime)&lt;br&gt;&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;The data will contain email addresses and the date when the insert took place. If no person subscribed in a day, there simply would not be any records with CreatedDate set to that specific day, but my reporting would have to show that day with 0(zero) subscribers.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The solution (at least my solution ;) )&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;I would need 2 tables :&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;(T1) the first would be a table with all the days in a month, starting with the first day of the first month of the first record in my Subscribers table going to this present day – this would have had to be generated. 
&lt;li&gt;(T2) the second is based on the “Subscribers” data but the data would be aggregated with count(*) for each day. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;The final thing would be an &lt;strong&gt;left outer join &lt;/strong&gt;(T1) on (T2).&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The TSQL way – stored procedure&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;In a newbie at TSQL, but I have experience with Oracle SQL, so the thinking was in place, I had to find out what syntax would help me achieve this.&lt;/p&gt;&lt;pre class="prettyprint"&gt;GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SubscribersByDay]
AS
BEGIN

SET NOCOUNT ON;

DECLARE @sd DATETIME, 
        @ed DATETIME;

--first day of the first month of the first subscriber
SELECT @sd = DATEADD(DAY, -(DAY(mn.minimum) - 1), mn.minimum)
  FROM (SELECT MIN(s.CreatedDate) minimum
          FROM [dbo].Subscriber s) mn;

--end date = today
SELECT @ed = GETDATE();

--this is the recursive part  and then left outer joining
WITH cte AS (
  SELECT cast(floor(cast(@sd as float)) as datetime) as dt
  UNION ALL
  SELECT dt + 1 FROM CTE
   WHERE dt + 1 &amp;lt;= @ed
)
SELECT cte.dt as "CalendarDate",
       ISNULL(grp.subscriber_no,0) as "SubscriberCount"
 FROM cte
LEFT OUTER JOIN (SELECT count(s.email) subscriber_no,
                        cast(floor(cast(s.CreatedDate as float)) as datetime) created
                   FROM [dbo].Subscriber s
               GROUP BY cast(floor(cast(s.CreatedDate as float)) as datetime)) grp
 ON cte.dt = grp.created
ORDER BY  dt DESC;

END

&lt;/pre&gt;
&lt;p&gt;I wanted to compare thee above code to what I would write in Oracle for the same problem, just as a character typing/syntax/code fluidity example (not anything performance-wise here!) and using the built-in “connect by” clause.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Oracle way – using “connect by” clause and transformations&lt;br&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;SELECT  t1.d subscribed_day,
        NVL(t2.subscriber_no,0) nr
FROM
(       
SELECT trunc(sysdate-level+1) d
             FROM dual
CONNECT BY level &amp;lt;= (SELECT trunc(sysdate)-to_date('01-'||(to_char(min(createddate),'MON-YYYY')),'DD-MON-YYYY')+1
                                             FROM Subscriber)
) t1 
   LEFT OUTER JOIN 
(
SELECT count(s.email) subscriber_no,
                  trunc(s.CreatedDate) d
             FROM Subscriber s
         GROUP BY trunc(s.CreatedDate)
)t2 
   ON t1.d = t2.d
ORDER BY t1.d desc
&lt;/pre&gt;
&lt;p&gt;In Oracle, to generate the days table (T1) I’m using the “connect by” clause and leveraging “level” pseudo column that will generate levels based on the number of days between the first day of the first month of the first Subscriber and curent date. &lt;/p&gt;
&lt;p&gt;The +1 there is to incorporate the current day&amp;nbsp; as without it would start with level=1, sysdate-1 , meaning yesterday.&lt;/p&gt;
&lt;p&gt;The end result is displayed like :&lt;/p&gt;
&lt;table style="width: 200px" align="center"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;th id="SUBSCRIBED_DAY"&gt;SUBSCRIBED_DAY&lt;/th&gt;
&lt;th id="NR"&gt;NR&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/24/2012&lt;/td&gt;
&lt;td headers="NR"&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/23/2012&lt;/td&gt;
&lt;td headers="NR"&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/22/2012&lt;/td&gt;
&lt;td headers="NR"&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/21/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/20/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/19/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/18/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/17/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/16/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/15/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/14/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/13/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/12/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/11/2012&lt;/td&gt;
&lt;td headers="NR"&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/10/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/09/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/08/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/07/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/06/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/05/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/04/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/03/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/02/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;
&lt;td headers="SUBSCRIBED_DAY"&gt;06/01/2012&lt;/td&gt;
&lt;td headers="NR"&gt;0&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;.... 
&lt;p&gt;As you can tell for yourself , the “connect by” clause offers very much flexibility when it comes to generating tables. One other example that comes to mind right now and that could be very useful was regarding generation of sales people targets based on months and indexed with a percentage.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/recursive-sql-in-tsql-and-oracle/</guid></item><item><title>Building A User Notification Helper</title><link>http://www.alexpeta.ro/article/building-a-user-notification-helper/</link><description>&lt;p&gt;Yet another quick post about something in my opinion useful that I had to build for a project that I’m currently working on.&lt;/p&gt;
&lt;p&gt;The idea is that when navigating from Method to Method&amp;nbsp; [speaking about ASP MVC here] i.e. after going to the Create ActionMethod and submitting the page , the user is redirected to the Index() list to see his newly created item, and he should be notified if his actions have resulted into something.&lt;/p&gt;
&lt;p&gt;I’ll write the code now, and comment it as we go along&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;quote&gt;1. The CSS – everything is better with &lt;em&gt;style&lt;/em&gt; and &lt;em&gt;class&lt;/em&gt;&lt;/quote&gt; &lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;.alert {
    background-color: #FCF8E3;
    border: 1px solid #FBEED5;
    border-radius: 4px 4px 4px 4px;
    color: #C09853;
    margin-bottom: 18px;
    padding: 8px 35px 8px 14px;
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
    margin-left:auto;
    margin-right:auto;
}

/* Error */
.alert-error {
    background-color: #F2DEDE;
    border-color: #EED3D7;
    color: #B94A48;
}


a.close {
    background: none repeat scroll 0 0 transparent;
    border: 0 none;
    cursor: pointer;
    padding: 0;
    text-decoration:none;
}
.close {
    color: #000000;
    float: right;
    font-size: 20px;
    font-weight: bold;
    line-height: 18px;
    opacity: 0.2;
    text-shadow: 0 1px 0 #FFFFFF;
}

/* Success */
.alert-success {
    background-color: #DFF0D8;
    border-color: #D6E9C6;
    color: #468847;
}


/* Info */
.alert-info {
    background-color: #D9EDF7;
    border-color: #BCE8F1;
    color: #3A87AD;
}
&lt;/pre&gt;
&lt;p&gt;Just to be fair here , I took the liberty of looking at the CSS code from Twitter Bootstrap notifications &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="$wlEmoticon-winkingsmile[2].png"&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;2. The &lt;strong&gt;UserNotification&lt;/strong&gt; class &amp;amp; &lt;strong&gt;NotificationType&lt;/strong&gt; enum&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;public enum NotificationType
    {
        Error   = 1,
        Success = 2,
        Info    = 3
    }

    public class UserNotification
    {
        public string Message { get; private set; }
        public string Scream { get; private set; }
        public string Type { get; private set; }
        public ushort AutoCloseTime { get; private set; }
        public ushort Width { get; private set; }

        public UserNotification(string msg, NotificationType msgType, ushort autoClose = 2200,ushort width = 300)
        {
            Message = msg;
            AutoClose = autoClose;
            switch (msgType)
            {
                case NotificationType.Error:
                    Scream = "Oh snap! ";
                    Type = NotificationType.Error.ToString().ToLower();
                    break;
                case NotificationType.Info:
                    Scream = "Heads up!";
                    Type = NotificationType.Info.ToString().ToLower();
                    break;
                case NotificationType.Success: 
                    Scream = "Well done!";
                    Type = NotificationType.Success.ToString().ToLower();
                    break;
            }
            Width = width;
        }

    }
&lt;/pre&gt;
&lt;p&gt;Here is our UserNotification class which we will use to pass to our HtmlHelper method. Its straight-forward.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;3. Finally , our HtmlHelper&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt; public static class DisplayHelpers
    {
        public static MvcHtmlString UserNotification(this HtmlHelper helper, UserNotification notification)
        {
            StringBuilder sb = new StringBuilder();
            if (notification != null)
            {
                sb.Append(@"&amp;lt;script&amp;gt;function closeMsg(){try { document.getElementById('msg-container').style.display='none'; } catch(err){}}&amp;lt;/script&amp;gt;");
                sb.Append(string.Format(@"&amp;lt;div class=""alert alert-{0}"" id=""msg-container"" style=""width:{1}px;""&amp;gt;
                                            &amp;lt;a class=""close"" href=""javascript:void(0);"" onclick=""closeMsg()""&amp;gt;×&amp;lt;/a&amp;gt;
                                            &amp;lt;strong&amp;gt;{2}&amp;lt;/strong&amp;gt; {3}
                                          &amp;lt;/div&amp;gt;
                         ", notification.Type,notification.Width,notification.Scream, notification.Message));
                sb.Append(@"&amp;lt;script&amp;gt;(function () {var t = setTimeout(""closeMsg()"", "+notification.AutoCloseTime+");})()&amp;lt;/script&amp;gt;");

            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }
&lt;/pre&gt;
&lt;p&gt;Not much happening here either. Besides the Html container with the specific class depending on the type of notification (Success, Error, Info)&amp;nbsp; I’ve written 2 small Javascript blocks : the upper one is for when the user chooses to close the notification manually,&amp;nbsp; pressing the “X” anchor, and the second block is the auto-closing block, that will remove the notification from being displayed after the give milliseconds.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;4. How to use it&lt;/p&gt;&lt;/blockquote&gt;&lt;pre class="prettyprint"&gt;public ActionResult Index()
        {
            ViewBag.message = new UserNotification("Welcome! Here is your first notification! This message will selfdistruct in about 4 seconds ;)", NotificationType.Info, 4000);
            return View();
        }
&lt;/pre&gt;
&lt;p&gt;Calling the Helper:&lt;/p&gt;&lt;pre class="prettyprint"&gt;@Html.UserNotification((UserNotificationAspMvc.Models.UserNotification)ViewBag.message)
&lt;/pre&gt;
&lt;p&gt;Things that I will update at a later time : &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Implement a message Queue 
&lt;li&gt;Messages should have possibility be displayed &lt;em&gt;“position : static”&lt;/em&gt;&amp;nbsp; &lt;li&gt;GROWL look and feel – maybe animations. 
&lt;li&gt;A better usage would be returning UserNotifications from the Repository methods like Create/Delete instead of void.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And the goodies for baring with me&amp;nbsp; : &lt;font size="5"&gt;&lt;a title="UserNotification Visual Studio Solution" href="http://www.alexpeta.ro/Content/Download/UserNotificationAspMvc.zip" rel="no-follow"&gt;download the solution here&lt;/a&gt;.&lt;/font&gt;&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/building-a-user-notification-helper/</guid></item><item><title>Simple Thousands HtmlHelper for Big Numbers</title><link>http://www.alexpeta.ro/article/simple-thousands-htmlhelper-for-big-numbers/</link><description>&lt;p&gt;Last night ~ 1:1o AM, just before shutting down any activity for today wanted to check how my blog is doing .&lt;/p&gt;
&lt;p&gt;And , not to brag about it here, but the activity and view numbers are reaching for the thousand mark [smug face on :) ], but unfortunately I didn’t see this coming too soon when I sketched out the design and they are making a mess of things.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Fix – a quick extension method for &lt;strong&gt;Int&lt;/strong&gt; that will make numbers like 3453 display like 3.4K&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;To the code:&lt;/p&gt;&lt;pre class="prettyprint"&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AlexPeta_2.Helpers
{
    public static class ThousandHelper
    {
        public static string ThousandK(this int helper)
        {
            double divisor = 0D;
            string letter = string.Empty;

            if (helper &gt;= Math.Pow(10D, 6D))
            {
                divisor =6D;
                letter = "M";
            }
            else if (helper &gt; Math.Pow(10D, 3D) &amp;&amp; helper &lt; Math.Pow(10D, 6D))
            {
                divisor = 3D;
                letter = "K";
            }

            if (divisor &gt; 0D)
            {
                double integerPart = Math.Floor(Convert.ToDouble(helper) / Math.Pow(10D, divisor));
                double reminderPart = Math.Floor(((Convert.ToDouble(helper) / Math.Pow(10D, divisor)) - integerPart) * 10);
                return string.Format("{0}.{1}{2}", integerPart, reminderPart, letter);
            }
            else
            {
                return helper.ToString();
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;And to use this, its simple as calling :&lt;/p&gt;&lt;pre class="prettyprint"&gt;int nr = 34566;
nr.ThousandK();  &lt;/pre&gt;
&lt;p&gt;I chose the method above to truncate a &lt;strong&gt;double&lt;/strong&gt; type because calling double.ToString("0.00");&amp;nbsp; &lt;a href="http://stackoverflow.com/questions/1426857/truncate-number-of-digit-of-double-value-in-c-sharp" rel="no-follow" target="_blank"&gt;may return an unexpected result.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;UPDATE&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Regarding what &lt;a href="http://blog.andrei.rinea.ro/" target="_blank"&gt;Andrei&lt;/a&gt; has suggested, I have updated the code to cope with millions. Looking forward to seeing the number in action :).&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/simple-thousands-htmlhelper-for-big-numbers/</guid></item><item><title>Y U No test speed code with BenchmarkNET</title><link>http://www.alexpeta.ro/article/y-u-no-test-speed-code-with-benchmarknet/</link><description>&lt;p&gt;The question for today is “What do you do when you need to test code speed? “. You could start the old fashioned way, adding DateTime variables all over the place and make the difference between them.&lt;/p&gt;
&lt;p&gt;But there is something out there much more flexible, a tool named "&lt;strong&gt;&lt;a href="http://benchmarknet.codeplex.com/" rel="nofollow"&gt;Benchmark.NET&lt;/a&gt;”, &lt;/strong&gt;a open source project&lt;strong&gt; &lt;/strong&gt;written by my friend &lt;a href="http://blog.andrei.rinea.ro/"  rel="nofollow"&gt;Andrei Rinea&lt;/a&gt;. You can read the whole blog post &lt;a href="http://blog.andrei.rinea.ro/2012/03/15/benchmark-code-blocks-easy/"  rel="nofollow"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;To write a quick example on this I will use my old code written back in December &lt;a href="http://www.alexpeta.ro/article/secret-santa-random-list-generator-using-csharp-.net"&gt;for our SecretSanta extraction&lt;/a&gt;. Its not the most complex piece of code to test, but its still a valid example because if you take a look at it you will notice that the &lt;a href="http://en.wikipedia.org/wiki/Big_O_notation"  rel="nofollow"&gt;algorithm complexity&lt;/a&gt; is variable.&lt;/p&gt;
&lt;p&gt;I will make a couple of changes to my old code. First , I will start by using a SecretSanta class rather then writing the whole piece of code in a Console Application Main method:&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
using System;&lt;br/&gt;using System.Collections.Generic;&lt;br/&gt;using System.Linq;&lt;br/&gt;using System.Text;&lt;br/&gt;&lt;br/&gt;using BenchmarkNet;&lt;br/&gt;&lt;br/&gt;namespace SecretSantaWithBenchmark&lt;br/&gt;{&lt;br/&gt;    public class SecretSanta&lt;br/&gt;    {&lt;br/&gt;        private List&amp;lt;string&amp;gt; peopleToMatch {get;set;}&lt;br/&gt;        private List&amp;lt;string&amp;gt; copyOfPeople { get; set; }&lt;br/&gt;        private List&amp;lt;int&amp;gt; excludedPosibilities { get; set; }&lt;br/&gt;&lt;br/&gt;        public Dictionary&amp;lt;string ,string &amp;gt; Results {get;set;}&lt;br/&gt;&lt;br/&gt;        public SecretSanta(List&amp;lt;string&amp;gt; users)&lt;br/&gt;        {&lt;br/&gt;            peopleToMatch = users;&lt;br/&gt;            copyOfPeople = users;&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        [BenchmarkedThis(BenchmarkNet.BenchmarkType.Sequential,&amp;quot;25-MAR-2012&amp;quot;,1,&amp;quot;00:00:00.0014501&amp;quot;,0,&amp;quot;Initial test&amp;quot;)]&lt;br/&gt;        public void Start()&lt;br/&gt;        {&lt;br/&gt;            do&lt;br/&gt;            {&lt;br/&gt;                Results = new Dictionary&amp;lt;string, string&amp;gt;();&lt;br/&gt;                excludedPosibilities = new List&amp;lt;int&amp;gt;();&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;                foreach (string person in peopleToMatch)&lt;br/&gt;                {&lt;br/&gt;                    var personPosibilites = GetPosibilities(person);&lt;br/&gt;                    var rand = (new Random()).Next(0, personPosibilites.Count);&lt;br/&gt;                    Results.Add(person, copyOfPeople[personPosibilites[rand]]);&lt;br/&gt;                    excludedPosibilities.Add(personPosibilites[rand]);&lt;br/&gt;                }&lt;br/&gt;            }&lt;br/&gt;            while (!TestResults());&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;&lt;br/&gt;        private List&amp;lt;int&amp;gt; GetPosibilities(string current_check)&lt;br/&gt;        {&lt;br/&gt;            List&amp;lt;int&amp;gt; return_posibilities = new List&amp;lt;int&amp;gt;();&lt;br/&gt;            for (int i = 0; i &amp;amp;lt; copyOfPeople.Count; i++)&lt;br/&gt;            {&lt;br/&gt;                if (copyOfPeople[i] != current_check &amp;&amp; !excludedPosibilities.Contains(i))&lt;br/&gt;                    return_posibilities.Add(i);&lt;br/&gt;            }&lt;br/&gt;            return return_posibilities;&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        private bool TestResults()&lt;br/&gt;        {&lt;br/&gt;            foreach (string person in peopleToMatch)&lt;br/&gt;            {&lt;br/&gt;                if (Results[person] == person)&lt;br/&gt;                    return false;&lt;br/&gt;            }&lt;br/&gt;            return true;&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;        public override string ToString()&lt;br/&gt;        {&lt;br/&gt;            StringBuilder sb = new StringBuilder();&lt;br/&gt;            foreach(var person in Results.Keys)&lt;br/&gt;            {&lt;br/&gt;                sb.Append(string.Format(&amp;quot;{0} will get a present for {1}&amp;quot;,person.ToUpper(),Results[person].ToUpper())).Append(Environment.NewLine);&lt;br/&gt;            }&lt;br/&gt;            return sb.ToString();&lt;br/&gt;        }&lt;br/&gt;&lt;br/&gt;    }&lt;br/&gt;}
&lt;/pre&gt;
&lt;p&gt;The logic is mostly the same,&amp;nbsp; no huge difference in the logic.&lt;/p&gt;
&lt;p&gt;The code testing will be done in our Main method :&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
using System;&lt;br/&gt;using System.Collections.Generic;&lt;br/&gt;using System.Linq;&lt;br/&gt;using System.Text;&lt;br/&gt;&lt;br/&gt;using BenchmarkNet;&lt;br/&gt;&lt;br/&gt;namespace SecretSantaWithBenchmark&lt;br/&gt;{&lt;br/&gt;    class Program&lt;br/&gt;    {&lt;br/&gt;        static void Main(string[] args)&lt;br/&gt;        {&lt;br/&gt;            List&amp;lt;string&amp;gt; data = new List&amp;lt;string&amp;gt; { &amp;quot;claudiu@email.com&amp;quot;,&amp;quot;raluca@email.com&amp;quot;,&lt;br/&gt;                                            &amp;quot;alex@email.com&amp;quot;,&amp;quot;madalina@email.com&amp;quot;,&lt;br/&gt;                                            &amp;quot;diana@email.com&amp;quot;,&amp;quot;mihaela@email.com&amp;quot;,&lt;br/&gt;                                            &amp;quot;georgeta@email.com&amp;quot; ,&amp;quot;maria@email.com&amp;quot; ,&lt;br/&gt;                                            &amp;quot;adriana@email.com&amp;quot;,&amp;quot;valentina@email.com&amp;quot; ,&lt;br/&gt;                                            &amp;quot;iulia@email.com&amp;quot;,&amp;quot;luciana@email.com&amp;quot; ,&lt;br/&gt;                                            &amp;quot;elena@email.com&amp;quot;,&amp;quot;amalia@email.com&amp;quot; ,&amp;quot;vava@email.com&amp;quot; };&lt;br/&gt;&lt;br/&gt;            SecretSanta s1 = new SecretSanta(data);&lt;br/&gt;&lt;br/&gt;            var b1 = Benchmark.Sequential(() =&amp;amp;gt; s1.Start() );&lt;br/&gt;&lt;br/&gt;            Console.WriteLine(&amp;quot;Santa results:&amp;quot;+Environment.NewLine);&lt;br/&gt;            Console.WriteLine(&amp;quot;-----------------------------&amp;quot;);&lt;br/&gt;            Console.WriteLine(s1.ToString() + Environment.NewLine);&lt;br/&gt;            Console.WriteLine(&amp;quot;-----------------------------&amp;quot;);&lt;br/&gt;            Console.WriteLine(b1.ToString());&lt;br/&gt;&lt;br/&gt;        }&lt;br/&gt;    }&lt;br/&gt;}
&lt;/pre&gt;
&lt;p&gt;All I needed to to in order to test the Start method of the SecretSanta class was to call the Benchmark.Sequential() method, that accepts a Action() and optional number of iterations the default being 1.&lt;/p&gt;
&lt;p&gt;Additionally, if you wish to add the test results to the method, you can do this via the BenchmarkThis attribute, and can also include a SVN commit number.&lt;/p&gt;
&lt;p&gt;And finally you can &lt;a href="http://www.alexpeta.ro/Content/Download/SecretSantaWithBenchmark.zip" rel="nofollow"&gt;download the Visual Studion solution here.&lt;/a&gt;&lt;/p&gt;
</description><guid>http://www.alexpeta.ro/article/y-u-no-test-speed-code-with-benchmarknet/</guid></item><item><title>Entity Framework and DBO Schema</title><link>http://www.alexpeta.ro/article/entity-framework-and-dbo-schema/</link><description>&lt;p&gt;Its been a while since I have written a new post. My attention has been recently on Entity Framework with Code First.&lt;/p&gt;
&lt;p&gt;As there is nothing better then learning through the power of example, i decided to redesign my blog both on the “outside” but also on the “inside”.&lt;/p&gt;
&lt;p&gt;I must admit, it was tricky. When you have always though that building an application starts with designing the database , the data structures and the table mappings, and to change all of that to just you model classes and leave all the “under the hood” stuff for EF’s “free will” was a scary thing.&lt;/p&gt;
&lt;p&gt;After building a so called “alpha” version of the blog v2 (this one that you are viewing right now), enthusiasm got the best of me and decided to publish it.&lt;/p&gt;
&lt;p&gt;Upon trying this i realized a couple of things.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;I did not use a connection string declaration in my Web.config file for the Database. This is translated to Entity Framework creating a database for me in my SQL Express instance. 
&lt;li&gt;Because i &lt;strike&gt;wouldn’t&lt;/strike&gt;&amp;nbsp; didn’t make any configurations to my models using Data Annotations or Fluent API, EF used the default [DBO] database schema.&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;I exported the database objects from my SQL Express instance and checked the code.&lt;/p&gt;
&lt;p&gt;My hosting schema user is “administrator” so i realized that i had to change the schema when it was time to move to production.&lt;/p&gt;
&lt;p&gt;It was as simple as FIND and REPLACE in Notepad ++ [dbo] with [administrator].&amp;nbsp; All the scripts ran smooth against the production server, but when&amp;nbsp; i opened up the blog url FAIL: &lt;strong&gt;Invalid object name “[dbo].[Articles]”.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;It didn’t suffice for me to add the Connection string to point to this schema after creating the site, nor could i change EF’s to point to the other schema without dropping and recreating the models. &lt;/p&gt;
&lt;p&gt;After searching &lt;a href="http://stackoverflow.com/questions/9341922/change-entity-framework-database-schema-map-after-using-code-first" rel="nofollow"&gt;StackOverflow for an answer&lt;/a&gt; i got it : always change your Schema via Data Annotations or Fluent API to suit your needs!!&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/entity-framework-and-dbo-schema/</guid></item><item><title>Building a Tracking Pixel in ASP MVC</title><link>http://www.alexpeta.ro/article/building-a-tracking-pixel-in-asp-mvc/</link><description>&lt;p&gt;Maybe you've heard about a &lt;a href="http://en.wikipedia.org/wiki/Web_bug"&gt;Tracking Pixel &lt;/a&gt;before , or not , but surely you've rendered one without knowing.&lt;/p&gt;
&lt;p&gt;The best way to keep tracks of views either on web pages, or even better&amp;nbsp; on emails is by exploiting a nice web bug : the tracking pixel : Wiki Pedia a &lt;a href="http://en.wikipedia.org/wiki/Email_tracking"&gt;better definition &lt;/a&gt;that i can give.&lt;/p&gt;
&lt;p&gt;When a user receives an email the client only downloads the email header at first.&amp;nbsp; After the user clicks to read the whole content of the email only then the full content will be displayed . This means that this is the moment when all the GET requests for images appear.&lt;/p&gt;
&lt;p&gt;As its name implies it, a tracking pixel is a 1x1 pixel image, but the link for it si provided by a server GET request that before respoding with image stream first does the counting logic.&lt;/p&gt;
&lt;p&gt;In ASP MVC this can be translated to a &lt;strong&gt;Action Method&lt;/strong&gt;, that returns &lt;strong&gt;FileStreamResult&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;I have build a very basic project just for the sake of example using a small Superman logo.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;Track&lt;/strong&gt; action method is the following:&lt;/p&gt;&lt;pre class="prettyprint"&gt;public FileStreamResult Track(int? id)
{                     
  //our image stored in the Img folder    
  var image = new Bitmap(Server.MapPath(@"\Img\superman.gif"));

  //the counting logic : for this example i will write a file
  //in the image folder for each view
  StreamWriter w = new StreamWriter(Server.MapPath(@"\Img\") + id + ".txt");
  w.Close();

  //create a new memory stream
  MemoryStream stream = new MemoryStream();

  //save the image in the stream
  image.Save(stream, ImageFormat.Gif);

  //This will rewind the stream to the beginning of the saved image.
  //Otherwise the stream will be positioned at
  //the end of the stream and nothing is sent to the receiver.
  stream.Seek(0, SeekOrigin.Begin);

  //return the filestreamresult
   return new FileStreamResult(stream, "image/gif"); 
}
&lt;/pre&gt;
&lt;p&gt;This is very usefull if you have the requirement for metrics on newsletters/email for any given project.&lt;/p&gt;
&lt;p&gt;The whole purpose of what we wrote about here is to get a link&amp;nbsp; that we will use as the src attribute for a img tag in a newsletter for example.&lt;/p&gt;
&lt;p&gt;i.e. &amp;lt;img src="http://localhost:1234/home/track/1345" alt="" /&amp;gt;&lt;/p&gt;
&lt;p&gt;This is translated to when the client sends a GET to the server via this link, it will trigger the counting logic and then it servers the tracking pixel.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;UPDATE :&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;As &lt;a href="http://msprogrammer.serviciipeweb.ro/" rel="no-follow" alt="Andrei Ignat"&gt;Andrei&lt;/a&gt; suggested , I could have made a HTML helper method to call the pixel generation instead of writing it each time.&lt;/p&gt;
&lt;p&gt;Let me do this now :&lt;/p&gt;
&lt;p&gt;A HML helper is basically a extension method of the HtmlHelper class , and an extension method is basically a static method in a static class that has the first parameter marked with "&lt;strong&gt;this&lt;/strong&gt;” keyword and the class that we wish to add our method to followed by any other additional parameters:&lt;/p&gt;&lt;pre class="prettyprint"&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TrackingPixel.Models
{
    public static class TrackingPixelHelper
    {
        public static MvcHtmlString TrackingPixel(this HtmlHelper helper, int idToTrack)
        {
            TagBuilder img = new TagBuilder("img");
            img.Attributes.Add(new KeyValuePair&lt;string string ,&gt;("alt", "."));
            img.Attributes.Add(new KeyValuePair&lt;string string ,&gt;("src", string.Format("/home/track/{0}", idToTrack.ToString())));
            return MvcHtmlString.Create(img.ToString());
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;As you can probably see I have used my Models folder to create my new class. I could have used any new folder, but in order for me to use the helper, I have to include it 1)either in my View() making use of the “using” directive like :&lt;/p&gt;&lt;pre class="prettyprint"&gt;@using TrackingPixel.Models&lt;/pre&gt;
&lt;p&gt;2) or insert it in my Web.config:&lt;/p&gt;&lt;pre class="prettyprint"&gt;&amp;lt;namespaces&amp;gt; …..&amp;nbsp;&amp;nbsp; &amp;lt;add namespace="TrackingPixel.Models" /&amp;gt; … &amp;lt;/namespaces&lt;br&gt;&lt;/pre&gt;
&lt;p&gt;and finally , we are able to use it :&lt;/p&gt;&lt;pre class="prettyprint"&gt;@Html.TrackingPixel(2345)&lt;/pre&gt;
&lt;p&gt;You can &lt;a href="http://www.alexpeta.ro/Content/Download/TrackingPixel.zip"&gt;download the update VS Solution here.&lt;/a&gt;&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/building-a-tracking-pixel-in-asp-mvc/</guid></item><item><title>Thinking On New Years Resolution vs Past Years Achievements</title><link>http://www.alexpeta.ro/article/thinking-on-new-years-resolution-vs-past-years-achievements/</link><description>&lt;p&gt;   2012 is allmost here!&lt;/p&gt;  &lt;p&gt;   As we are reaching the finish line for this year,&amp;nbsp; its time to take a look back and reflect, summarize and learn from the passing year and step in 2012 with&amp;nbsp;the whole 2011&amp;#39;s worth of wisdom.&lt;/p&gt;  &lt;p&gt;   &lt;a href="http://en.wikipedia.org/wiki/2011"&gt;Globally , a lot of things happened in 2011&lt;/a&gt;, and for me personally 2011&amp;nbsp;it has been a good year.&lt;/p&gt;  &lt;p&gt;   From a Programmers point of view, 2011 ment for me :&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;    Starting learning ASP MVC&lt;/li&gt;   &lt;li&gt;    Reading a couple of .NET books&lt;/li&gt;   &lt;li&gt;    Finishing freelance work on&amp;nbsp; : &lt;a href="http://mp-books.ru"&gt;http://mp-books.ru&lt;/a&gt;&lt;/li&gt;   &lt;li&gt;    Fianlly starting work on &lt;a href="http://www.alexpeta.ro"&gt;http://www.alexpeta.ro&lt;/a&gt;&lt;/li&gt;   &lt;li&gt;    Creating my own small blog CMS as part of the learning ASP MVC process [ psssst its this site that you are using right now]&lt;/li&gt;   &lt;li&gt;    Blogged a litte&lt;/li&gt;   &lt;li&gt;    Did some interesting &lt;a href="mailto:projects@work"&gt;proje  cts@work&lt;/a&gt;&lt;/li&gt;   &lt;li&gt;    &lt;a href="http://twitter.com/alexpeta"&gt;Started Twitting&lt;/a&gt;&lt;/li&gt;   &lt;li&gt;    Went to a couple of .NET conferences&lt;/li&gt;  &lt;/ul&gt;  &lt;p&gt;   but it wasn&amp;#39;t&amp;nbsp;all just about programming :&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;    Travelled a bit : Greece - Thassos&lt;/li&gt;   &lt;li&gt;    Met a lot of interesting and smart people who became my friends&lt;/li&gt;   &lt;li&gt;    Worked out - as much as&amp;nbsp;i could keep up with the schedule&lt;/li&gt;   &lt;li&gt;    Tryied to party as much as i could ;)&lt;/li&gt;   &lt;li&gt;    generally enjoyed myself&lt;/li&gt;  &lt;/ul&gt;  &lt;p&gt;   These are just the first things that popped into my head.&lt;/p&gt;  &lt;p&gt;   You can sum all these up&amp;nbsp;in just a couple of rows, and you start thinking that maybe you should had done more....&lt;/p&gt;  &lt;p&gt;   Though one to beat, but im sure ill do the very best to top it from every point of view, and you should do the same too!&lt;/p&gt;  &lt;p&gt;   Wish you all only the best in the new year to come, may all your wishes come true, may you live to the fullest and just enjoy the ride!&lt;/p&gt;  &lt;p&gt;   &amp;nbsp;&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/thinking-on-new-years-resolution-vs-past-years-achievements/</guid></item><item><title>Secret Santa Random List Generator using CSharp .Net</title><link>http://www.alexpeta.ro/article/secret-santa-random-list-generator-using-csharp-.net/</link><description>&lt;p&gt;   As Christmas is just around the courner, the corporate life is organizing, as we do every year, &lt;a href="http://en.wikipedia.org/wiki/Secret_Santa"&gt;Secret Santa&lt;/a&gt;. We are beeing each others Santa&amp;#39;s by write names of a piece of paper, put them in a bowl, and take turns in picking one ticket, and then buying the selected persons a present withing a given budget or course (this operation is repeaded if you pick your name up).&lt;/p&gt;  &lt;p&gt;   Now today, because our team is spread across 2 diffrent buildings, us techies from the bunch decided to skip the trip over and build a web app to do the lottery for us.&lt;/p&gt;  &lt;p&gt;   The app has an interface for WishLists with an underlying table that contains&amp;nbsp;contact info, pic url, and present details&amp;nbsp;and on the day we decide to run the lottery app, it will generate pairs of 2 people and send them to each &amp;quot;Santa&amp;quot; with the designated person&amp;#39;s pic and wishlist. Of course a lot of ideas flowed and it prooved out to be a lot of fun.&lt;/p&gt;  &lt;p&gt;   This was build using &lt;a href="http://apex.oracle.com/i/index.html"&gt;Oracle Application Express 4.1&lt;/a&gt;, but hey, i just wanted to do the same logic in C#.NET 3.5&lt;/p&gt;  &lt;p&gt;   For this exercise i&amp;#39;ll be using a Console Application , and List&amp;lt;String&amp;gt; with the emails as my data source.&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
class Program      
{            
   
   static bool TestMatch(List&lt;string[]&gt; toTest)
   {
     foreach (string[] p in toTest)
     {
        if (p[0] == p[1])  
        return false; 
     }
     
     return true;    
   }

   static void Main(string[] args) 
   {
     Stopwatch w = new Stopwatch(); 
     List&lt;string&gt; all =  new List&lt;string&gt; { "claudiu@email.com","raluca@email.com",
                                            "alex@email.com","madalina@email.com",
                                            "diana@email.com","mihaela@email.com",
                                            "georgeta@email.com" ,"maria@email.com" ,
                                            "adriana@email.com","valentina@email.com" ,
                                            "iulia@email.com","luciana@email.com" ,
                                            "elena@email.com","amalia@email.com" ,"vava@email.com" };
     List&lt;string[]&gt; theMatchup = new List&lt;string[]&gt;();           
     do{
           List&lt;string&gt; posibilities = all.ToList();
         theMatchup.Clear();
         Random r = new Random();
         foreach (string person in all)
         {
           if (posibilities.Count &gt; 0)
           { 
              int generated = 0;
              do{
                  generated = r.Next(0, posibilities.Count); 
                } while (person == posibilities[generated]);
            
            theMatchup.Add(new string[] { person, posibilities[generated] });
            posibilities.Remove(posibilities[generated]);
           } 
          } 
        }while (!TestMatch(theMatchup));
        
        foreach (string[] p in theMatchup)
        { 
          Console.WriteLine("{0} ---------------&gt; {1}",p[0],p[1]); 
        }
        
        Console.WriteLine(TestMatch(theMatchup));
        
        w.Stop();
        Console.WriteLine("Elapsed : {0}",w.Elapsed);
     }      
}  
 &lt;/pre&gt;
 &lt;p&gt;   So first of all we will need something to store our results :List of string[] that will act as our pair holder:&lt;/p&gt;
 &lt;pre class="prettyprint"&gt;
 List&lt;string[]&gt; theMatchup = new List&lt;string[]&gt;(); &lt;/pre&gt;
 &lt;p&gt;   After creating a duplicate list, we&amp;#39;ll use Random r to generate a number for us to &amp;quot;pop&amp;quot; from the auxiliary list,but beeing aware that the values musn&amp;#39;t match :&lt;/p&gt;
 &lt;pre class="prettyprint"&gt;
   List&lt;string&gt; posibilities = all.ToList();
   
   theMatchup.Clear();
   
   Random r = new Random();
   foreach (string person in all)
   {
     if (posibilities.Count &gt; 0)
    {
       int generated = 0;
       
       do{
           generated = r.Next(0, posibilities.Count);
         } while (person == posibilities[generated]);
         
      theMatchup.Add(new string[] { person, posibilities[generated] });
      posibilities.Remove(posibilities[generated]);
    
    }
   }&lt;/pre&gt;
  &lt;p&gt;   Finally we check the results, and repeat the whole process if necessary&lt;/p&gt; 
&lt;pre class="prettyprint"&gt;
  static bool TestMatch(List&lt;string[]&gt; toTest)
  {
    foreach (string[] p in toTest)
    {
      if (p[0] == p[1])
      return false;
    }
    return true;
  }
 &lt;/pre&gt;
 &lt;p&gt;   Not sure how this scales up, when you are a large department but on this example here : Elapsed : 00:00:00.0017831&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/secret-santa-random-list-generator-using-csharp-.net/</guid></item><item><title>The Mentality for hitting the Gym</title><link>http://www.alexpeta.ro/article/the-mentality-for-hitting-the-gym/</link><description>&lt;p&gt;   Wanted to&amp;nbsp;blog for some time now about &lt;a href="http://en.wikipedia.org/wiki/Bodybuilding"&gt;Bodybuilding&lt;/a&gt;, and i finally got some time and inspiration.&lt;/p&gt;  &lt;p&gt;   Since i have been a kid i&amp;#39;ve allways practiced a sport. I think its the one of the most important things that my parents encuranged me to practice.&lt;/p&gt;  &lt;p&gt;   First it was footbal (soccer) playing with the neighbour&amp;#39;s kinds around the neighbourhood. I must admit, i wasn&amp;#39;t too good at it but the idea is that everytime i heard my voice yealled at the yard door, i allways looked forward to just go around and have fun.&lt;/p&gt;  &lt;p&gt;   After&amp;nbsp;a couple of years in junior high i started playing Basketball and it stuck with me all through highschool and a little in my first year of College.&lt;/p&gt;  &lt;p&gt;   *I love this game.*&lt;/p&gt;  &lt;div&gt;   &lt;iframe allowfullscreen="" frameborder="0" height="315" src="http://www.youtube.com/embed/HPiaoPCtkXk" width="560"&gt;&lt;/iframe&gt;&lt;/div&gt;  &lt;p&gt;   Beeing in College in &lt;a href="http://binged.it/rNGNdK"&gt;Bucharest&lt;/a&gt;, i didn&amp;#39;t&amp;nbsp; have time to go anymore to hit the basketball field, nor were the my old friends allways available for a match, so at this point&amp;nbsp; i had to do something else and &amp;nbsp;then came the answer : go to the gym.&lt;/p&gt;  &lt;p&gt;   When i first stepped foot in a&amp;nbsp; gym i was weighing about 60KG (130punds for all you non-metric people) 180, eathing one meal , two the most&amp;nbsp; per day, could even do a flat Bench Press with no weights.&lt;/p&gt;  &lt;p&gt;   &lt;a href="http://www.youtube.com/results?search_query=bodybuilding+metrorex&amp;amp;oq=bodybuilding+metrorex&amp;amp;aq=f&amp;amp;aqi=&amp;amp;aql=&amp;amp;gs_sm=e&amp;amp;gs_upl=597l4044l0l4186l23l19l1l9l10l0l211l1180l2.6.1l9l0"&gt;It was a underground gym&lt;/a&gt;, located in a huge empty room at a&lt;a href="http://ro.wikipedia.org/wiki/Lujerului_(sta%C8%9Bie_de_metrou)"&gt; subway station &lt;/a&gt;near where i was living at that time. I&amp;#39;ve later learned that this is the place where the guys that go to bodybuilding competitions were training.&lt;/p&gt;  &lt;p&gt;   The first days / weeks were awkword, i didnt knew anything, i just moved the weights around trying to mimic the other bulked up guys there.&lt;/p&gt;  &lt;p&gt;   It was hard, really hard trying to integrate gym after work,but after i&amp;#39;ve noticed that my body was begining to transform, i was hooked.&lt;/p&gt;  &lt;p&gt;   There is a lot of motivational material out there and a lot of views on how you should be motivated to &amp;quot;go hard or go home&amp;quot;.&amp;nbsp;&lt;/p&gt;  &lt;p&gt;   I personally think of bodybuilding and sports in general as something long term with a&amp;nbsp;lifetime span&amp;nbsp;mentality. I am setting milestones, objectives , short term goals and i push myself to reach them but they are positioned . I think you can apply this in any aspect of your life and it will surely keep you focused and on track.&lt;/p&gt;  &lt;p&gt;   Stay focused, train hard, set goals, set milestones and have fun. The results will come and trust me, you will be hooked.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/the-mentality-for-hitting-the-gym/</guid></item><item><title>Create a Selfexpanding Textarea using Javascript</title><link>http://www.alexpeta.ro/article/create-a-selfexpanding-textarea-using-javascript/</link><description>&lt;p&gt;   This post today is about how to create a Facebook-like auto expanding textarea.&lt;/p&gt;
&lt;p&gt;   In order to solve this problem I looked to Facebook in order to somehow reversengineer it and failed gracefully, the javascript code there is pretty complex and out of my understanding and decided to start from scratch.&lt;/p&gt;
&lt;p&gt;   After creating a html textarea element and trying to make some simple calculus with character counting, i had noticed that fonts /characters differ from browser to browser. i.e. Lets say i have &amp;nbsp;a &amp;lt;span&amp;gt; element , font family Arial, 12px size, they are 2 diffrent actual pixel sizes in Firefox vs IE.&lt;/p&gt;
&lt;p&gt;   As the &amp;lt;textarea&amp;gt; element doesnt self-expand, the question I&amp;#39;ve asked myself was : what html tag element is self exapading vertically when filled with text ? Why not have the text fill a &amp;lt;div&amp;gt; element and transfer its size to the &amp;lt;textarea&amp;gt; ?&amp;nbsp;&lt;/p&gt;
&lt;p&gt;   So lets get started with the code, first we have the some CSS :&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
.big_wrap{
  background-color: #EDEFF4;
  border-bottom: 1px solid #E5EAF1;
  margin-top: 2px;
  padding: 5px 5px 4px;
}
.fontStyle{
  direction: ltr;
  font-family: &amp;quot;lucida grande&amp;quot;,tahoma,verdana,arial,sans-serif;
  font-size: 11px;
  text-align: left;
}
#Test{
  left:-9999px;
  position: absolute;
  height: auto;
  width: auto;
  font-family: &amp;quot;lucida grande&amp;quot;,tahoma,verdana,arial,sans-serif;
  font-size: 11px;
}
#comm{
  width:340px;
  border:1px solid #BDC7D8;
  height:13px;
  padding:3px;
  overflow:hidden;
  resize: none;
  word-wrap: break-word;
  white-space: pre-wrap;
  z-index:2;
}
.btn {
  background-color: #5B74A8;
  border: 0 none;
  color: White;
  cursor: pointer;
  display: block;
  font-weight: bold;
  padding: 3px 8px;
}
#highlighter{
  width:340px;
  white-space: pre-wrap;
  word-wrap: break-word;
  position:absolute;
  color:trasparent;
  z-index:1;
  border:1px solid #003;
  visibility:hidden;
  padding:3px;
  margin:1px;
}
&lt;/pre&gt;
&lt;p&gt;   Here we have defied some styles to resemble the facebook interface.&lt;/p&gt;
&lt;p&gt;   Next is the HTML :&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
&amp;lt;table cellpadding=&amp;quot;0&amp;quot; cellspacing=&amp;quot;0&amp;quot; align=&amp;quot;center&amp;quot;&amp;gt;
  &amp;lt;tbody&amp;gt;
    &amp;lt;tr&amp;gt;
	  &amp;lt;td&amp;gt;
	    &amp;lt;div style=&amp;quot;&amp;quot; class=&amp;quot;fontStyle&amp;quot; id=&amp;quot;highlighter&amp;quot; name=&amp;quot;highlighter&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
		&amp;lt;div class=&amp;quot;big_wrap&amp;quot;&amp;gt;
		  &amp;lt;div class=&amp;quot;wrap&amp;quot;&amp;gt;
		    &amp;lt;textarea id=&amp;quot;comm&amp;quot; class=&amp;quot;fontStyle&amp;quot;  onkeypress=&amp;quot;enlarge(this,event)&amp;quot; onkeyup=&amp;quot;enlarge(this,event)&amp;quot; onkeydown=&amp;quot;enlarge(this,event)&amp;quot; onblur=&amp;quot;enlarge(this,event)&amp;quot; onfocus=&amp;quot;enlarge(this,event)&amp;quot;&amp;gt;&amp;lt;/textarea&amp;gt;
			&amp;lt;input class=&amp;quot;mentionsHidden&amp;quot; type=&amp;quot;hidden&amp;quot; autocomplete=&amp;quot;off&amp;quot; name=&amp;quot;add_comment_text&amp;quot; value=&amp;quot;&amp;quot;&amp;gt; 
		 &amp;lt;/div&amp;gt;
		&amp;lt;/div&amp;gt;
	&amp;lt;/td&amp;gt;
	&amp;lt;/tr&amp;gt;
	&amp;lt;tr&amp;gt;
	   &amp;lt;td style=&amp;quot;height:20px;padding-top:2px;&amp;quot; align=&amp;quot;right&amp;quot;&amp;gt;
		 &amp;lt;input type=&amp;quot;submit&amp;quot; class=&amp;quot;btn&amp;quot; id=&amp;quot;btnAddComm&amp;quot; value=&amp;quot;Add Comment&amp;quot; name=&amp;quot;btnAddComm&amp;quot;&amp;gt;
	   &amp;lt;/td&amp;gt;
	&amp;lt;/tr&amp;gt; 
	&amp;lt;tr&amp;gt;
	  &amp;lt;td style=&amp;quot;height:20px;&amp;quot;&amp;gt;&amp;amp;nbsp;&amp;lt;/td&amp;gt;
	&amp;lt;/tr&amp;gt;
  &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;  
&lt;/pre&gt;     &lt;p&gt;   And finally the Javascript code :&lt;/p&gt;
&lt;p&gt;   &amp;nbsp;&lt;/p&gt;
&lt;pre class="prettyprint"&gt;
function enlarge(c,e){
  if(c.value.length == 0){
    document.getElementById(&amp;#39;highlighter&amp;#39;).innerHTML = &amp;#39;&amp;#39;;
	c.style.height == &amp;#39;13px&amp;#39;;
  }
  else
  {
    document.getElementsByName(&amp;#39;add_comment_text&amp;#39;).item(0).value = c.value;
	document.getElementById(&amp;#39;highlighter&amp;#39;).innerHTML = c.value;
	var h = document.getElementById(&amp;#39;highlighter&amp;#39;).clientHeight-6;
	c.style.height = h+&amp;#39;px&amp;#39;;
  }
}
&lt;/pre&gt;  &lt;p&gt;   So what i have created here is my &amp;lt;textarea&amp;gt; element with the id comm, which i have binded with keypress/keydown/keyup/onblur/onfocus events to call the enlarge function.&lt;/p&gt;  &lt;p&gt;   The function will put the textarea content in our &amp;quot;highlighter&amp;quot; div, which as you noticed must have the same width /style definition as the textarea, and the get the height of the highlighter and send it to the textarea.&lt;/p&gt;</description><guid>http://www.alexpeta.ro/article/create-a-selfexpanding-textarea-using-javascript/</guid></item><item><title>Adding Gravatar To  An ASP MVC Project</title><link>http://www.alexpeta.ro/article/adding-gravatar-to--an-asp-mvc-project/</link><description>&lt;p&gt;
Have you ever left a comment on a site , where you were asked just name/email/website info, and found in front an image&amp;nbsp; similar to this image here:&amp;nbsp;&lt;/p&gt;     &lt;p&gt;&lt;img alt="" src="http://www.gravatar.com/avatar/00000000000000000000000000000000?d=identicon" style="width: 80px; height: 80px" /&gt; And even more, did you notice that if you used the same credentials the image was the same?&lt;/p&gt;      &lt;p&gt;       All these sites use &lt;a href="http://en.gravatar.com/"&gt;Gravatar &lt;/a&gt;to implement this image. It works both ways, for the gravatar user, each time you leave a comment you can leave your personal image wherever you comment ,and sites can benefit from this without having to save images for every user.&lt;/p&gt;      &lt;p&gt;       I wanted this feature on this blog and i had to write today this in my ASP MVC project, so lets get coding :&lt;/p&gt;  

&lt;pre class="prettyprint"&gt;
 public static class Gravatar 
 {
    public enum GRProtocol 
	{
	  Normal,// = "http://www.gravatar.com/avatar/",
	  Secure,// = "https://www.gravatar.com/avatar/"  
	}
	
	public enum GRSize 
	{
	  xs20,// = "s=20",
	  s40,// = "s=40",
	  m80,// = "s=80",
	  l160,// = "s=160",
	  xl200,// = "s=200"
	}
	
	public enum GRDefault 
	{
	   MysteryMan, // = "d=mm",
	   IdentIcon,// = "d=identicon",
	   MonsterId,// = "d=monsterid",
	   WaveAtar,// = "d=wavatar",
	   Retro,// = "d=retro"
	}
	
	public static string GetGravatarLink(string email,GRProtocol protocol, GRSize size, GRDefault defaultAvatar)
	{
	   string theEmail = email.Trim().ToLower();
	   
	   MD5 md5Hasher = MD5.Create(); 
	   
	   byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(theEmail));
	   
	   StringBuilder sBuilder = new StringBuilder();
	   
	   //add the procol
	   
	   switch (protocol)
	   {
	      case GRProtocol.Normal:  sBuilder.Append("http://www.gravatar.com/avatar/"); break;
		  case GRProtocol.Secure:  sBuilder.Append("https://www.gravatar.com/avatar/"); break;
	   } 
	   
	   // Loop through each byte of the hashed data 
	   // and format each one as a hexadecimal string.
	   for (int i = 0; i&amp;lt;data.Length; i++)
	   {
	      sBuilder.Append(data[i].ToString("x2"));
	   }
	   sBuilder.Append("?");
	   
	   //add the size
	   switch (size)
	   {
	     case GRSize.xs20: sBuilder.Append("&amp;s=20"); break;
		 case GRSize.s40: sBuilder.Append("&amp;s=40"); break;
		 case GRSize.m80: sBuilder.Append("&amp;s=80"); break;
		 case GRSize.l160: sBuilder.Append("&amp;s=160"); break;
		 case GRSize.xl200: sBuilder.Append("&amp;s=200"); break;
	   } 
	   
	   //add the default gravatar when email is not on gravatar
	   switch (defaultAvatar) 
	   { 
	     case GRDefault.MysteryMan: sBuilder.Append("&amp;d=mm"); break;
		 case GRDefault.IdentIcon: sBuilder.Append("&amp;d=identicon"); break;
		 case GRDefault.MonsterId: sBuilder.Append("&amp;d=monsterid"); break; 
		 case GRDefault.WaveAtar: sBuilder.Append("&amp;d=wavatar"); break; 
		 case GRDefault.Retro: sBuilder.Append("&amp;d=retro"); break; 
		}
		// Return the gravatar link 
		return sBuilder.ToString(); 
	  }
} 
&lt;/pre&gt;
  &lt;p&gt;   As you can see the end result represents a Gravatar url that will be specified in and &amp;lt;img&amp;gt; tag.&lt;/p&gt;
  &lt;p&gt;   The url must contain the MD5 encoded email (trimmed and all lower case), and aditional parameters that you may include such as the size of the gravatar (i&amp;#39;ve predifed a couple here but basically you can request images anywhere from &lt;strong&gt;1px up to 512px.&lt;/strong&gt;&lt;/p&gt;
  &lt;p&gt;   We can also have default images in case gravatar doesnt exist, and it also has support for secure protocols as well.&lt;/p&gt;
  &lt;p&gt;   All you are left to do is call this in either a helper method or a view directly :&lt;/p&gt;
  &lt;p&gt;   
    &lt;strong&gt;GetGravatarLink(c.Email,GRProtocol.Normal,GRSize.m80,GRDefault.MonsterId);&lt;/strong&gt;
 &lt;/p&gt; 
 &lt;p&gt;   The URL result will look like : &lt;a href="http://www.gravatar.com/avatar/19dc7b4182ba5c474300444465aee722?&amp;amp;s=80&amp;amp;d=monsterid"&gt;http://www.gravatar.com/avatar/19dc7b4182ba5c474300444465aee722?&amp;amp;s=80&amp;amp;d=monsterid&lt;/a&gt;&lt;/p&gt;  </description><guid>http://www.alexpeta.ro/article/adding-gravatar-to--an-asp-mvc-project/</guid></item><item><title>The Blog Is Live</title><link>http://www.alexpeta.ro/article/the-blog-is-live/</link><description>&lt;p&gt;   So i&amp;#39;ve been coding for the last 2 weeks in my spare time&amp;nbsp; between work and hitting the gym at this blog that you are seeing right now, but this is still very much a work-in-progress.&lt;/p&gt;  &lt;p&gt;   I&amp;#39;ve allways been a fan of the .NET platform ,and my interest lately is &lt;a href="http://asp.net/mvc"&gt;ASP MVC&lt;/a&gt;. I absolutely love it, and the first step in doing so is coding my own small scale blog CMS.&lt;/p&gt;  &lt;p&gt;   As you can probably tell im kind of a&amp;nbsp; &amp;quot;designely challenged&amp;quot; person if i can say so and because i can&amp;#39;t afford buying a good blog design right now, i&amp;#39;ve googled some free templates, filtered them out and chose this black - greenish one. I&amp;#39;ve left the credits and the footer intact and i dont claim this as being my own concoction.&lt;/p&gt;  &lt;p&gt;   As for the code itself, i&amp;#39;ve focused just on the main functionality used LINQ2SQL [ although last week , after going to a &lt;a href="http://ronua.ro"&gt;RONUA&lt;/a&gt; conference , i&amp;#39;ve learnead that MSF doesnt&amp;nbsp;continue to develop&amp;nbsp;Linq anymore just do only the bugfixing, instead going for &lt;a href="http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework"&gt;Entity Framework &lt;/a&gt;as their &lt;a href="http://en.wikipedia.org/wiki/Object-relational_mapping"&gt;ORM&lt;/a&gt; implementation ] and the basic CRUD operations in the backend Admin, and simple operation in the front end design.&lt;/p&gt;  &lt;p&gt;   Im leaving all the jQuery goodness, efects and magic&amp;nbsp; for as the last thing on the&amp;nbsp; &lt;a href="http://msdn.microsoft.com/en-us/library/zce12xx2%28v=vs.80%29.aspx"&gt;// TODO :&lt;/a&gt; &amp;nbsp;list.&lt;/p&gt; </description><guid>http://www.alexpeta.ro/article/the-blog-is-live/</guid></item><item><title>My First Article</title><link>http://www.alexpeta.ro/article/my-first-article/</link><description>&lt;p&gt;   Its good to be on the blogosphere. I&amp;#39;ve been waiting for this moment for &lt;strike&gt;quite some time&lt;/strike&gt; over two years now, and its finally good to be virtually present.&lt;/p&gt;  &lt;p&gt;   I&amp;#39;ve allways wanted to be apart of the online family, although im sure that one day&amp;nbsp; the &lt;a href="http://www.hanselman.com/blog/410GoneThoughtsOnMarkDiveintomarkPilgrimsAndWhysInfosuicides.aspx"&gt;excitement will fade away&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;   So, enough for the first post now, its been exhausting.&lt;/p&gt;  &lt;p&gt;   &amp;nbsp;&lt;/p&gt; </description><guid>http://www.alexpeta.ro/article/my-first-article/</guid></item></channel></rss>