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

<channel>
	<title>OmegaMan&#039;s Musings</title>
	<atom:link href="http://OmegaCoder.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://OmegaCoder.com</link>
	<description>Technology blog written by a Microsoft C# MVP</description>
	<lastBuildDate>Mon, 25 Mar 2013 17:38:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>ASP.Net MVC: Single Page Application (SPA) from Scratch; A How To Step by Step</title>
		<link>http://OmegaCoder.com/?p=986</link>
		<comments>http://OmegaCoder.com/?p=986#comments</comments>
		<pubDate>Mon, 25 Mar 2013 17:35:17 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[SPA]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=986</guid>
		<description><![CDATA[During my presentation to the Denver Visual Studio Users Group on Asp.net SPA on March 25, 2013, I created an example SPA application from scratch using Visual Studio 2012 with Asp.Net and MVC. The intent was to provide an understanding of the tools and technologies needed to build an Asp.net spa. The following are the [...]]]></description>
				<content:encoded><![CDATA[<p>During my presentation to the <a href="http://www.denvervisualstudio.net/">Denver Visual Studio Users Group</a> on Asp.net SPA on March 25, 2013, I created an example SPA application from scratch using Visual Studio 2012 with Asp.Net and MVC. The intent was to provide an understanding of the tools and technologies needed to build an Asp.net spa. The following are the steps I used to create the basic SPA entitled UserGroupSPA in VS2012. </p>
<p>The following technologies and templates were used or provided inspiration in creating the example:</p>
<ul>
<li>Visual Studio 2012 </li>
<li>Nuget </li>
<li><a href="http://www.breezejs.com">Breeze.WebApi</a> </li>
<li><a href="http://durandaljs.com/">Durandal</a>
<ul>
<li>Durandal.Router </li>
<li>Durandal.Transitions </li>
</ul>
</li>
<li>jQuery </li>
<li><a href="http://knockoutjs.com/">knockoutjs</a> </li>
<li>Microsoft.AspNet.Mvc </li>
<li><a href="https://github.com/CodeSeven/toastr">toastr</a> </li>
<li><a href="http://twitter.github.com/bootstrap/index.html">Twitter.Bootstrap</a> </li>
<li><a href="http://nuget.org/packages/WebActivator">WebActivator</a> </li>
<li><a href="http://www.johnpapa.net/hottowel/">HotTowel</a> SPA template – Uses design components from this template which gives it a similar look and feel. </li>
<li><a href="http://www.asp.net/single-page-application">Single Page Application</a> template/info </li>
<li><a href="http://responsive.victorcoulon.fr/">Responsive Design</a> bookmarklet for Chrome </li>
</ul>
<h2>Pre Setup</h2>
<ol>
<li>Using <a href="http://www.microsoft.com/web/platform/">Microsoft Web Platform</a> Installer 4.5, install&#160; <a href="http://www.microsoft.com/web/handlers/webpi.ashx/getinstaller/ASPDOTNETandWebTools2012_2.appids">Asp.Net and Web Tools 2012.2 Update</a>.
<ol>
<li>Note that as of this writing that update will be included in the future Visual Studio 2012 Update #2. </li>
<li>In the Microsoft Web Platform installer it is listed as Asp.net and Web Tools 2012.2 </li>
</ol>
</li>
</ol>
<h2>Visual Studio Project</h2>
<ol>
<li>Create new project
<ol>
<li>ASP.Net MVC 4 Web Application named <font color="#ff0000"><strong>UserGroupSPA</strong></font>
<ol>
<li>Choose <strong>Basic</strong> Asp.net MVC4 Project Template with <strong>Razor</strong> view engine </li>
</ol>
</li>
</ol>
</li>
<li>Package Manager Console (NUGET)
<ol>
<li>Get-Package –Update
<ol>
<li>Update-Package jQuery </li>
<li>… (update all packages which can be updated as reported) </li>
<li>Update-Package knockoutjs </li>
</ol>
</li>
<li>Install-Package Breeze.Webapi </li>
</ol>
</li>
</ol>
<h2>Create Viewable Web Page in MVC at Root</h2>
<ol>
<li>UserGroupSpa\Views (project folder in solution)
<ol>
<li>Delete <strong>Shared </strong>folder and all of its contents </li>
<li>Delete the view <strong>_View Start.cshtml</strong> </li>
<li>Create <strong>DVSUG</strong> directory
<ol>
<li>Add <em>the view</em> index.cshtml into the DVSUG directory               <br /> 
<pre class="brush: xml; gutter: false; auto-links: false;">@using System.Web
@using System.Web.Optimization
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Denver Visual Studio Users Group&lt;/title&gt;
    
    @Styles.Render(&quot;~/Content/css&quot;)
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Denver Visual Studio Users Group Main&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt; </pre>
</li>
</ol>
</li>
</ol>
</li>
<li>Global.asax
<ol>
<li>Comment out the line RegisterBundles such as:<br />
        </p>
<pre class="brush: csharp; gutter: false; toolbar: false; auto-links: false;">WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//BundleConfig.RegisterBundles(BundleTable.Bundles);</pre>
</li>
</ol>
</li>
<li>App_Start folder
<ol>
<li>Add C# class DVSUGConfig<br />
        </p>
<pre class="brush: csharp; gutter: false; toolbar: false; auto-links: false;">using System.Web.Optimization;

[assembly: WebActivator.PostApplicationStartMethod(
    typeof(UserGroupSPA.App_Start.DVSUGConfig), &quot;PreStart&quot;)]

namespace UserGroupSPA.App_Start
{
    public class DVSUGConfig
    {
        public static void PreStart()
        {
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

}</pre>
</li>
<li>Add C# class DVSUGRouteConfig<br />
        </p>
<pre class="brush: csharp; gutter: false; toolbar: false; auto-links: false;">using System.Web.Mvc;

[assembly: WebActivator.PreApplicationStartMethod(
    typeof(UserGroupSPA.App_Start.DVSUGRouteConfig), &quot;RegisterDVSUGPreStart&quot;, Order = 2)]

namespace UserGroupSPA.App_Start
{
    ///&lt;summary&gt;
    /// Inserts the DVSUGRouteConfig SPA sample view controller to the front of all MVC routes
    /// so that the DVSUGRouteConfig SPA sample becomes the default page.
    ///&lt;/summary&gt;
    ///&lt;remarks&gt;
    /// This class is discovered and run during startup
    /// http://blogs.msdn.com/b/davidebb/archive/2010/10/11/light-up-your-nupacks-with-startup-code-and-webactivator.aspx
    ///&lt;/remarks&gt;
    public static class DVSUGRouteConfig
    {

        public static void RegisterDVSUGPreStart()
        {

            // Preempt standard default MVC page routing to go to DVSUG 
            System.Web.Routing.RouteTable.Routes.MapRoute(
                name: &quot;DVSUGMvc&quot;,
                url: &quot;{controller}/{action}/{id}&quot;,
                defaults: new
                {
                    controller = &quot;DVSUG&quot;,
                    action = &quot;Index&quot;,
                    id = UrlParameter.Optional
                }
            );
        }
    }
}</pre>
</li>
</ol>
</li>
<li>Controllers directory
<ol>
<li>Add controller DVSUGController (Empty MVC Controller) </li>
</ol>
</li>
<li>Run the application in IE (not chrome) in debug (F5)<br />
    </li>
</ol>
<h2>Adding Toastr For Notifications</h2>
<ol>
<li>Package Manager Console
<ol>
<li>install-package toastr </li>
</ol>
</li>
<li>App_Start
<ol>
<li>BundleConfig.CS change to:<br />
        </p>
<pre class="brush: csharp; gutter: false; toolbar: false; auto-links: false;">using System.Web;
using System.Web.Optimization;

namespace UserGroupSPA
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.IgnoreList.Ignore(&quot;*.intellisense.js&quot;);
            bundles.IgnoreList.Ignore(&quot;*-vsdoc.js&quot;);

            bundles.Add(
                        new ScriptBundle(&quot;~/scripts/UGScripts&quot;)
                        .Include(&quot;~/Scripts/jquery-{version}.js&quot;)
                        .Include(&quot;~/scripts/knockout-{version}.debug.js&quot;)
                        .Include(&quot;~/scripts/toastr.js&quot;)
                        .Include(&quot;~/scripts/Q.js&quot;)
                        .Include(&quot;~/scripts/breeze.debug.js&quot;)
                        );

            bundles.Add(
                        new StyleBundle(&quot;~/Content/css&quot;)
                       .Include(&quot;~/Content/bootstrap.css&quot;)
                        .Include(&quot;~/Content/toastr.css&quot;)
                        );
        }
    }
}</pre>
</li>
</ol>
</li>
<li>Views\DVSUG\index.cshtml<br />
    </p>
<pre class="brush: xml; gutter: false; toolbar: false; auto-links: false;">@using System.Web
@using System.Web.Optimization
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Denver Visual Studio Users Group&lt;/title&gt;

    @Styles.Render(&quot;~/Content/css&quot;)

&lt;/head&gt;

&lt;body onload=&quot;toastr.info('Loading Main Body')&quot;&gt;

    @Scripts.Render(&quot;~/scripts/UGScripts&quot;)

    &lt;h1&gt;Denver Visual Studio Users Group Main&lt;/h1&gt;
    
&lt;/body&gt;

&lt;/html&gt; </pre>
</li>
<li>Run in IE again and verify the toast event “Loading Main Body” comes up. such as:<br />
    <br /><a href="http://omegacoder.com/wp-content/uploads/2013/03/DVSUG.png"><img title="DVSUG" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; display: block; padding-right: 0px; border-top-width: 0px; margin-right: auto" border="0" alt="DVSUG" src="http://omegacoder.com/wp-content/uploads/2013/03/DVSUG_thumb.png" width="244" height="23" /></a> </li>
</ol>
<h2>Install Durandal</h2>
<ol>
<li>Package Manager Console
<ol>
<li>install-package Durandal </li>
<li>install-package Durandal.Router </li>
<li>install-package Durandal.Transitions </li>
<li>install-package Twitter.Bootstrap </li>
</ol>
</li>
<li>App_Start\BundleConfig.CS<br />
    </p>
<pre class="brush: csharp; gutter: false; toolbar: false; auto-links: false;">using System.Web;
using System.Web.Optimization;

namespace UserGroupSPA
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.IgnoreList.Ignore(&quot;*.intellisense.js&quot;);
            bundles.IgnoreList.Ignore(&quot;*-vsdoc.js&quot;);

            bundles.Add(
                        new ScriptBundle(&quot;~/scripts/UGScripts&quot;)
                        .Include(&quot;~/Scripts/jquery-{version}.js&quot;)
                        .Include(&quot;~/scripts/knockout-{version}.debug.js&quot;)
                        .Include(&quot;~/scripts/sammy-{version}.js&quot;)
                        .Include(&quot;~/scripts/toastr.js&quot;)
                        .Include(&quot;~/scripts/Q.js&quot;)
                        .Include(&quot;~/scripts/breeze.debug.js&quot;)
                        .Include(&quot;~/scripts/bootstrap.js&quot;)
                        .Include(&quot;~/scripts/moment.js&quot;)
                        );

            bundles.Add(
                        new StyleBundle(&quot;~/Content/css&quot;)
                .Include(&quot;~/Content/ie10mobile.css&quot;)
                .Include(&quot;~/Content/bootstrap.css&quot;)
                .Include(&quot;~/Content/bootstrap-responsive.css&quot;)
                .Include(&quot;~/Content/durandal.css&quot;)
                .Include(&quot;~/Content/toastr.css&quot;)
                .Include(&quot;~/Content/app.css&quot;)

                        );

        }
    }
}</pre>
</li>
</ol>
<h2>Work With Views as a SPA using Durandal </h2>
<ol>
<li>UserGroupSPA\App directory (created by Durandal)
<ol>
<li>Add the folders
<ol>
<li>viewmodels </li>
<li>views </li>
</ol>
</li>
<li>Add the javascript file main.js<br />
        </p>
<pre class="brush: js; gutter: false; toolbar: false; auto-links: false;">require.config({
    paths: { &quot;text&quot;: &quot;durandal/amd/text&quot; }
});

define(['durandal/app', 'durandal/viewLocator', 'durandal/system', 'durandal/plugins/router'],
    function (app, viewLocator, system, router) {

       system.debug(true); // Outputs to the console the process, turn off for production

       app.start().then(function () {
           toastr.options.positionClass = 'toast-bottom-right';
           toastr.options.backgroundpositionClass = 'toast-bottom-right';

           router.handleInvalidRoute = function (route, params) {
               toastr.info('No Route Found: ' + route);
           };

           router.useConvention();
           viewLocator.useConvention();
           
           // Our three views
           router.mapNav('home');
           router.mapNav('speakers');
           router.mapNav('events');
           
           
           app.adaptToDevice(); // Touch devices to adapt to
           
           app.setRoot('viewmodels/shell', 'entrance'); //Show the SPA at its root
       });
        
  });</pre>
</li>
</ol>
</li>
<li>Views\DVSUG\index.cshtml changed to<br />
    </p>
<pre class="brush: xml; gutter: false; toolbar: false; auto-links: false;">@using System.Web
@using System.Web.Optimization
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Denver Visual Studio Users Group&lt;/title&gt;
    &lt;meta charset=&quot;utf-8&quot; /&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge, chrome=1&quot; /&gt;
    &lt;meta name=&quot;apple-mobile-web-app-capable&quot; content=&quot;yes&quot; /&gt;
    &lt;meta name=&quot;apple-mobile-web-app-status-bar-style&quot; content=&quot;black&quot; /&gt;
    &lt;meta name=&quot;format-detection&quot; content=&quot;telephone=no&quot;/&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;

    @Styles.Render(&quot;~/Content/css&quot;)
&lt;/head&gt;

    &lt;body onload=&quot;toastr.info('Loading Main Body')&quot;&gt;
        
        &lt;div id=&quot;applicationHost&quot;&gt;
        &lt;/div&gt;


        @Scripts.Render(&quot;~/scripts/UGScripts&quot;)

        @if(HttpContext.Current.IsDebuggingEnabled) {
            &lt;script type=&quot;text/javascript&quot; src=&quot;~/App/durandal/amd/require.js&quot; data-main=&quot;@Url.Content(&quot;~/App/main&quot;)&quot;&gt;&lt;/script&gt;
        } else 
        {
            &lt;script type=&quot;text/javascript&quot; src=&quot;~/App/main-built.js&quot;&gt;&lt;/script&gt;
        }
    
    &lt;/body&gt;
&lt;/html&gt;   </pre>
</li>
<li>App\viewmodels
<ol>
<li>add event.js<br />
        </p>
<pre class="brush: js; gutter: false; toolbar: false; collapse: false; auto-links: false;">define(function () {
    var vm = {
        activate: activate,
        title: 'Events View'
    };

    return vm;

    function activate() {
        toastr.info('Events View Activated');
        return true;
    }
});</pre>
</li>
<li>add home.js<br />
        </p>
<pre class="brush: js; gutter: false; toolbar: false; collapse: false; auto-links: false;">define(function () {
    var vm = {
        activate: activate,
        title: 'Home View'
    };

    return vm;

    function activate() {
        toastr.info('Home View Activated');
        return true;
    }
});</pre>
</li>
<li>add shell.js<br />
        </p>
<pre class="brush: js; gutter: false; toolbar: false; collapse: false; auto-links: false;">define(['durandal/system', 'durandal/plugins/router'],
    function (system, router) {
        var shell = {
            activate: activate,
            router: router
        };

        return shell;

        function activate() {
            return boot();
        }

        function boot() {

            toastr.info('DVSUG Boot Loaded!');
            return router.activate('home');
        }


    });</pre>
</li>
<li>add speakers.js<br />
        </p>
<pre class="brush: js; gutter: false; toolbar: false; collapse: false; auto-links: false;">define(function () {
    var vm = {
        activate: activate,
        title: 'Speakers View'
    };

    return vm;

    function activate() {
        toastr.info('Speakers View Activated');
        return true;
    }
});</pre>
</li>
</ol>
</li>
<li>App\views
<ol>
<li>add events.html<br />
        </p>
<pre class="brush: xml; gutter: false; toolbar: false; collapse: false; auto-links: false;">&lt;section&gt;
    &lt;h2 class=&quot;page-title&quot; data-bind=&quot;text: title&quot;&gt;&lt;/h2&gt;
&lt;/section&gt;</pre>
</li>
<li>add footer.html<br />
        </p>
<pre class="brush: xml; gutter: false; toolbar: false; collapse: false; auto-links: false;">&lt;nav class=&quot;navbar navbar-fixed-bottom&quot;&gt;
    &lt;div class=&quot;navbar-inner navbar-content-center&quot;&gt;
        &lt;span class=&quot;pull-left&quot;&gt;&lt;a href=&quot;http://omegacoder.com&quot; target=&quot;_blank&quot;&gt;OmegaCoder.com &lt;/a&gt;&lt;/span&gt;
        &lt;span class=&quot;pull-right&quot;&gt;&lt;a href=&quot;http://www.denvervisualstudio.net/&quot; target=&quot;_blank&quot;&gt;Denver Visual Studio User Group&lt;/a&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/nav&gt;</pre>
</li>
<li>add home.html<br />
        </p>
<pre class="brush: xml; gutter: false; toolbar: false; collapse: false; auto-links: false;">&lt;section&gt;
    
    &lt;table&gt;
        &lt;tr&gt;&lt;td&gt;&lt;h2 class=&quot;page-title&quot; data-bind=&quot;text: title&quot;&gt;&lt;/h2&gt;&lt;/td&gt;&lt;/tr&gt;
        
        &lt;tr&gt;&lt;td&gt;&lt;h3&gt;Next: Asp.Net SPA&lt;/h3&gt;&lt;/td&gt;&lt;/tr&gt;
  
              &lt;tr&gt;&lt;td&gt;&lt;p&gt;Come and find out all about it in this introduction to building Single Page Applications (SPA) which allow for rich client side interactions using JavaScript, HTML 5, and CSS in the ASP.NET world.&lt;/p&gt;
                &lt;p&gt;This introduction will familiarize you, the developer, to the templates available as well as an overview of the components which make up SPAs and how to put them together. This talk is a general how-to on being able to come up to speed on the technology and will focus on actually creating a page and cover the interactions of ASP.Net MVC with basic data transport.&lt;/p&gt;
                &lt;p&gt;You will see how ASP.NET Single-Page Applications (SPA) enable cutting-edge web developers to deliver rich, engaging web applications that surface information and interactivity in fresh and exciting new ways.&lt;/p&gt;
      &lt;/td&gt;&lt;/tr&gt;        

    &lt;/table&gt;
    
    

&lt;/section&gt;</pre>
</li>
<li>add nav.html<br />
        </p>
<pre class="brush: xml; gutter: false; toolbar: false; collapse: false; auto-links: false;">&lt;nav class=&quot;navbar navbar-fixed-top&quot;&gt;
    &lt;div class=&quot;navbar-inner&quot;&gt;
        &lt;a class=&quot;brand&quot; href=&quot;/&quot;&gt;
            &lt;span class=&quot;title&quot;&gt;Denver Visual Studio Users Group&lt;/span&gt; 
        &lt;/a&gt;
        &lt;div class=&quot;btn-group&quot; data-bind=&quot;foreach: router.visibleRoutes&quot;&gt;
            &lt;a data-bind=&quot;css: { active: isActive }, attr: { href: hash }, text: name&quot; 
                class=&quot;btn btn-info&quot; href=&quot;#&quot;&gt;&lt;/a&gt;
        &lt;/div&gt;

    &lt;/div&gt;
&lt;/nav&gt;</pre>
</li>
<li>add shell.html<br />
        </p>
<pre class="brush: xml; gutter: false; toolbar: false; collapse: false; auto-links: false;">&lt;div&gt;
    &lt;header&gt;
        &lt;!--ko compose: {view: 'nav'} --&gt;&lt;!--/ko--&gt;
    &lt;/header&gt;
    &lt;section id=&quot;content&quot; class=&quot;main container-fluid&quot;&gt;
        &lt;!--ko compose: {model: router.activeItem, 
            afterCompose: router.afterCompose, 
            transition: 'entrance'} --&gt;
        &lt;!--/ko--&gt;
    &lt;/section&gt;
    &lt;footer&gt;
        &lt;!--ko compose: {view: 'footer'} --&gt;&lt;!--/ko--&gt;
    &lt;/footer&gt;
&lt;/div&gt;</pre>
</li>
<li>add speakers.html<br />
        </p>
<pre class="brush: xml; gutter: false; toolbar: false; collapse: false; auto-links: false;">&lt;section&gt;
    
    &lt;table&gt;
        &lt;tr&gt;&lt;td&gt;&lt;h2 class=&quot;page-title&quot; data-bind=&quot;text: title&quot;&gt;&lt;/h2&gt;&lt;/td&gt;&lt;/tr&gt;
        
        &lt;tr&gt;&lt;td&gt;&lt;h3&gt;William Wegerson&lt;/h3&gt;&lt;/td&gt;&lt;/tr&gt;
  
        &lt;tr&gt;&lt;td&gt;
                &lt;p&gt;William Wegerson is an Architect Developer who has been working here in Denver for over 20 years.&lt;/p&gt;
                &lt;p&gt;He has presented to the group before on such topics as Silverlight and Visual Studio releases (VS 2010 and 2012) as well as teaching labs to the members.&lt;/p&gt;
                &lt;p&gt;He has been awarded Microsoft MVP status since 2009 as a result of his community work such as this presentation as well as his blog and as an active resource on the MSDN forums and StackOverflow, answering questions of all types.&lt;/p&gt;
       &lt;/td&gt;&lt;/tr&gt;        

    &lt;/table&gt;
    
    

&lt;/section&gt;</pre>
</li>
</ol>
</li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D986&amp;title=ASP.Net%20MVC%3A%20Single%20Page%20Application%20%28SPA%29%20from%20Scratch%3B%20A%20How%20To%20Step%20by%20Step" id="wpa2a_2"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=986</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#: Combine Two Values Together From a List Into Pairs</title>
		<link>http://OmegaCoder.com/?p=967</link>
		<comments>http://OmegaCoder.com/?p=967#comments</comments>
		<pubDate>Thu, 06 Dec 2012 22:09:43 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Utilities]]></category>
		<category><![CDATA[Extension Methods]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=967</guid>
		<description><![CDATA[Sometimes in C# .Net (see Notes section on usage for before .Net 4)  one might have a list of items and want to make them into pairs. Possibly to take those pairs and place the them into a dictionary. If the items are in a list, that list is linear by nature and using linq [...]]]></description>
				<content:encoded><![CDATA[<p>Sometimes in C# .Net (<em>see Notes section on usage for before .Net 4</em>)  one might have a list of items and want to make them into pairs. Possibly to take those pairs and place the them into a dictionary. If the items are in a list, that list is linear by nature and using linq is not an option when using the extension <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx" target="_blank">ToDictionary</a>.</p>
<p>I have created extension methods to create paired values from any list and those methods are named AsPairs and AsPairsSafe. If the list is odd in length, the final number will be combined with the system default for that type as handled in the method AsPairs. If that is not desired then call AsPairsSafe which will skip the last odd value.</p>
<p>Here is the usage of the AsPairs extension on integers and strings:</p>
<pre class="brush: csharp; gutter: false;">var ints = new List&lt;int&gt; { 1, 2, 3, 4, 5 };

IEnumerable&lt;Tuple&lt;int,int&gt;&gt; asTuplePairs = ints.AsPairs();

/* asTuplePairs looks like this(Note value 5 is paired with a default value of 0)
1,2 
3,4
5,0
*/

var strings = new List&lt;string&gt; { "Alpha", "Beta", "Gamma", "Delta", "Omega" };

IEnumerable&lt;Tuple&lt;string,string&gt;&gt; asTuplePairsStrings = strings.AsPairs();

/* asTuplePairsStrings (note Omega is paired a default value of Null)
Alpha, Beta 
Gamma, Delta
Omega, NULL

Whereas the call to AsPairsSafe would return without Omega:
Alpha, Beta 
Gamma, Delta
*/
</pre>
<p>Here are the extension methods:</p>
<pre class="brush: csharp; gutter: false;">public static class MyExtensions
{
   // Create Pairs from a list. If the list is odd add a default value for the final pair. 
   public static IEnumerable&lt;Tuple&lt;T, T&gt;&gt; AsPairs&lt;T&gt;(this List&lt;T&gt; list)
   {
      int index = 0;

      while (index &lt; list.Count())
      {
         if (index + 1 &gt; list.Count())
            yield break;

         if (index + 1 == list.Count())    
            yield return new Tuple&lt;T,T&gt;(list[index++],  default(T));
         else
            yield return new Tuple&lt;T,T&gt;(list[index++],  list[index++]);
      }
   }

   // Create Pairs from a list. Note if the list is not even in count, the last value is skipped.
   public static IEnumerable&lt;Tuple&lt;T, T&gt;&gt; AsPairsSafe&lt;T&gt;(this List&lt;T&gt; list)
   {
      int index = 0;

      while (index &lt; list.Count())
      {
         if (index + 1 &gt;= list.Count())
            yield break;

         yield return new Tuple&lt;T,T&gt;(list[index++],  list[index++]);
      }

   }
}</pre>
<h3>Notes</h3>
<p><a href="http://msdn.microsoft.com/en-us/library/dd268536(v=vs.100).aspx" target="_blank">Tuple</a> is a .Net 4 item. If you are using a previous version of .Net use the <a href="http://msdn.microsoft.com/en-us/library/vstudio/5tbh8a42(v=vs.90).aspx" target="_blank">KeyValuePair</a> structure instead.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D967&amp;title=C%23%3A%20Combine%20Two%20Values%20Together%20From%20a%20List%20Into%20Pairs" id="wpa2a_4"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=967</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Hyper-V: Creating and Managing a Minimal 2012 installation from Windows 7</title>
		<link>http://OmegaCoder.com/?p=950</link>
		<comments>http://OmegaCoder.com/?p=950#comments</comments>
		<pubDate>Mon, 24 Sep 2012 00:52:05 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[How To]]></category>
		<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[WIndows 7]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=950</guid>
		<description><![CDATA[This is the process I used to create and install a Hyper-V 2012 minimal installation on my network on its own machine and manage it from a different machine running Windows 7. This installation targets two machines on a Workgroup network. Below are the steps taken for each of the machines. Step Server Client Summary/Links [...]]]></description>
				<content:encoded><![CDATA[<p>This is the process I used to create and install a Hyper-V 2012 minimal installation on my network on its own machine and manage it from a different machine running Windows 7. This installation targets two machines on a Workgroup network. Below are the steps taken for each of the machines.</p>
<table border="0" cellspacing="20" cellpadding="4">
<tbody>
<tr>
<td valign="top">Step</td>
<td valign="top" width="200">Server</td>
<td valign="top" width="200">Client</td>
<td valign="top">Summary/Links</td>
</tr>
<tr>
<td valign="top">1</td>
<td valign="top" width="200">Install Hyper-V on the Server</td>
<td valign="top" width="200">Install Windows 7</td>
<td valign="top"></td>
</tr>
<tr>
<td valign="top">2</td>
<td valign="top" width="200">Rename (Option 2)</td>
<td valign="top" width="200"></td>
<td valign="top">Name your server something meaningful. I named my “HyperV”. <img class="wlEmoticon wlEmoticon-smile" style="border-style: none;" src="http://omegacoder.com/wp-content/uploads/2012/09/wlEmoticon-smile.png" alt="Smile" /></td>
</tr>
<tr>
<td valign="top">3</td>
<td valign="top" width="200">Get IP Address</td>
<td valign="top" width="200">Add Server IP to Hosts file<br />
Windows\System32\Drivers\etc</td>
<td valign="top">Allows for quicker access during remote desktop. Note this step may ignored if the Server gets a dynamic IP. If that is the case the suggested option is to change the DNS server/gateway/router or whatever it is on the system to make it static.</td>
</tr>
<tr>
<td valign="top">4</td>
<td valign="top" width="200">Enable Remote Desktop for all clients<br />
7) Remote Desktop</td>
<td valign="top" width="200">Remote to Server</td>
<td valign="top">If you have issues at this point, pinging the server won’t tell you anything. The server is behind its firewall. See the below section miscellaneous commands to turn off the firewall.</td>
</tr>
<tr>
<td valign="top">5</td>
<td valign="top" width="200">5) Do Windows Update Full</td>
<td valign="top" width="200"></td>
<td valign="top">Get the latest and greatest</td>
</tr>
<tr>
<td valign="top">6</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">Download / Install<br />
Remote Server Administration Tools For Windows 7 With Service Pack 1<br />
(<a href="http://www.microsoft.com/en-us/download/details.aspx?id=7887" target="_blank">link</a>)</td>
<td valign="top">This allows you to create VMs from windows 7. Verify that there is not a new version since this blog was written.</td>
</tr>
<tr>
<td valign="top">7</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">Follow install instruction’s on the download page (or the W7 Remote admin tools window which pops up after install) to turn on the newly installed windows 7 feature:<br />
Remote Server Administration Tools</td>
<td valign="top">Control Panel –&gt; Programs –&gt; Programs and Features –&gt; Turn Windows features on or off –&gt; Remote Server Administration tools –&gt; Select the tools needed (Hyper-V tools)</td>
</tr>
<tr>
<td valign="top">8</td>
<td valign="top" width="200">3) Create Local Admin Account the step #3 on the sconfig.cmd shell.</td>
<td valign="top" width="200"></td>
<td valign="top">This account will be used to access the sever either during remote sessions. Note you might want to use the name of the client computer’s account for the name/password. Otherwise you will need to do an additional step #11 on the client.</td>
</tr>
<tr>
<td valign="top">9</td>
<td valign="top" width="200">-Install On Server-</td>
<td valign="top" width="200">-Install on Client-</td>
<td valign="top"><a href="http://archive.msdn.microsoft.com/HVRemote">Hyper-V Remote Management Configuration Utility</a><br />
This is helps minimize the number of operations needed to configure a hyper-v setup on both the server and a remote server operation. Note this will help deduce any problems which might occur. This utility was made for a previous version of Hyper-V and for Windows 7. As of this writing it is being updated to be used on Windows 8. We will be following the 10-second guide on its page for “Client and Server both workgroup” but skipping steps no longer needed since this version of Hyper-V server has some of those commands offered on the initial boot screen.</td>
</tr>
<tr>
<td valign="top">9</td>
<td valign="top" width="200">cscript hvremote.wsf /add:{account name used in #8}</td>
<td valign="top" width="200"></td>
<td valign="top">This step prepares for the remote admin access for hyper-v.</td>
</tr>
<tr>
<td valign="top">10</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">cscript hvremote.wsf<br />
/anondcom:grant</td>
<td valign="top">Check the script for “Granted Remote DCOM Access to Anonymous Logon” for success</td>
</tr>
<tr>
<td valign="top">11</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">cmdkey<br />
/add:servername<br />
/user:servername\account<br />
/pass</td>
<td valign="top">This step is only needed if either the client’s account  or even just the password is different than what is done.  (/pass is the actual, though in some situations to save the password use /pass:{actual passsword}</td>
</tr>
<tr>
<td valign="top">12</td>
<td valign="top" width="200">cscript hvremote.wsf<br />
/show<br />
/target:{clinetComputerName}</td>
<td valign="top" width="200">cscript hvremote.wsf<br />
/show<br />
/target:{ServerName}</td>
<td valign="top">Identifies problems on either the client or the server.</td>
</tr>
<tr>
<td valign="top">13</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">Run Hyper-V manager<br />
Connect to Server</td>
<td valign="top">If there is a problem here and one cannot connect to the server got step 12 and investigate.</td>
</tr>
<tr>
<td valign="top">14</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">(Hyper-V Manager)<br />
Virtual Network Manager</td>
<td valign="top">Setup networking for victuals to access the network. See next step in Virtual Network Manager (VNM)</td>
</tr>
<tr>
<td valign="top">15</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">(Hyper-V Manager &#8211; VNM )<br />
Add “External” virtual network</td>
<td valign="top">Just name the network to use with Virtuals and accept that pending changes may disrupt the network. This may take awhile..so give it time.</td>
</tr>
<tr>
<td valign="top">16</td>
<td valign="top" width="200"></td>
<td valign="top" width="200">(Hyper-V Manager)<br />
Create a Virtual!</td>
<td valign="top">Dust off that old ISO and create a virtual to remember. Just realize that the browse operation is from the server and not your client.</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<h3>Misc commands</h3>
<table width="800" border="0" cellspacing="20" cellpadding="4">
<tbody>
<tr>
<td valign="top" width="400">NET SHARE Images=D:\Images /GRANT:Everyone,FULL</td>
<td valign="top" width="400">Create a Share drive.</td>
</tr>
<tr>
<td valign="top" width="400">Get-VMSwitch</td>
<td valign="top" width="400">Lists all the virtual switches</td>
</tr>
<tr>
<td valign="top" width="400">netsh advfirewall set allprofiles state off</td>
<td valign="top" width="400">Turn off the firewall. Note that the firewall on a Hyper-V machine will block any ping from your internal network.</td>
</tr>
</tbody>
</table>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D950&amp;title=Hyper-V%3A%20Creating%20and%20Managing%20a%20Minimal%202012%20installation%20from%20Windows%207" id="wpa2a_6"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=950</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fear and Loathing in Visual Studio 2012 at 256 Colors</title>
		<link>http://OmegaCoder.com/?p=942</link>
		<comments>http://OmegaCoder.com/?p=942#comments</comments>
		<pubDate>Thu, 12 Jul 2012 03:54:04 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[Visual Studio 2012]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=942</guid>
		<description><![CDATA[While working with the Visual Studio 2012 RC I experienced the downside to the new color scheme. When I Citrix-ed into my workstation I adjusted the colors to the 256 color set for better performance over the wire. That was not good. Now I normally work with the dark color theme and discovered that the [...]]]></description>
				<content:encoded><![CDATA[<p>While working with the Visual Studio 2012 RC I experienced the downside to the new color scheme. When I Citrix-ed into my workstation I adjusted the colors to the 256 color set for better performance over the wire. That was not good.</p>
<p>Now I normally work with the dark color theme and discovered that the appropriately shaded colors simply ran together to the point where text editor window became almost as one the other windows.</p>
<p>Ok, a picture is worth a thousand bug reports, <em>ahem issue reports, </em>so let me show you.</p>
<h3>Dark Theme</h3>
<table width="400" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td valign="top" width="200">256 Colors</td>
<td valign="top" width="200">Full Color</td>
</tr>
<tr>
<td valign="top" width="200"><a href="http://omegacoder.com/wp-content/uploads/2012/07/256-colors-dark.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="256 colors dark" src="http://omegacoder.com/wp-content/uploads/2012/07/256-colors-dark_thumb.png" alt="256 colors dark" width="850" height="477" border="0" /></a></td>
<td valign="top" width="200"><a href="http://omegacoder.com/wp-content/uploads/2012/07/True-Colors-Dark.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="True Colors Dark" src="http://omegacoder.com/wp-content/uploads/2012/07/True-Colors-Dark_thumb.png" alt="True Colors Dark" width="858" height="485" border="0" /></a></td>
</tr>
</tbody>
</table>
<h3>Light Theme</h3>
<p>I decided to switch to the light theme,<em> not that my specific editor colors which work on the dark, do not play well in the light and that has nothing to do with this situation,</em> but notice how in 256 colors the golden rod color becomes prominent in the windows.</p>
<table width="402" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td valign="top" width="200">256 Colors</td>
<td valign="top" width="200">Full Colors</td>
</tr>
<tr>
<td valign="top" width="200"><a href="http://omegacoder.com/wp-content/uploads/2012/07/256-colors-Light.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="256 colors Light" src="http://omegacoder.com/wp-content/uploads/2012/07/256-colors-Light_thumb.png" alt="256 colors Light" width="841" height="458" border="0" /></a></td>
<td valign="top" width="200"><a href="http://omegacoder.com/wp-content/uploads/2012/07/True-Colors-Light.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="True Colors Light" src="http://omegacoder.com/wp-content/uploads/2012/07/True-Colors-Light_thumb.png" alt="True Colors Light" width="848" height="471" border="0" /></a></td>
</tr>
</tbody>
</table>
<h3>VS2010</h3>
<p>How did VS 2010 look in 256 Colors? Just fine thank you!</p>
<p><em>Ahh nothing ages well like a good editor; Chateau De Studio 2010! </em></p>
<p><em><a href="http://omegacoder.com/wp-content/uploads/2012/07/256-VS-2010.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="256 VS 2010" src="http://omegacoder.com/wp-content/uploads/2012/07/256-VS-2010_thumb.png" alt="256 VS 2010" width="854" height="490" border="0" /></a></em></p>
<h3>Summary</h3>
<p>Long story short don’t use the non true color setting when remoting in to use Visual Studio 2012!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D942&amp;title=Fear%20and%20Loathing%20in%20Visual%20Studio%202012%20at%20256%20Colors" id="wpa2a_8"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=942</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Asp.Net C#: Upgrading Website to Latest Version Gotchas and How to Resolve</title>
		<link>http://OmegaCoder.com/?p=910</link>
		<comments>http://OmegaCoder.com/?p=910#comments</comments>
		<pubDate>Thu, 22 Mar 2012 13:51:41 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[.Net 3.5]]></category>
		<category><![CDATA[.Net 4]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=910</guid>
		<description><![CDATA[One can get lost in the weeds when upgrading an asp.net .Net 1 website to anything from .Net 2 through .Net 4.  One of the biggest problems after the initial conversion is that when built each page or control throws a build error: Could not load type &#8216;MyNamespace.myWebPage’. The issue stems from the fact that [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://omegacoder.com/wp-content/uploads/2012/03/iStock_000015438998XSmall.jpg"><img style="background-image: none; margin: 0px 10px 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; padding-top: 0px; border: 0px;" title="iStock_000015438998XSmall" src="http://omegacoder.com/wp-content/uploads/2012/03/iStock_000015438998XSmall_thumb.jpg" alt="iStock_000015438998XSmall" width="143" height="96" align="left" border="0" /></a>One can get lost in the weeds when upgrading an asp.net .Net 1 website to anything from .Net 2 through .Net 4.  One of the biggest problems after the initial conversion is that when built each page or control throws a build error:</p>
<blockquote><p>Could not load type &#8216;MyNamespace.myWebPage’.</p></blockquote>
<p>The issue stems from the fact that things changed, <em>made life easier for new projects,</em> and namespaces which were required were removed and certain attributes changed. To resolve the above issue follow these steps presented in this article.</p>
<h4>In the code behind file</h4>
<ol>
<li>Remove the namespace scope. In the example below remove the highlighted lines:
<pre class="brush: csharp; gutter: false; highlight: [1,2,4];">namespace MyNamespace
{
    public class myWebPage : System.Web.UI.Page {}
}</pre>
</li>
<li>Add the modifier partial to the class definition to make it look like this
<pre class="brush: csharp; gutter: false;">public partial class myWebPage : System.Web.UI.Page { ... }</pre>
</li>
</ol>
<h4>In the aspx File</h4>
<p>Which initially looks like this:</p>
<pre class="brush: csharp; gutter: false;">&lt;%@ Page language="c#" AutoEventWireup="false"
                       Codebehind="myWebPage.aspx.cs"
                       Inherits="MyNamespace.myWebPage" %&gt;</pre>
<ol>
<li>Change the attribute Codebehind to CodeFile.</li>
<li>Remove the namespace from the value found in the attribute Inherits.</li>
</ol>
<p>The result should look like this:</p>
<pre class="brush: csharp; gutter: false;">&lt;%@ Page language="c#" AutoEventWireup="false"
                       Codefile="myWebPage.aspx.cs"
                       Inherits="myWebPage" %&gt;</pre>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D910&amp;title=Asp.Net%20C%23%3A%20Upgrading%20Website%20to%20Latest%20Version%20Gotchas%20and%20How%20to%20Resolve" id="wpa2a_10"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=910</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Silverlight (How To): Manipulation of Dynamic Selection Rubber Band in C#</title>
		<link>http://OmegaCoder.com/?p=897</link>
		<comments>http://OmegaCoder.com/?p=897#comments</comments>
		<pubDate>Sun, 12 Feb 2012 21:53:42 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Canvas]]></category>
		<category><![CDATA[Mouse Movement]]></category>
		<category><![CDATA[Mouse Positioning]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=897</guid>
		<description><![CDATA[One of the basic tenets of WYSIWYG is to be able to create a rubber band region using the mouse to give the user the ability to create a selectable region. This article demonstrates how to do that in any version of Silverlight and the user is given the tools to create such a bounding [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://omegacoder.com/wp-content/uploads/2012/02/iStock_000017079915XSmall.jpg"><img style="background-image: none; border-right-width: 0px; margin: 0px 10px 5px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Large group of women exercising in the park" border="0" alt="Large group of women exercising in the park" align="left" src="http://omegacoder.com/wp-content/uploads/2012/02/iStock_000017079915XSmall_thumb.jpg" width="228" height="284" /></a>One of the basic tenets of WYSIWYG is to be able to create a rubber band region using the mouse to give the user the ability to create a selectable region. This article demonstrates how to do that in any version of Silverlight and the user is given the tools to create such a bounding rectangle in any circumstances via the usage of some basic building blocks in Silverlight. </p>
<p>The below picture (<em>not the one on the left</em>) shows our goal, the dynamic creation of a bounding rubber band (a rectangle control for this demonstration) in a canvas. The below canvas is drawn in black (visually grey due to the opacity set) while the bounding rectangle shows itself in red. </p>
<p><a href="http://omegacoder.com/wp-content/uploads/2012/02/RubberBanding.png"><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="RubberBanding" border="0" alt="RubberBanding" src="http://omegacoder.com/wp-content/uploads/2012/02/RubberBanding_thumb.png" width="218" height="145" /></a></p>
<p>The user starts the process with an initial click which designates a start location of an <em>upper left </em>point for our bounding box with a mouse click.&#160; Once the click happens the mouse cursor changes to a hand (<u>if moving to the lower right</u>) as a visible indicator that the process has started. While user continues to move to the lower right the band grows and while the mouse button has yet to be let go or released. For the demo a bounded number is shown is which relates the actual dynamic change in the X (horizontal) position. That is done for this article only and the above picture shows the rectangle with an X size of 123 pixels and can still be grown as shown by the hand icon.</p>
<h3>Initial Xaml</h3>
<p>In the page’s xaml we add a grid and a canvas as such this: </p>
<pre class="brush: xml; gutter: false;">&lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height=&quot;33*&quot; /&gt;
        &lt;RowDefinition Height=&quot;267*&quot; /&gt;
    &lt;/Grid.RowDefinitions&gt;
    &lt;Grid.ColumnDefinitions&gt;
        &lt;ColumnDefinition Width=&quot;32*&quot; /&gt;
        &lt;ColumnDefinition Width=&quot;568*&quot; /&gt;
    &lt;/Grid.ColumnDefinitions&gt;
    &lt;Canvas x:Name=&quot;cMain&quot;
            MouseLeftButtonDown=&quot;cMain_MouseLeftButtonDown&quot;
            MouseLeftButtonUp=&quot;cMain_MouseLeftButtonUp&quot;
            MouseMove=&quot;cMain_MouseMove&quot;
            Grid.Row=&quot;1&quot;
            Grid.Column=&quot;1&quot;&gt;
        &lt;TextBlock Width=&quot;100&quot;
                    Height=&quot;30&quot;
                    Text=&quot;{Binding XValue, ElementName=userControl}&quot;
                    /&gt;
        &lt;Rectangle Fill=&quot;Black&quot;
                    Width=&quot;550&quot;
                    Height=&quot;200&quot;
                    Opacity=&quot;.25&quot;/&gt;
    &lt;/Canvas&gt;
&lt;/Grid&gt;</pre>
<p>The things to note are that the canvas is in a grid which is offset from the initial by 30 pixels in both axis. We then place a rectangle on the canvas which is our area which will be our <em>strike zone </em>where we will intercept the messages mouse events. <em>We have a strike zone because individual controls in a canvas, such as texblocks have whitespace between them and the canvas will not get the mouse clicks and we want to be able to capture the process at all locations on the canvas</em>; hence we fill up the canvas with our strike zone as to be ensured that the events are consumed properly by the code.&#160; </p>
<p>When the user clicks within the strike zone the process starts as signified by a cursor change to the hand, as the user moves within the zone the rubber banding increases and when the mouse button is let up the process ends and the cursor is returned to its previous state.</p>
<h3>Initial Properties</h3>
<p>Here are the three variables we will use during this process:</p>
<pre class="brush: xml; gutter: false;">private int _xValue;

public int XValue
{
    get { return _xValue; }
    set
    {
        _xValue = value;
        OnPropertyChanged( &quot;XValue&quot; );
    }
}

private Point OriginatingPostionOnCanvas { get; set; }

private Rectangle RubberBandBox { get; set; }</pre>
<p>Since the XValue property is reflected on the screen in a text box it reports all changes by using&#160; INotifyPropertyChanged which our class handles in a standard way for notify property (not shown). Followed by that is our initial click location named OriginatingPostionOnCanvas which will dictate the upper left (or lower right) location of the rubber band rectangle which we will dynamically create. The last variable is the actual dynamic rectangle control named RubberBandBox which will be created and modified during the process.</p>
<h3>Event Mouse Left Button Down</h3>
<p>We will handle three events during this process. The first is the when the user clicks and begins to hold down the mouse button:</p>
<pre class="brush: csharp; gutter: false;">private void cMain_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
{
    OriginatingPostionOnCanvas = e.GetPosition( cMain );

    RubberBandBox = new Rectangle() { Width = 1, 
                                      Height = 1, 
                                      Fill = new SolidColorBrush( Colors.Red ), 
                                      Opacity = .1
                                    };

    RubberBandBox.SetValue( Canvas.LeftProperty, OriginatingPostionOnCanvas.X);
    RubberBandBox.SetValue( Canvas.TopProperty,  OriginatingPostionOnCanvas.Y );

    cMain.Children.Add( RubberBandBox );
}</pre>
<p>Our goals here are simple:</p>
<ol>
<li>Get and store the location where the user clicked in relation to the canvas. </li>
<li>Create&#160; and store the rectangle in red and with an opacity which does allows the user to see what is being selected. </li>
<li>Setting the initial location of the rectangle and adding it to the children of the canvas. </li>
</ol>
<h3>Event Mouse Move</h3>
<p>The user is moving and we must adjust the rectangle as appropriate for the target direction. Note we also have to handle when the user moves to the upper left instead of the lower right…. So when that happens we will change the cursor to a Stylus (the dot) for visual indication that we are getting a reverse band situation.</p>
<pre class="brush: csharp; gutter: true;">private void cMain_MouseMove(object sender, MouseEventArgs e)
{
    if (RubberBandBox == null)
        return;

    Point pointMovedTo = e.GetPosition( cMain );

    double xDelta = pointMovedTo.X - OriginatingPostionOnCanvas.X;
    double yDelta = pointMovedTo.Y - OriginatingPostionOnCanvas.Y;

    LayoutRoot.Cursor = ((xDelta &gt; 0) &amp;&amp; (yDelta &gt; 0)) ? Cursors.Hand : Cursors.Stylus;

    if (LayoutRoot.Cursor == Cursors.Hand)
    {
        RubberBandBox.Height = yDelta;
        RubberBandBox.Width  = xDelta;
    }
    else if (LayoutRoot.Cursor == Cursors.Stylus)
    {
        RubberBandBox.Height = Math.Abs( yDelta );
        RubberBandBox.Width = Math.Abs( xDelta );

        if (xDelta &lt; 0)
            RubberBandBox.SetValue( Canvas.LeftProperty, pointMovedTo.X );

        if (yDelta &lt; 0)
            RubberBandBox.SetValue( Canvas.TopProperty, pointMovedTo.Y );
    }

    XValue = (int) (e.GetPosition( cMain ).X - OriginatingPostionOnCanvas.X);
}</pre>
<table border="0" cellspacing="0" cellpadding="2" width="95%">
<thead>
<tr>
<td style="text-align: center" colspan="2">Explanation</td>
</tr>
</thead>
<tbody>
<tr>
<td valign="top" width="86">Line 3</td>
<td valign="top">The mouse can move through the canvas during times we are not processing. We need to check that and only process when we have an actual rectangle on the canvas.</td>
</tr>
<tr>
<td valign="top" width="86">Line 6</td>
<td valign="top">Extract the current location in relation to the canvas.</td>
</tr>
<tr>
<td valign="top" width="86">Line 8-9</td>
<td valign="top">Get the change differences for x and y as named deltas.</td>
</tr>
<tr>
<td valign="top" width="86">Line 11</td>
<td valign="top">If the deltas retrieved are in the positive we have a drag to the lower right and that is designated by or specifying the cursor to a hand. If not, the deltas indicate that movement is upwards and to the left; regardless change the&#160; cursor to the stylus. </td>
</tr>
<tr>
<td valign="top" width="86">Line 13</td>
<td valign="top">If we are in the <em>hand state</em>, we want to grow (or decrease) the rectangle in that direction towards the lower right.</td>
</tr>
<tr>
<td valign="top" width="86">Line 18</td>
<td valign="top">If we are in the <em>stylus state</em>, there is a negative growth either in the x or y axis. Handle the negatives while changing the height and width. Depending on which delta is negative, handle the new location position of the upper left hand position of our bounding rectangle which will follow the mouse. </td>
</tr>
<tr>
<td valign="top" width="86">Line 30</td>
<td valign="top">Inform the user of the current X axis location of the mouse whether positive or negative. </td>
</tr>
</tbody>
</table>
<h3>Event Mouse Left Button Up</h3>
<p>This is our final event we have to handle. We do a safety check on whether we are actually in operations, and if we are then we simply return the cursor to its original state and remove the rectangle from the canvas’ children. </p>
<pre class="brush: csharp; gutter: false;">private void cMain_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
{
    if (RubberBandBox == null)
        return;

    // Return to the previous state; whatever it is, the OS handles it.
    LayoutRoot.Cursor = null; 

    cMain.Children.Remove( RubberBandBox );

    // Show that we are not processing by making this null.
    RubberBandBox = null; 
}</pre>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D897&amp;title=Silverlight%20%28How%20To%29%3A%20Manipulation%20of%20Dynamic%20Selection%20Rubber%20Band%20in%20C%23" id="wpa2a_12"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=897</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Git: Rollback (or Undo) a Pull from an External Repository To Return To A Previous Stable Commit State</title>
		<link>http://OmegaCoder.com/?p=889</link>
		<comments>http://OmegaCoder.com/?p=889#comments</comments>
		<pubDate>Wed, 18 Jan 2012 00:49:02 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[Git]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=889</guid>
		<description><![CDATA[Zen is not possible and we need to return to a state of peace within Git! In the case where one pulls from a repository such as GitHub and something breaks, one may want to undo that pull. Here are the steps to rollback to a previous version using Git. Note if you have any [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://omegacoder.com/wp-content/uploads/2012/01/iStock_000017591577XSmall.jpg"><img style="background-image: none; margin: 0px 10px 10px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; padding-top: 0px; border: 0px;" title="iStock_000017591577XSmall" src="http://omegacoder.com/wp-content/uploads/2012/01/iStock_000017591577XSmall_thumb.jpg" alt="iStock_000017591577XSmall" width="221" height="148" align="left" border="0" /></a><em>Zen is not possible and we need to return to a state of peace within Git!</em></p>
<p>In the case where one pulls from a repository such as GitHub and something breaks, one may want to undo that pull. Here are the steps to rollback to a previous version using Git.</p>
<p><span style="color: #ff0000;">Note if you have any work in the local<strong> working directory</strong> done after the pull, it will be lost using this method. </span></p>
<p><span style="color: #000000;">Our goal is to move to the Head to the last snapshot before the pull and return the Zen to us.</span></p>
<h3>Steps</h3>
<ol>
<li>Find the SHA-1 version using reflog. <em>The reflog is interactive and one uses a q to exit out.<br />
</em></p>
<pre class="brush: plain; gutter: false;">git reflog</pre>
<p>That will bring up a list such as this:</p>
<pre class="brush: plain; gutter: false; highlight: [2];">da88c95 HEAD@{0}: pull origin br_1.0.0: Merge made by recursive.
26a96f1 HEAD@{1}: commit: Non movable end block not being placed at end time fix.
abc8366 HEAD@{2}: commit: Created durationd dependancy to adjust the timeline correctly to the actual time.
1b3ca89 HEAD@{3}: commit: _ReSharper directory ignored
5d579ba HEAD@{4}: pull origin br_1.0.0: Fast-forward
68fbb98 HEAD@{5}: commit: Ignore tests which are creating timelines and provisioned timelines</pre>
<p>&nbsp;</p>
<p>We are interested in the second line as highlighted above which is before the pull.</li>
<li>Then we want to move the head to  either the hash or the symbolic name before the pull so we do a reset command which targets the local working directory and moves it to the target commit.
<pre class="brush: plain; gutter: false;">git reset --hard 26a96f1</pre>
<p>or (<em><span style="color: #ff0000;">in this case yours may be different</span></em>)</p>
<p>&nbsp;</p>
<pre class="brush: plain; gutter: false;">git reset --hard HEAD@{1}:</pre>
</li>
</ol>
<p>The &#8212; hard options  brings about changes to the working copy and sets us to the state before the pull. Now interestingly enough if we look at the log it shows our reset operation as the top level log item which has the same hash as where we wanted to go:</p>
<pre class="brush: plain; gutter: false;">26a96f1 HEAD@{0}: 26a96f1: updating HEAD
da88c95 HEAD@{1}: pull origin br_1.0.0: Merge made by recursive.
26a96f1 HEAD@{2}: commit: Non movable end block not being placed at end time fix.
abc8366 HEAD@{3}: commit: Created durationd dependancy to adjust the timeline correctly to the actual time.
1b3ca89 HEAD@{4}: commit: _ReSharper directory ignored
5d579ba HEAD@{5}: pull origin br_1.0.0: Fast-forward</pre>
<h3>Final Thoughts</h3>
<p>Of course you have only delayed the inevitable. One usually does this because something about the current state of changes in the remote is just not palatable and someone else is working on it. When ready do a normal pull to pull down those <em>new </em>changes and merge.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D889&amp;title=Git%3A%20Rollback%20%28or%20Undo%29%20a%20Pull%20from%20an%20External%20Repository%20To%20Return%20To%20A%20Previous%20Stable%20Commit%20State" id="wpa2a_14"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=889</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xaml: Adding Visibility Behaviors Using Blend to A DataGrid for WPF or Silverlight</title>
		<link>http://OmegaCoder.com/?p=876</link>
		<comments>http://OmegaCoder.com/?p=876#comments</comments>
		<pubDate>Sun, 08 Jan 2012 17:19:16 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[Blend]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Xaml]]></category>
		<category><![CDATA[Behavior]]></category>
		<category><![CDATA[DataGrid]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=876</guid>
		<description><![CDATA[In Xaml the determining when to trigger the visibility, or the hiding of  controls or their functionality is a key concept of doing either WPF or Silverlight programming. This article builds upon my article C#: WPF and Silverlight DataGrid Linq Binding Example Using Predefined Column Header Names in Xaml where we are going to add [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://omegacoder.com/wp-content/uploads/2012/01/iStock_000015143879XSmall.jpg"><img style="background-image: none; margin: 0px 10px 5px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; padding-top: 0px; border-width: 0px;" title="iStock_000015143879XSmall" src="http://omegacoder.com/wp-content/uploads/2012/01/iStock_000015143879XSmall_thumb.jpg" alt="iStock_000015143879XSmall" width="244" height="238" align="left" border="0" /></a>In Xaml the determining when to trigger the visibility, or the hiding of  controls or their functionality is a key concept of doing either WPF or Silverlight programming. This article builds upon my article <a href="http://omegacoder.com/?p=719" target="_blank">C#: WPF and Silverlight DataGrid Linq Binding Example Using Predefined Column Header Names in Xaml</a> where we are going to add behaviors to the datagrid shown.  (<em>Don’t worry about reading the article, for I will get you up to speed with the code snippets in this article.</em>) We will use Microsoft’s Expression Blend product to do the dirty work of xaml modification to our DataGrid and it will be shown in a step by step process.</p>
<h3>Concept</h3>
<p>In the previous article the idea was to load our datagrid with two columns of data. The first column showed us a filename and the second column displayed a modified filename with a count in it. We will take that one step further and have a description show up with the file size. Here is the resulting look:</p>
<p><a href="http://omegacoder.com/wp-content/uploads/2012/01/Inital-with-Description.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px; border-width: 0px;" title="Inital with Description" src="http://omegacoder.com/wp-content/uploads/2012/01/Inital-with-Description_thumb.png" alt="Inital with Description" width="275" height="116" border="0" /></a></p>
<p>The user gets the description when the row is clicked.</p>
<p>But what if we wanted to disable that functionality and <em>automatically </em>show the user all the items when the mouse hovers over the datagrid such as</p>
<p align="center"><a href="http://omegacoder.com/wp-content/uploads/2012/01/Result.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="Result" src="http://omegacoder.com/wp-content/uploads/2012/01/Result_thumb.png" alt="Result" width="263" height="137" border="0" /></a></p>
<h3>Setup</h3>
<p>First thing we need to do is setup our datagrid. Below is the xaml and the code behind to load our datagrid. Note the datagrid has the RowDetailsVisibiltyMode set to collapsed. That means that when a user clicks on the row, it will only select it and not open up our description. The loading of the ItemsSource happens during the construction and after the initial initialization and is shown in C# in the second pane.</p>
<table border="0" cellspacing="10" cellpadding="4">
<tbody>
<tr>
<td valign="top" width="300">
<pre class="brush: xml; gutter: false;">&lt;DataGrid x:Name="dgPrimary"
            RowDetailsVisibilityMode="Collapsed"&gt;
    &lt;DataGrid.RowDetailsTemplate&gt;
        &lt;DataTemplate&gt;

            &lt;TextBlock FontWeight="Bold"
                        Text="{Binding Size, StringFormat=Size \{0\} (bytes)}" /&gt;

        &lt;/DataTemplate&gt;
    &lt;/DataGrid.RowDetailsTemplate&gt;
    &lt;DataGrid.Columns&gt;
        &lt;DataGridTextColumn Binding="{Binding Original}"
                            Header="File Name Before"
                            IsReadOnly="True" /&gt;
        &lt;DataGridTextColumn Binding="{Binding New}"
                            Header="File Name After"
                            IsReadOnly="True" /&gt;
    &lt;/DataGrid.Columns&gt;
&lt;/DataGrid&gt;</pre>
</td>
<td valign="top" width="300">
<pre class="brush: csharp; gutter: false;">dgPrimary.ItemsSource = 
    new DirectoryInfo( "c:\\" ).GetFiles()
                               .Select( ( fInfo, index ) =&gt; new
                    {
                        Original = fInfo.Name,
                        New = string.Format( "{0}_{1}{2}", 
                                    System.IO.Path.GetFileNameWithoutExtension( fInfo.Name ), 
                                    index, 
                                    System.IO.Path.GetExtension( fInfo.Name ) ),
                        Size = fInfo.Length
                    } );</pre>
</td>
</tr>
</tbody>
</table>
<h3>Behaviors and Blend</h3>
<p>One of the easiest ways to add a <em>behavior [of the action]</em> to a control is to use Blend to add an interaction behavior.  In our case we want a mouse over action to open up all of the Row Details and a secondary action to close them when the mouse leaves. The behavior we need to search for in blend is the <a href="http://msdn.microsoft.com/en-us/library/ff723951(v=Expression.40).aspx" target="_blank">ChangePropertyAction</a>. Below we drag (or add) two behaviors to the datagrid and change the RowDetailsVisibilityMode to visible on mouse enter and to collapsed on mouse leave.</p>
<table border="0" cellspacing="10" cellpadding="4">
<tbody>
<tr>
<td valign="top" width="400"><a href="http://omegacoder.com/wp-content/uploads/2012/01/cpaEnter.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="cpaEnter" src="http://omegacoder.com/wp-content/uploads/2012/01/cpaEnter_thumb.png" alt="cpaEnter" width="402" height="437" border="0" /></a></td>
<td valign="top" width="400"><a href="http://omegacoder.com/wp-content/uploads/2012/01/cpaLeave.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="cpaLeave" src="http://omegacoder.com/wp-content/uploads/2012/01/cpaLeave_thumb.png" alt="cpaLeave" width="397" height="442" border="0" /></a></td>
</tr>
</tbody>
</table>
<p>Then when we build and run the app, the mouse hover over makes the descriptions visible and collapsed depending on the mouse. Here is the final xaml:</p>
<pre class="brush: xml; gutter: false; collapse: true;">&lt;DataGrid x:Name="dgPrimary"
            RowDetailsVisibilityMode="Collapsed"&gt;
    &lt;DataGrid.RowDetailsTemplate&gt;
        &lt;DataTemplate&gt;

            &lt;TextBlock FontWeight="Bold"
                        Text="{Binding Size, StringFormat=Size \{0\} (bytes)}" /&gt;

        &lt;/DataTemplate&gt;
    &lt;/DataGrid.RowDetailsTemplate&gt;
    &lt;DataGrid.Columns&gt;
        &lt;DataGridTextColumn Binding="{Binding Original}"
                            Header="File Name Before"
                            IsReadOnly="True" /&gt;
        &lt;DataGridTextColumn Binding="{Binding New}"
                            Header="File Name After"
                            IsReadOnly="True" /&gt;
    &lt;/DataGrid.Columns&gt;
    &lt;i:Interaction.Triggers&gt;
        &lt;i:EventTrigger EventName="MouseEnter" SourceObject="{Binding ElementName=dgPrimary}"&gt;
            &lt;ei:ChangePropertyAction x:Name="cpaEnter" PropertyName="RowDetailsVisibilityMode"&gt;
                &lt;ei:ChangePropertyAction.Value&gt;
                    &lt;DataGridRowDetailsVisibilityMode&gt;Visible&lt;/DataGridRowDetailsVisibilityMode&gt;
                &lt;/ei:ChangePropertyAction.Value&gt;
            &lt;/ei:ChangePropertyAction&gt;
        &lt;/i:EventTrigger&gt;
        &lt;i:EventTrigger EventName="MouseLeave"&gt;
            &lt;ei:ChangePropertyAction x:Name="cpaLeave"
                PropertyName="RowDetailsVisibilityMode" /&gt;
        &lt;/i:EventTrigger&gt;
    &lt;/i:Interaction.Triggers&gt;</pre>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D876&amp;title=Xaml%3A%20Adding%20Visibility%20Behaviors%20Using%20Blend%20to%20A%20DataGrid%20for%20WPF%20or%20Silverlight" id="wpa2a_16"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=876</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xaml Mammal Presentation Notes</title>
		<link>http://OmegaCoder.com/?p=860</link>
		<comments>http://OmegaCoder.com/?p=860#comments</comments>
		<pubDate>Tue, 13 Dec 2011 18:45:35 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[Presentation]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=860</guid>
		<description><![CDATA[Initial Meeting Notes and code: Xs.Code for WPF &#60;Button Click=&#34;HandleClick&#34; Name=&#34;TestButton&#34; Width=&#34;50&#34; Height=&#34;30&#34; Content=&#34;Click Me!&#34; /&#62; &#60;x:Code&#62; void HandleClick(object sender, RoutedEventArgs eventArgs) { TestButton.Width = 100; TestButton.Content = &#34;Thank you!&#34;; MessageBox.Show(&#34;Hello from Xaml&#34;); } &#60;/x:Code&#62; Links Xaml Intellisense Presenter Xaml Styler buildwindowscontest.com Silveright Lifespan]]></description>
				<content:encoded><![CDATA[<p>Initial Meeting Notes and code:</p>
<p>Xs.Code for WPF</p>
<pre class="brush: xml; gutter: false;">&lt;Button Click=&quot;HandleClick&quot;
        Name=&quot;TestButton&quot;
        Width=&quot;50&quot;
        Height=&quot;30&quot;
        Content=&quot;Click Me!&quot; /&gt;

&lt;x:Code&gt;
            
void HandleClick(object sender, RoutedEventArgs eventArgs)
{
    TestButton.Width = 100;
    TestButton.Content = &quot;Thank you!&quot;;
    MessageBox.Show(&quot;Hello from Xaml&quot;);
}
      
&lt;/x:Code&gt;</pre>
<p><font face="Courier New"></font></p>
<h2>Links</h2>
<p><font face="Courier New"><a href="http://karlshifflett.wordpress.com/2010/03/21/visual-studio-2010-xaml-editor-intellisense-presenter-extension" target="_blank">Xaml Intellisense Presenter</a> </font></p>
<p><font face="Courier New"><a href="http://xamlstyler.codeplex.com/" target="_blank">Xaml Styler</a></font></p>
<p><a href="http://buildwindowscontest.com/">buildwindowscontest.com</a></p>
<p><a href="http://support.microsoft.com/gp/lifean" target="_blank" class="broken_link">Silveright Lifespan</a></p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D860&amp;title=Xaml%20Mammal%20Presentation%20Notes" id="wpa2a_18"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=860</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.Net Regex: Can Regular Expression Parsing be Faster than XmlDocument or Linq to Xml?</title>
		<link>http://OmegaCoder.com/?p=850</link>
		<comments>http://OmegaCoder.com/?p=850#comments</comments>
		<pubDate>Fri, 25 Nov 2011 18:03:05 +0000</pubDate>
		<dc:creator>OmegaMan</dc:creator>
				<category><![CDATA[Linq To Xml]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[XMLDocument]]></category>

		<guid isPermaLink="false">http://OmegaCoder.com/?p=850</guid>
		<description><![CDATA[Most of the time one needs the power of the xml parser whether it is the XmlDocument or Linq to Xml to manipulate and extract data. But what if I told you that in some circumstances regular expressions might be faster? Most conventional development thinking has branded regex processing as slow and the thought of [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://omegacoder.com/wp-content/uploads/2011/11/iStock_000017256683XSmall1.jpg"><img style="background-image: none; margin: 0px 10px 5px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; padding-top: 0px; border: 0px;" title="iStock_000017256683XSmall" src="http://omegacoder.com/wp-content/uploads/2011/11/iStock_000017256683XSmall_thumb1.jpg" alt="iStock_000017256683XSmall" width="141" height="140" align="left" border="0" /></a>Most of the time one needs the power of the xml parser whether it is the XmlDocument or Linq to Xml to manipulate and extract data. But what if I told you that in some circumstances regular expressions might be faster?</p>
<p>Most conventional development thinking has branded regex processing as slow and the thought of using regex on xml might seem counter intuitive. In a continuation of articles I again want to dispel those thoughts and provide a real world example where Regular Expression parsing is not only on par with other tools in the .Net world but sometimes faster. The results of my speed test may surprise you;  and hopefully show that regular expressions are not as slow as believed, <em>if not faster!</em></p>
<p>See: <a href="http://OmegaCoder.com/?p=324" target="_blank">Are C# .Net Regular Expressions Fast Enough for You?</a></p>
<h3>Real World Scenario</h3>
<p>There was a developer on the MSDN forums who needed the ability to count URLs in multiple xml files. <em>(See the actual post </em><a href="http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/f91a43c8-f60b-4384-ad42-1d6bb1bcfd15" target="_blank"><em>count the urls in xml file</em></a><em> on Msdn) </em>The poster received three distinct replies, one to use XMLDocument, another provided a Linq to XML solution and I chimed in with the regular expression method. The poster took the XMLDocument method and marked as the answer, but could he have done better?</p>
<p>I thought so…</p>
<p>So I took the three replies and distilled them down into their core processing and wrapped them in a similar IO extraction layer and proceeded to time them. I created 48 xml files with over one hundred thousand urls to find for a total of 13 meg on disk. I then proceeded to run the test all in release mode to get the results.  (See below section Setup to get a gist repository of the code).</p>
<h3>Real World Result</h3>
<p>Five tests, each test name is the technology and the user as found on the original msdn post. In red is the slowest and fastest time. Remember XmlDoc is the one the user choose as the answer.</p>
<p><span style="color: #004000; font-family: Consolas;"><strong>Test 1</strong><br />
Regex           found 116736 urls in 00:00:00.1843576<br />
XmlLinq_Link_FR found 116736 urls in 00:00:00.2662190<br />
XmlDoc_Hasim()  found 116736 urls in 00:00:00.<span style="color: #ff0000;">3534628</span></span></p>
<p><span style="color: #004000; font-family: Consolas;"><strong>Test 2</strong><br />
Regex           found 116736 urls in 00:00:00.2317883<br />
XmlLinq_Link_FR found 116736 urls in 00:00:00.2792730<br />
XmlDoc_Hasim()  found 116736 urls in 00:00:00.2694969</span></p>
<p><span style="color: #004000; font-family: Consolas;"><strong>Test 3</strong><br />
Regex           found 116736 urls in 00:00:00.<span style="color: #ff0000;">1646719<br />
</span>XmlLinq_Link_FR found 116736 urls in 00:00:00.2333891<br />
XmlDoc_Hasim()  found 116736 urls in 00:00:00.2625176</span></p>
<p><span style="color: #004000; font-family: Consolas;"><strong>Test 4</strong><br />
Regex           found 116736 urls in 00:00:00.1677931<br />
XmlLinq_Link_FR found 116736 urls in 00:00:00.2258825<br />
XmlDoc_Hasim()  found 116736 urls in 00:00:00.2590841</span></p>
<p><span style="color: #004000; font-family: Consolas;"><strong>Test 5</strong><br />
Regex           found 116736 urls in 00:00:00.1668231<br />
XmlLinq_Link_FR found 116736 urls in 00:00:00.2278445<br />
XmlDoc_Hasim()  found 116736 urls in 00:00:00.2649262</span></p>
<p>&nbsp;</p>
<p>Wow! Regex consistently performed better, even when there was no caching of the files as found for the first run! Note that the time is Hours : Minutes : Seconds and regex’s is the fastest at 164 millseconds to parse 48 files! Regex worst time of 184 milleseconds is still better than the other two’s best times.</p>
<p>How was this all done? Let me show you.</p>
<h3>Setup</h3>
<p>Ok what magic or trickery have I played? All tests are run in a C# .Net 4 Console application in release mode. I have created a public <a href="https://gist.github.com/1393981" target="_blank">Gist (Regex vs Xml)</a> repository of the code and data which is actually valid Git repository<em> for anyone how may want to add their tests</em>, but let me detail what I did here on the blog as well.</p>
<p>The top level operation found in the Main looks like this where I run the tests 5 times</p>
<pre class="brush: csharp; gutter: false;">Enumerable.Range( 1, 5 )
            .ToList()
            .ForEach( tstNumber =&gt;
            {
                Console.WriteLine( "Test " + tstNumber );
                Time( "Regex", RegexFindXml );
                Time( "XmlLinq_Link_FR", XmlLinq_Link_FR );
                Time( "XmlDoc_Hasim()", XmlDoc_Hasim );
                Console.WriteLine( Environment.NewLine );
            }</pre>
<p>while the Time generic method looks like this and dutifully runs the target work and reports the results in “Test X found Y Urls in X [time]”:</p>
<pre class="brush: csharp; gutter: false;">public static void Time&lt;T&gt;( string what, Func&lt;T&gt; work )
{
    var sw = Stopwatch.StartNew();
    var result = work();
    sw.Stop();
    Console.WriteLine( "\t{0,-15} found {1} urls in {2}", what, result, sw.Elapsed );
}</pre>
<p>Now in the msdn post the different methods had differing ways of finding each xml file and opening it, I made them all adhere to the way I open and sum the ULR counts. Here is its snippet:</p>
<pre class="brush: csharp; gutter: false;">return Directory.EnumerateFiles( @"D:\temp", "*.xml" )
            .ToList()
            .Sum( fl =&gt;
            {

            } );</pre>
<h3>Contender  –  XML Document</h3>
<p>This is one which the poster marked as the chosen one he used and I dutifully copied it to the best of my ability.</p>
<pre class="brush: csharp; gutter: false;">public static int XmlDoc_Hasim()
{
    return Directory.EnumerateFiles( @"D:\temp", "*.xml" )
                .ToList()
                .Sum( fl =&gt;
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml( System.IO.File.ReadAllText( fl ) );

                    if (doc.ChildNodes.Count &gt; 0)
                        if (doc.ChildNodes[1].HasChildNodes)
                            return doc.ChildNodes[1].ChildNodes.Count;

                    return 0;

                } );

}</pre>
<p>I used the sum extension method which is a little different from the original sum operation used, but it brings the tests closer in line by using the Extension.</p>
<h3>Contender – Linq to Xml</h3>
<p>Of the other two attempts, this one I felt was the more robust of the two, because it actually handled the xml namespace. Sadly it appeared to be ignored by the original poster. Here is his code</p>
<pre class="brush: csharp; gutter: false;">public static int XmlLinq_Link_FR()
{
    XNamespace xn = "http://www.sitemaps.org/schemas/sitemap/0.9";

    return Directory.EnumerateFiles( @"D:\temp", "*.xml" )
                    .Sum( fl =&gt; XElement.Load( fl ).Descendants( xn + "loc" ).Count() );

}</pre>
<h3>Contender – Regular Expression</h3>
<p>Finally here is the speed test winner. I came up with the pattern design Upon by looking at the xml and it appeared one didn’t need to match the actual url, but just the two preceding  tags and any possible space between. <span style="text-decoration: underline;">That is the key to regex</span>, using good patterns can achieve fast results.</p>
<pre class="brush: csharp; gutter: false;">public static int RegexFindXml()
{
    string pattern = @"(&lt;url&gt;\s*&lt;loc&gt;)";

    return Directory.EnumerateFiles( @"D:\temp", "*.xml" )
                    .Sum( fl =&gt; Regex.Matches( File.ReadAllText( fl ), pattern ).OfType&lt;Match&gt;().Count() );

}</pre>
<h3>XML1 (Shortened)</h3>
<pre class="brush: xml; gutter: false; collapse: true;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/internet-web2.0-startups-social-networking/barcelona.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/internet-web2.0-startups-social-networking/basel.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/internet-web2.0-startups-social-networking/bath.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/computer-networking/sheffield.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/computer-networking/singapore.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/computer-networking/slough.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/directory/companies/computer-networking/slovak-republic.html&lt;/loc&gt;&lt;changefreq&gt;weekly&lt;/changefreq&gt;&lt;/url&gt;
&lt;/urlset&gt;</pre>
<h3>Xml2 Shortened</h3>
<pre class="brush: xml; gutter: false; collapse: true;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2431604&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2430868&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/Wireless-Carrier-Reps-Past-Present-2430807&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2430694&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2430575&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2431452&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2432377&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2428508&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2432379&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2432380&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2432381&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2432383&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;url&gt;&lt;loc&gt;http://www.linkedin.com/groups/gid-2432384&lt;/loc&gt;&lt;changefreq&gt;monthly&lt;/changefreq&gt;&lt;/url&gt;
&lt;/urlset&gt;</pre>
<h2>Summary</h2>
<p>It really comes down to the right tool for the right situation and this one regex really did well. But Regex is not good at most xml parsing needs, but for certain scenarios it really shines. If the xml has malformed or the namespace was wrong, then the parser has its own unique problems which would lead to a bad count. All the technologies had to do some upfront loading and that is key to how they performed. Regex is optimized to handle large data efficiently and as long as the pattern is spot on, it can really be quick.</p>
<p>My thought is don’t dismiss regular expression parsing out of hand, while the learning of it can pay off in some unique text parsing situations.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2FOmegaCoder.com%2F%3Fp%3D850&amp;title=.Net%20Regex%3A%20Can%20Regular%20Expression%20Parsing%20be%20Faster%20than%20XmlDocument%20or%20Linq%20to%20Xml%3F" id="wpa2a_20"><img src="http://OmegaCoder.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://OmegaCoder.com/?feed=rss2&#038;p=850</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
