<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Christophe Geers&#039; Blog</title>
	<atom:link href="http://cgeers.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cgeers.com</link>
	<description>Christophe Geers&#039; Blog about .NET programming</description>
	<lastBuildDate>Tue, 18 Jun 2013 09:09:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='cgeers.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Christophe Geers&#039; Blog</title>
		<link>http://cgeers.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://cgeers.com/osd.xml" title="Christophe Geers&#039; Blog" />
	<atom:link rel='hub' href='http://cgeers.com/?pushpress=hub'/>
		<item>
		<title>AngularJS File Upload</title>
		<link>http://cgeers.com/2013/05/03/angularjs-file-upload/</link>
		<comments>http://cgeers.com/2013/05/03/angularjs-file-upload/#comments</comments>
		<pubDate>Fri, 03 May 2013 18:00:41 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[AngularJS]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[File Upload]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4722</guid>
		<description><![CDATA[Introduction Recently I had some time to play around with AngularJS. More specifically I had to implement a jQuery based file upload widget. The widget&#8217;s demo site already contains an AngularJS demo, but I wanted a minimum setup, so I started from scratch and figured out the necessary parts to implement the file upload using [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4722&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2013/05/angularjs.png"><img src="http://cgeers.files.wordpress.com/2013/05/angularjs.png?w=480" alt="AngularJS"   class="alignright size-full wp-image-4723" /></a></p>
<p>Recently I had some time to play around with <a href="http://angularjs.org/" target="_blank">AngularJS</a>. More specifically I had to implement a jQuery based <a href="http://blueimp.github.io/jQuery-File-Upload/" target="_blank">file upload widget</a>.</p>
<p>The widget&#8217;s demo site already contains an AngularJS demo, but I wanted a minimum setup, so I started from scratch and figured out the necessary parts to implement the file upload using ASP.NET MVC as the server-side platform.</p>
<p>Let&#8217;s see which steps we need to take to implement a basic version.</p>
<p><span id="more-4722"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#server">Server Side</a></li>
<li><a href="#dependencies">Dependencies</a></li>
<li><a href="#module">Module</a></li>
<li><a href="#layout">Layout</a></li>
<li><a href="#controller">FileUploadCtrl</a></li>
<li><a href="#service">uploadManager Service</a></li>
<li><a href="#directive">upload Directive</a></li>
<li><a href="#progress">Progress bar</a></li>
<li><a href="#summary">Summary</a></li>
</ul>
<p><a title="server" name="server"></a><strong>Server Side</strong></p>
<p>Let&#8217;s focus on the server-side part first.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> HomeController : Controller
{
    <span class="kwrd">public</span> ActionResult Index()
    {
        <span class="kwrd">return</span> View();
    }
}
</pre>
</div>
<p>Can&#8217;t get much simpler. </p>
<p>Now you&#8217;ll just need to add one more action method which handles a file upload.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[HttpPost]
<span class="kwrd">public</span> ContentResult Upload(HttpPostedFileBase file)
{
    <span class="kwrd">var</span> filename = Path.GetFileName(file.FileName);
    <span class="kwrd">var</span> path = Path.Combine(Server.MapPath(<span class="str">"~/uploads"</span>), filename);
    file.SaveAs(path);

    <span class="kwrd">return</span> <span class="kwrd">new</span> ContentResult
    {
        ContentType = <span class="str">"text/plain"</span>,
        Content = filename,
        ContentEncoding = Encoding.UTF8
    }; 
}</pre>
</div>
<p>The code is self-explanatory. When a file is uploaded (POST) the data is bound to the file parameter which is of type <a href="http://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.aspx" target="_blank">HttpPostedFileBase</a>. The file name is extracted and the file is saved on the server. Finally we return the file name as plain text.</p>
<p>Voila, that&#8217;s all the server side code you&#8217;ll need.</p>
<p><strong>Remark</strong>: I had to explicitly set the content type otherwhise IE will prompt you to download the result. Feel free to change the content type (e.g. JSON) and return something else than the filename instead.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="dependencies" name="dependencies"></a><strong>Dependencies</strong></p>
<p>When setting up a small demo site I developed the tendency to implement <a href="http://twitter.github.io/bootstrap/" target="_blank">Twitter Bootstrap</a> so that I can easily style it. If you are not familiar with Bootstrap, check out the following article to get started:</p>
<p><a href="http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/" target="_blank">Getting started with Twitter Bootstrap</a></p>
<p>So if you see some unfamiliar CSS in the HTML listings you know where it&#8217;s coming from.</p>
<p>Apart from Bootstrap and the jQuery file upload widget you&#8217;ll need to include the following resources:</p>
<ul>
<li><a href="http://jquery.com/" target="_blank">jQuery</a></li>
<li><a href="http://jqueryui.com/" target="_blank">jQuery UI Widget</a></li>
<li><a href="http://angularjs.org/" target="_blank">AngularJS</a></li>
</ul>
<p>The <a href="https://github.com/blueimp/jQuery-File-Upload/tags" target="_blank">download package</a> of the jQuery file upload contains a couple of JS files, but you&#8217;ll only need the jquery.fileupload.js library.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="module" name="module"></a><strong>Module</strong></p>
<p>Let&#8217;s create a custom Angular module. Add a new script file called app.js to the project and add the following code to it:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
(function () {
    'use strict';

    var myApp = angular.module('myApp', []);
}());
</pre>
</div>
<p>Don&#8217;t forget to bootstrap the application.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">html</span> <span class="attr">ng-app</span><span class="kwrd">="myApp"</span><span class="kwrd">&gt;</span>
...
<span class="kwrd">&lt;/</span><span class="html">html</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The root of our Angular application is now defined, let&#8217;s flesh out the rest.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="layout" name="layout"></a><strong>Layout</strong></p>
<p>The file upload control looks as follows:</p>
<p><a href="http://cgeers.files.wordpress.com/2013/05/fileupload.png"><img src="http://cgeers.files.wordpress.com/2013/05/fileupload.png?w=480" alt="fileupload"   class="aligncenter size-full wp-image-4746" /></a></p>
<p>Let&#8217;s compose the HTML to create this layout. First add a DIV and link it an Angular controller named FileUploadCtrl. Ignore the controller for now, we&#8217;ll get back to it later.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">h2</span><span class="kwrd">&gt;</span>File Upload<span class="kwrd">&lt;/</span><span class="html">h2</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">ng-controller</span><span class="kwrd">="FileUploadCtrl"</span><span class="kwrd">&gt;</span>
...
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The remaining HTML can be split into three sections:</p>
<ul>
<li>Select (files) button</li>
<li>List of selected files</li>
<li>Upload button</li>
</ul>
<p>Start by adding the HTML for the select button.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="control-group"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="controls"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">class</span><span class="kwrd">="btn btn-success fileinput-button"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">i</span> <span class="attr">class</span><span class="kwrd">="icon-plus icon-white"</span><span class="kwrd">&gt;&lt;/</span><span class="html">i</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">data-url</span><span class="kwrd">="home/upload"</span> 
                   <span class="attr">multiple</span> <span class="attr">upload</span><span class="kwrd">&gt;&lt;</span><span class="html">span</span><span class="kwrd">&gt;</span>Add files...<span class="kwrd">&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p><strong>Remark</strong>: You&#8217;ll need to include some <a href="https://dl.dropboxusercontent.com/u/40603470/fileinput-button.css" target="_blank">additional CSS</a> to properly style the file upload input, because by default it is designed to be butt-ugly (I borrowed this CSS from the file upload demo page).</p>
<p>Next add a list to display the selected files names. The list is bound to an array (files) of our Angular controller. </p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">ng-show</span><span class="kwrd">="!files.length"</span><span class="kwrd">&gt;</span>No files selected<span class="kwrd">&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">ul</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">ng-repeat</span><span class="kwrd">="file in files"</span><span class="kwrd">&gt;</span>{{file}}<span class="kwrd">&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">ul</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Last, but not least: the Upload button.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="form-actions"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">button</span> <span class="attr">type</span><span class="kwrd">="submit"</span> <span class="attr">class</span><span class="kwrd">="btn btn-primary pull-left"</span> <span class="attr">ng-click</span><span class="kwrd">="upload()"</span><span class="kwrd">&gt;</span>Upload<span class="kwrd">&lt;/</span><span class="html">button</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Clicking the button will invoke the upload function on the controller&#8217;s scope.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="controller" name="controller"></a><strong>FileUploadCtrl</strong></p>
<p>Time to add our FileUploadCtrl to our Angular module.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
myApp.controller('FileUploadCtrl',
    ['$scope', '$rootScope', 'uploadManager', 
    function ($scope, $rootScope, uploadManager) {
    $scope.files = [];
    $scope.percentage = 0;

    $scope.upload = function () {
        uploadManager.upload();
        $scope.files = [];
    };

    $rootScope.$on('fileAdded', function (e, call) {
        $scope.files.push(call);
        $scope.$apply();
    });

    $rootScope.$on('uploadProgress', function (e, call) {
        $scope.percentage = call;
        $scope.$apply();
    });
}]);</pre>
</div>
<p>We inject 3 dependencies into the controller: $scope, $rootScope and uploadManager. The latter being a custom service which manages the files that we want to upload. The scope has two properties, files (array) and percentage (int). The files array contains the name of the files to be uploaded. We&#8217;ll get back to the percentage later.</p>
<p>When you click the upload button the upload function on the scope is called. It informs the uploadManager service to start uploading the files and resets the files array.</p>
<p>Via the $rootScope we also listen to two events, fileAdded and uploadProgress, which are broadcast by the uploadManager service. Each time a file is added using the third-party jQuery plugin the fileAdded event is triggered. When this happens we add the filename to the files array. The uploadProgress event is triggered when the widget is busy uploading the files. Here we update the percentage property. Later we&#8217;ll bind this to a progress bar.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="service" name="service"></a><strong>uploadManager service</strong></p>
<p>The uploadManager service is fairly straightforward. It manages the files you wish to upload, it allows you to communicate between the third party file upload widget and your Angular controller.</p>
<p>Only the $rootScope is injected as a dependency. We use it to broadcast the two events (fileAdded and uploadProgress) we mentioned earlier.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
myApp.factory('uploadManager', function ($rootScope) {
    var _files = [];
    return {
        add: function (file) {
            _files.push(file);
            $rootScope.$broadcast('fileAdded', file.files[0].name);
        },
        clear: function () {
            _files = [];
        },
        files: function () {
            var fileNames = [];
            $.each(_files, function (index, file) {
                fileNames.push(file.files[0].name);
            });
            return fileNames;
        },
        upload: function () {
            $.each(_files, function (index, file) {
                file.submit();
            });
            this.clear();
        },
        setProgress: function (percentage) {
            $rootScope.$broadcast('uploadProgress', percentage);
        }
    };
});</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="directive" name="directive"></a><strong>upload Directive</strong></p>
<p>So the uploadManager service triggers events to which our controller listens and consequently updates its scope. But who then notifies this service of events triggered by the file upload widget? </p>
<p>That&#8217;s where our custom upload directive comes into play. Take a look again at the input element for the file upload listed earlier.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
 <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">="file"</span> <span class="attr">name</span><span class="kwrd">="file"</span> <span class="attr">data-url</span><span class="kwrd">="home/upload"</span>
        <span class="attr">multiple</span> <span class="attr">upload</span><span class="kwrd">&gt;&lt;</span><span class="html">span</span><span class="kwrd">&gt;</span>Add files...<span class="kwrd">&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The data-url attribute points to the URL the files are POSTed to. Note the upload attribute. This extends the input element. Let&#8217;s discover what it does.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
myApp.directive('upload', ['uploadManager', function factory(uploadManager) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            $(element).fileupload({
                dataType: 'text',
                add: function (e, data) {
                    uploadManager.add(data);
                },
                progressall: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    uploadManager.setProgress(progress);
                },
                done: function (e, data) {
                    uploadManager.setProgress(0);
                }
            });
        }
    };
}]);</pre>
</div>
<p>First we have Angular inject the uploadManager service. We then use the link function to transform the DOM. Here our element is turned into a file upload widget. The widget supports a number of callbacks. Here we only use the add, progressall and done callbacks. When these are triggered by the widget we notify the uploadManager. For example when a file is added we pass this to the uploadManager which then broadcasts the fileAdded event. Since our controller is listening for this event, it&#8217;ll be notified when a new file has been selected.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="progress" name="progress"></a><strong>Progress bar</strong></p>
<p>Let&#8217;s get back to that progress property on the scope of our controller. Each time the uploadManager service broadcasts the uploadProgress event we update the percentage. </p>
<p>This way you can easily add a <a href="http://twitter.github.io/bootstrap/components.html#progress" target="_blank">progress bar</a> and show the upload progress. For example:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="progress"</span> <span class="attr">ng-show</span><span class="kwrd">="percentage"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="bar"</span> <span class="attr">style</span><span class="kwrd">="width: {{percentage}}%;"</span><span class="kwrd">&gt;&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="summary" name="summary"></a><strong>Summary</strong></p>
<p>To recapitulate, we have 3 components that make up our Angular application:</p>
<ul>
<li><strong>FileUploadCtrl</strong>: Our controller which is tied to a DIV which contains the file upload widget</li>
<li><strong>uploadManager Service</strong>: This service manages the files we want to upload. It sends out a couple of events to which our controller listens and acts to accordingly.</li>
<li><strong>upload Directive</strong>: This directive transforms the file input into a bonafide upload widget. It uses the widget&#8217;s callbacks to notify the uploadManager service.</li>
</ul>
<p>And that&#8217;s basically all there is too it. I tested the code in Chrome and IE8. If you have any issues or suggestions please let me know.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/angularjs/'>AngularJS</a>, <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4722/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4722/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4722&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2013/05/03/angularjs-file-upload/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2013/05/angularjs.png" medium="image">
			<media:title type="html">AngularJS</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2013/05/fileupload.png" medium="image">
			<media:title type="html">fileupload</media:title>
		</media:content>
	</item>
		<item>
		<title>GitHub Service Hooks: AppHarbor</title>
		<link>http://cgeers.com/2012/10/30/github-service-hooks-appharbor/</link>
		<comments>http://cgeers.com/2012/10/30/github-service-hooks-appharbor/#comments</comments>
		<pubDate>Tue, 30 Oct 2012 05:30:39 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[AppHarbor]]></category>
		<category><![CDATA[Continous Deployment]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4655</guid>
		<description><![CDATA[Introduction The last 7 posts discussed how you can create a single-page application using GitHub, Twitter Bootstrap, MongoDB and Knockout.js. One last thing I touched briefly during my session in September is continuous deployment using AppHarbor. If you are not familiar with AppHarbor, it&#8217;s basically .NET as a service where you can deploy a .NET [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4655&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/10/appharbor.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor.png?w=80&#038;h=80" alt="AppHarbor" title="AppHarbor" width="80" height="80" class="alignright wp-image-4656" /></a></p>
<p>The last 7 posts discussed how you can create a single-page application using <a href="http://cgeers.com/2012/09/15/getting-started-with-github/" target="_blank">GitHub</a>, <a href="http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/" target="_blank">Twitter Bootstrap</a>, <a href="http://cgeers.com/2012/09/29/an-introduction-to-mongodb/" target="_blank">MongoDB</a> and <a href="http://cgeers.com/2012/10/06/single-page-application-with-knockout-js-part-1/" target="_blank">Knockout.js</a>.</p>
<p>One last thing I touched briefly during my session in September is continuous deployment using <a href="https://appharbor.com/" target="_blank">AppHarbor</a>. If you are not familiar with AppHarbor, it&#8217;s basically .NET as a service where you can deploy a .NET application to the cloud.</p>
<p>In this tutorial let&#8217;s create a small web application, use GitHub for source control and automatically deploy any commits directly to our AppHarbor hosted site.</p>
<p><span id="more-4655"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#spa">Single-page Application</a></li>
<li><a href="#github">GitHub Repository</a></li>
<li><a href="#appharbor">AppHarbor</a></li>
<li><a href="#servicehook">Service Hook</a></li>
<li><a href="#mongodb">MongoDB</a></li>
</ul>
<p><a title="spa" name="spa"></a><strong>Single-page Application</strong></p>
<p>First we&#8217;ll need a site which we can add to GitHub. Let&#8217;s use the single-page application created earlier during the 4-part Knockout.js series. I&#8217;m using this site as it also uses MongoDB. When deploying to AppHarbor we&#8217;ll need to replace the connection string to reflect the new environment. We&#8217;ll get back to that later.</p>
<p>You can download the application here:</p>
<p><a href="http://dl.dropbox.com/u/40603470/SinglePageApplicationPart4.zip" target="_blank">Single-page application using Knockout.js</a></p>
<p>If you haven&#8217;t followed the <a href="http://cgeers.com/category/programming/knockout-js/" target="_blank">Knockout series</a> you can have a quick look, but it&#8217;s not required to be able to follow along</p>
<p><a href="#top">Top of page</a></p>
<p><a title="github" name="github"></a><strong>GitHub Repository</strong></p>
<p>Once you&#8217;ve downloaded the source code, go ahead and extract it.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor1.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor1.png?w=480" alt="Files" title="Files"   class="aligncenter size-full wp-image-4669" /></a></p>
<p>Log in to your <a href="https://github.com/login" target="_blank">GitHub account</a> and create a new (public) repository called MySinglePageApplication.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor2.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor2.png?w=480" alt="New Repository" title="New Repository"   class="aligncenter size-full wp-image-4671" /></a></p>
<p>Make sure to initialize it with a README and a <a href="https://dl.dropbox.com/u/40603470/.gitignore" target="_blank">.gitignore file for C#</a>. </p>
<p>Once the remote repository has been created, open up GitHub for Windows and clone it to a local repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor3.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor3.png?w=480&#038;h=95" alt="Clone Repository" title="Clone Repository" width="480" height="95" class="aligncenter size-full wp-image-4674" /></a></p>
<p>When cloned, copy and paste the extracted files in this local repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor4.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor4.png?w=480" alt="Local Repository" title="Local Repository"   class="aligncenter size-full wp-image-4676" /></a></p>
<p>Time to commit. Open up a GitHub shell for the repo and push the new files to the remote repository. You need to execute the following commands:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
git add .
git commit -m "Initial commit"
git push</pre>
</div>
<p>Once you execute the &#8220;git push&#8221; command your new code files will be uploaded to your remote repository. This will probably take a minute or two.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor5.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor5.png?w=480&#038;h=123" alt="git push" title="git push" width="480" height="123" class="aligncenter size-full wp-image-4679" /></a></p>
<p>Alright, the remote repository now contains the code for our single-page application.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor61.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor61.png?w=480" alt="Initial commit" title="Initial commit"   class="aligncenter size-full wp-image-4683" /></a></p>
<p>If you are new to GitHub, be sure to read my post on <a href="http://cgeers.com/2012/09/15/getting-started-with-github/" target="_blank">getting started with GitHub</a> first.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="appharbor" name="appharbor"></a><strong>AppHarbor</strong></p>
<p>If you haven&#8217;t signed up with AppHarbor yet, go ahead and <a href="https://appharbor.com/user/new" target="_blank">create a free account</a>. Once signed in create a new application called MySinglePageApplication. Be sure to select United States or Europe depending on your actual location.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor7.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor7.png?w=480&#038;h=94" alt="New application" title="New application" width="480" height="94" class="aligncenter size-full wp-image-4686" /></a></p>
<p>When the application has been created you&#8217;ll automatically be redirected to its dashboard. On the lefthand menu you should see a button labelled BUILD URL. </p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor8.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor8.png?w=480" alt="Build URL" title="Build URL"   class="aligncenter size-full wp-image-4688" /></a></p>
<p>Click it. This copies the application&#8217;s build URL to the clipboard. The URL has the following pattern:</p>
<p><a href="https://appharbor.com:443/applications/mysinglepageapplication/builds?authorization=" rel="nofollow">https://appharbor.com:443/applications/mysinglepageapplication/builds?authorization=</a><strong>YOUR_AUTHORIZATION_ID</strong></p>
<p>Copy the value of the authorization query parameter into your clipboard. You won&#8217;t need the rest of the URL.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="servicehook" name="servicehook"></a><strong>Service Hook</strong></p>
<p>Your application has now been configured in GitHub and AppHarbor. Time to link the two. Go back to your GitHub account and go the MySinglePageApplication repository&#8217;s admin section. In the lefthand menu click the service hooks option.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor91.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor91.png?w=480" alt="Service Hooks" title="Service Hooks"   class="aligncenter size-full wp-image-4695" /></a></p>
<p>You&#8217;ll be presented with a very long list of available service hooks. Locate the AppHarbor hook and select it. To link GitHub to AppHarbor you need to complete the following form:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor10.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor10.png?w=480" alt="AppHarbor Service Hook" title="AppHarbor Service Hook"   class="aligncenter size-full wp-image-4697" /></a></p>
<p>Just enter &#8220;MySinglePageApplication&#8221; for the application slug and copy / paste the authorization ID from AppHarbor&#8217;s build URL into the token field. Check the active checkbox and finally click Update Settings. </p>
<p>That&#8217;s it. Your GitHub account is now linked to your AppHarbor application. Each time you push your commits to your remote repository GitHub will trigger the service hook and notify AppHarbor. AppHarbor in its turn will pull in the source code, build your application and automatically deploy it.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="mongodb" name="mongodb"></a><strong>MongoDB</strong></p>
<p>There&#8217;s just one last thing we need to address. Our application uses MongoDB, this hasn&#8217;t been setup for the AppHarbor hosted application yet. Let&#8217;s rectify this. Go back to your application&#8217;s dashboard on AppHarbor and select the Add-ons menu item.</p>
<p>Locate the MongoHQ add-on and click the &#8220;See more&#8221; link.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor11.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor11.png?w=480" alt="MongoHQ" title="MongoHQ"   class="aligncenter size-full wp-image-4702" /></a></p>
<p>Go ahead and install the free sandbox version which offers you 16 MB of storage.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor12.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor12.png?w=480" alt="MongoHQ sandbox" title="MongoHQ sandbox"   class="aligncenter size-full wp-image-4704" /></a></p>
<p>Voila, you&#8217;ve just added MongoDB support to your application. How does AppHarbor know how to replace your MongoDB connection string with its own? A simple naming convention does the trick. Just make sure you add your MongoDB connection string under the Web.config&#8217;s appSettings node and call it MONGOHQ_URL.</p>
<p>Go ahead and rename the connection string for the single-page application demo (Web.config + TimesheetsController.cs). Save the changes, commit and push them to the remote repository.</p>
<p>GitHub&#8217;s AppHarbor service hook will now deliver the payload to AppHarbor which in its turn will build and deploy your application. Just check your application&#8217;s dashboard on AppHarbor. Here you can follow the build&#8217;s progress.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/appharbor13.png"><img src="http://cgeers.files.wordpress.com/2012/10/appharbor13.png?w=480&#038;h=136" alt="Build status" title="Build status" width="480" height="136" class="aligncenter size-full wp-image-4706" /></a></p>
<p>On the top of the page you&#8217;ll find a &#8220;Go to your application&#8221; link. Click and you&#8217;ll notice that within a couple of minutes your new changes will have been deployed. </p>
<p>If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/continuous-integration/'>Continuous Integration</a>, <a href='http://cgeers.com/category/programming/github/'>GitHub</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4655/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4655&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/10/30/github-service-hooks-appharbor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor.png" medium="image">
			<media:title type="html">AppHarbor</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor1.png" medium="image">
			<media:title type="html">Files</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor2.png" medium="image">
			<media:title type="html">New Repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor3.png" medium="image">
			<media:title type="html">Clone Repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor4.png" medium="image">
			<media:title type="html">Local Repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor5.png" medium="image">
			<media:title type="html">git push</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor61.png" medium="image">
			<media:title type="html">Initial commit</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor7.png" medium="image">
			<media:title type="html">New application</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor8.png" medium="image">
			<media:title type="html">Build URL</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor91.png" medium="image">
			<media:title type="html">Service Hooks</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor10.png" medium="image">
			<media:title type="html">AppHarbor Service Hook</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor11.png" medium="image">
			<media:title type="html">MongoHQ</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor12.png" medium="image">
			<media:title type="html">MongoHQ sandbox</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/appharbor13.png" medium="image">
			<media:title type="html">Build status</media:title>
		</media:content>
	</item>
		<item>
		<title>Single-page Application with Knockout.js, Part 4</title>
		<link>http://cgeers.com/2012/10/22/single-page-application-with-knockout-js-part-4/</link>
		<comments>http://cgeers.com/2012/10/22/single-page-application-with-knockout-js-part-4/#comments</comments>
		<pubDate>Mon, 22 Oct 2012 05:30:08 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Knockout.js]]></category>
		<category><![CDATA[Knockout]]></category>
		<category><![CDATA[Twitter Bootstrap]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4609</guid>
		<description><![CDATA[Introduction Let&#8217;s wrap up our little Knockout powered single-page application. We already covered 3 out of 4 parts of the timesheets application. Displaying a list of timesheets Adding timesheets Editing timesheets Time to finish up with the fourth and final part, deleting timesheets. Using some Twitter Bootstrap and Knockout magic it shouldn&#8217;t take that long. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4609&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/10/knockout.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout.png?w=80&#038;h=80" alt="Knockout.js" title="Knockout.js" width="80" height="80" class="alignright wp-image-4454" /></a></p>
<p>Let&#8217;s wrap up our little Knockout powered single-page application. We already covered 3 out of 4 parts of the timesheets application.</p>
<ul>
<li><a href="http://cgeers.com/2012/10/06/single-page-application-with-knockout-js-part-1/" target="_blank">Displaying a list of timesheets</a></li>
<li><a href="http://cgeers.com/2012/10/10/single-page-application-with-knockout-js-part-2/" target="_blank">Adding timesheets</a></li>
<li><a href="http://cgeers.com/2012/10/15/single-page-application-with-knockout-js-part-3/?preview=true&amp;preview_id=4564&amp;preview_nonce=d85d7976ab" target="_blank">Editing timesheets</a></li>
</ul>
<p>Time to finish up with the fourth and final part, deleting timesheets. Using some Twitter Bootstrap and Knockout magic it shouldn&#8217;t take that long.</p>
<p><span id="more-4609"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#dropdown">Button Dropdown</a></li>
<li><a href="#checkboxes">Checkboxes</a></li>
<li><a href="#confirmation">Are You Sure?</a></li>
<li><a href="#nothingselected">Nothing Selected?</a></li>
<li><a href="#delete">Delete</a></li>
</ul>
<p><a title="dropdown" name="dropdown"></a><strong>Button Dropdown</strong></p>
<p>Bootstrap is awesome, you know that by now, right? Let&#8217;s introduce another one of its components to help us delete timesheets. Download the <a href="http://dl.dropbox.com/u/40603470/SinglePageApplicationPart3.zip" target="_blank">source code</a> of the previous part and open it in Visual Studio.</p>
<p>Open the index.cshtml view and copy / paste the following HTML above the table displaying the timesheets.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="btn-toolbar"</span> 
     <span class="attr">data-bind</span>="<span class="attr">visible:</span> <span class="attr">viewModel</span>.<span class="attr">timesheets</span>().<span class="attr">length</span> <span class="kwrd">&gt;</span> 0"<span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="btn-group"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">class</span><span class="kwrd">="btn btn-primary"</span><span class="kwrd">&gt;</span>Actions<span class="kwrd">&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">class</span><span class="kwrd">="btn btn-primary dropdown-toggle"</span> 
           <span class="attr">data-toggle</span><span class="kwrd">="dropdown"</span> <span class="attr">href</span><span class="kwrd">=""</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">class</span><span class="kwrd">="caret"</span><span class="kwrd">&gt;&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">ul</span> <span class="attr">class</span><span class="kwrd">="dropdown-menu"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>Delete<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">ul</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>This displays a button dropdown above the table if there is at least one timesheet present in our observable array. Notice the data-bind attribute on the div.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout10.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout10.png?w=480" alt="Button dropdown" title="Button dropdown"   class="aligncenter size-full wp-image-4621" /></a></p>
<p>The dropdown is toggled when you click on the caret. Like Bootstrap&#8217;s modal it also has a data-toggle attribute. Currently our dropdown list only contains one item, but feel free to add more.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout112.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout112.png?w=480" alt="Caret" title="Caret"   class="aligncenter size-full wp-image-4625" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="checkboxes" name="checkboxes"></a><strong>Checkboxes</strong></p>
<p>Alright, we have given the user an action which he can execute when he wants to delete one or more timesheets. But we still need them to be able to select the timesheets they want to delete. Adding a checkbox to each row will serve this purpose.</p>
<p>First add a new empty header cell to the &lt;thead&gt;. Make sure it is the first cell.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">thead</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">tr</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">th</span><span class="kwrd">&gt;&lt;/</span><span class="html">th</span><span class="kwrd">&gt;</span>
        //...
    <span class="kwrd">&lt;/</span><span class="html">tr</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">thead</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Then add a new cell to the row template. Also insert it before the other cells, so that it is nicely displayed beneath the empty header cell.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">tbody</span> <span class="attr">data-bind</span><span class="kwrd">="foreach: viewModel.timesheets"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">tr</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">td</span><span class="kwrd">&gt;&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">="checkbox"</span> <span class="attr">data-bind</span><span class="kwrd">="checked: selected"</span><span class="kwrd">/&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
        //...
    <span class="kwrd">&lt;/</span><span class="html">tr</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">tbody</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Your layout should now resemble this:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout122.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout122.png?w=480" alt="Checkboxes" title="Checkboxes"   class="aligncenter size-full wp-image-4639" /></a></p>
<p>Take a look at the cell which contains the HTML for the checkbox. Here we make use of the <a href="http://knockoutjs.com/documentation/checked-binding.html" target="_blank">checked binding</a>. The checkbox is linked to a property on its coherent timesheet object, called selected. Add this new property to the timesheet class.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
function timesheet(timesheet) {
    //...
    this.selected = ko.observable(false);
    //...
}</pre>
</div>
<p>When the user checks the timesheet, the selected property on the timesheet object will be updated. This way each timesheet knows wether or not it is currently selected.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="confirmation" name="confirmation"></a><strong>Are You Sure?</strong></p>
<p>When deleting data, it&#8217;s best to ask the user if he is sure he wants to proceed. So when he selects one or more timesheets and clicks the delete action we want to alert him.</p>
<p>Add the following HTML to your page.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal hide fade"</span> <span class="attr">id</span><span class="kwrd">="timesheet-delete"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-header"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">button</span> <span class="attr">type</span><span class="kwrd">="button"</span> <span class="attr">class</span><span class="kwrd">="close"</span> 
                <span class="attr">data-dismiss</span><span class="kwrd">="modal"</span><span class="kwrd">&gt;</span>×<span class="kwrd">&lt;/</span><span class="html">button</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">h3</span><span class="kwrd">&gt;</span>Delete?<span class="kwrd">&lt;/</span><span class="html">h3</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-body"</span><span class="kwrd">&gt;</span>
      <span class="kwrd">&lt;</span><span class="html">p</span><span class="kwrd">&gt;</span>Are you sure you want to delete these timesheets?<span class="kwrd">&lt;/</span><span class="html">p</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-footer"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span> <span class="attr">class</span><span class="kwrd">="btn"</span> <span class="attr">data-dismiss</span><span class="kwrd">="modal"</span><span class="kwrd">&gt;</span>Cancel<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">="submit"</span> <span class="attr">class</span><span class="kwrd">="btn btn-danger"</span> <span class="attr">value</span><span class="kwrd">="Delete"</span> 
               <span class="attr">data-bind</span><span class="kwrd">="click: function() { deleteTimesheets('timesheet-delete') }"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>That&#8217;s right, another modal window. Initially hidden we&#8217;ll show this popup when the user is about to delete timesheets. Let&#8217;s hookup the delete action to this modal.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">ul</span> <span class="attr">class</span><span class="kwrd">="dropdown-menu"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">id</span><span class="kwrd">="new-timesheet"</span> 
           <span class="attr">data-toggle</span><span class="kwrd">="modal"</span> 
           <span class="attr">href</span><span class="kwrd">="#timesheet-delete"</span><span class="kwrd">&gt;</span>Delete<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">ul</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Now the delete action toggles the model through the data-toggle and href attributes.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout131.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout131.png?w=480&#038;h=152" alt="Are you sure?" title="Are you sure?" width="480" height="152" class="aligncenter size-full wp-image-4636" /></a></p>
<p>If you take a look at the modal&#8217;s HTML you&#8217;ll notice that the Delete button is wired (data-bind) to the view model&#8217;s deleteTimesheets() function. For now just add the following stub function to your view model.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var viewModel = {
    //...
    deleteTimesheets: function (modalId) {
        //...
    }
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="nothingselected" name="nothingselected"></a><strong>Nothing Selected?</strong></p>
<p>Before we can actually delete timesheets, there&#8217;s one little issue that we need to fix. Currently the delete action is also available when no timesheets have been selected. Let&#8217;s disable it in this case. Add a new <a href="http://knockoutjs.com/documentation/computedObservables.html" target="_blank">computed observable</a> to the view model.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
viewModel.timesheetsSelected = ko.computed(function () {
    var selected = 0;
    $.each(this.timesheets(), function (index, timesheet) {
        if (timesheet.selected())
            selected++;
    });
    return selected;
}, viewModel);</pre>
</div>
<p>This computed observable returns the number of selected timesheets. Let&#8217;s hook up the visibility of the button dropdown to it. Just remove the old data-bind attribute and put the following one in its place.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="btn-toolbar"</span> <span class="attr">data-bind</span>="<span class="attr">visible:</span> <span class="attr">viewModel</span>.<span class="attr">timesheetsSelected</span>() <span class="kwrd">&gt;</span> 0"<span class="kwrd">&gt;</span>
...
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Problem solved. Now the user can only select the Delete action if at least one timesheet has been selected. You might want to hook up the computed observable directly to the Delete action instead of hiding the whole dropdown, feel free to experiment.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="delete" name="delete"></a><strong>Delete</strong></p>
<p>We&#8217;re only one Ajax call away from deleting the timesheets and completing our timesheets application. So without further ado, here&#8217;s the implementation for the deleteTimesheets() function.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
deleteTimesheets: function (modalId) {
    var ids = new Array();
    $.each(this.timesheets(), function (index, timesheet) {
        if (timesheet.selected())
            ids.push(timesheet.id());
    });

    var self = this;
    $.ajax({
        url: '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "timesheets" })',
        type: 'DELETE',
        data: ko.toJSON(ids),
        contentType: 'application/json; charset=utf-8',
        success: function () {
            $.each(ids, function (index, id) {
                var match = ko.utils.arrayFirst(self.timesheets(), function (item) {
                    return id === item.id();
                });
                self.timesheets.remove(match);
            });
            $('#' + modalId).modal('hide');
        }
    });
},</pre>
</div>
<p>First we loop through our observable array and check which timesheet is selected. We add the IDs of those to an array. Then we serialize this array to JSON and pass it via an Ajax call to our REST service.  Notice the DELETE HTTP verb.</p>
<p>I did make on little change to the REST controller though. Instead of deleting each timesheet one by one I now allow users of the API to pass in more than one ID.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> HttpResponseMessage Delete(<span class="kwrd">params</span> <span class="kwrd">string</span>[] ids)
{
    <span class="kwrd">foreach</span> (<span class="kwrd">var</span> id <span class="kwrd">in</span> ids)
    {
        _repository.Remove(Query.EQ(<span class="str">"_id"</span>, <span class="kwrd">new</span> ObjectId(id)));
    }
    <span class="kwrd">return</span> Request.CreateResponse(HttpStatusCode.NoContent);
}</pre>
</div>
<p>And that wraps up the Knockout CRUD application. Hope you find it useful. I&#8217;d like to point out another thing though, here&#8217;s the code for the controller behind the page.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> HomeController : Controller
{
    <span class="kwrd">public</span> ActionResult Index()
    {
        <span class="kwrd">return</span> View();
    }
}</pre>
</div>
<p>Maybe we&#8217;ll clean that one up in the next part <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . </p>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/knockout-js/'>Knockout.js</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4609/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4609/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4609&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/10/22/single-page-application-with-knockout-js-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout.png" medium="image">
			<media:title type="html">Knockout.js</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout10.png" medium="image">
			<media:title type="html">Button dropdown</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout112.png" medium="image">
			<media:title type="html">Caret</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout122.png" medium="image">
			<media:title type="html">Checkboxes</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout131.png" medium="image">
			<media:title type="html">Are you sure?</media:title>
		</media:content>
	</item>
		<item>
		<title>Single-page Application with Knockout.js, Part 3</title>
		<link>http://cgeers.com/2012/10/15/single-page-application-with-knockout-js-part-3/</link>
		<comments>http://cgeers.com/2012/10/15/single-page-application-with-knockout-js-part-3/#comments</comments>
		<pubDate>Mon, 15 Oct 2012 05:30:28 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Knockout.js]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Knockout]]></category>
		<category><![CDATA[Twitter Bootstrap]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4564</guid>
		<description><![CDATA[Introduction In part 3 of this series we&#8217;ll implement another feature of our little Knockout.js powered CRUD application. We already talked about read and create in the first two articles, skim through them if you want to get up to speed. Single-page Application with Knockout.js, Part 1 (READ) Single-page Application with Knockout.js, Part 2 (CREATE) [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4564&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/10/knockout.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout.png?w=80&#038;h=80" alt="Knockout.js" title="Knockout.js" width="80" height="80" class="alignright wp-image-4454" /></a></p>
<p>In part 3 of this series we&#8217;ll implement another feature of our little Knockout.js powered CRUD application. We already talked about read and create in the first two articles, skim through them if you want to get up to speed.</p>
<ul>
<li><a href="http://cgeers.com/2012/10/06/single-page-application-with-knockout-js-part-1/" target="_blank">Single-page Application with Knockout.js, Part 1</a> (READ)</li>
<li><a href="http://cgeers.com/2012/10/10/single-page-application-with-knockout-js-part-2/" target="_blank">Single-page Application with Knockout.js, Part 2</a> (CREATE)</li>
</ul>
<p>The next logical step after enabling users to add timesheets is to allow them to edit the new records. Time to implement some update functionality.</p>
<p><span id="more-4564"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#edit">Edit Link</a></li>
<li><a href="#objectid">ObjectId</a></li>
<li><a href="#modalform">Modal Form</a></li>
<li><a href="#populating">Populating the Form</a></li>
<li><a href="#submit">Submitting the Form</a></li>
</ul>
<p><a title="edit" name="edit"></a><strong>Edit Link</strong></p>
<p>Start where we left off last time. Download the <a href="http://dl.dropbox.com/u/40603470/SinglePageApplicationPart2.zip" target="_blank">source code</a> of the previous part, unzip it and open it up in Visual Studio.</p>
<p>Compile and run it. After adding a couple of timesheets you should see a similar list.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout13.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout13.png?w=480&#038;h=270" alt="Timesheets" title="Timesheets" width="480" height="270" class="aligncenter size-full wp-image-4575" /></a></p>
<p>Let&#8217;s make the first- and lastname clickable.</p>
<p>Open the Index.cshtml view, locate the table&#8217;s body and replace the following two cells:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">td</span> <span class="attr">data-bind</span><span class="kwrd">="text: firstname"</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">td</span> <span class="attr">data-bind</span><span class="kwrd">="text: lastname"</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span></pre>
</div>
<p>with</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">td</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span> <span class="attr">data-bind</span><span class="kwrd">="text: firstname, click: edit"</span><span class="kwrd">&gt;&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">td</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span> <span class="attr">data-bind</span><span class="kwrd">="text: lastname, click: edit"</span><span class="kwrd">&gt;&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span></pre>
</div>
<p>First we turned the first- and lastname into anchors. The text attribute of these anchors is bound to our timesheet objects as before. Then we hooked up the click events of both anchors to the edit() function of the timesheet object. Let&#8217;s declare it.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
function timesheet(timesheet) {
    //...

    this.edit = function() {
        console.log(this.id());
        //...
    }
}</pre>
</div>
<p>When editing a timesheet we&#8217;d like to know the ID of the timesheet. Easy, the edit() function will automatically be called on the correct timesheet object. This object already knows the ID of the timesheet.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
function timesheet(timesheet) {
    this.id = ko.observable(timesheet.id);
    //...
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="objectid" name="objectid"></a><strong>ObjectId</strong></p>
<p>On the server-side our Timesheet type descends from the abstract Entity class. This base class contains the Id property of type ObjectId. This is a MongoDB specific type provided by the <a href="http://nuget.org/packages/mongocsharpdriver" target="_blank">MongoDB C# driver</a>. </p>
<p>If you open the Entity.cs code file you&#8217;ll notice that it is decorated with a couple of attributes.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> Entity
{
    [JsonProperty(PropertyName = <span class="str">"id"</span>)]
    [JsonConverter(<span class="kwrd">typeof</span>(ObjectIdConverter))]
    <span class="kwrd">public</span> ObjectId Id { <span class="kwrd">get</span>; <span class="kwrd">protected</span> <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Nothing special here, just a few JSON.NET specific attributes to specify how to serialize the data. The only special case is the ObjectIdConverter attribute. It&#8217;s a custom <a href="http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/" target="_blank">JSON.NET converter</a> to help serialize the ObjectId.</p>
<p>The ObjectId is a 12-byte binary value consisting out of:</p>
<ul>
<li>4-byte timestamp (seconds sinds epoch)</li>
<li>3-byte machine id</li>
<li>2-byte process id</li>
<li>3-byte counter</li>
</ul>
<p>Check out the implementation of the custom converter if you want to. Nothing special, basically we just call ToString() on the ObjectId to retrieve a more readable format.</p>
<p>For example:</p>
<p>5079220fb4075a041495e119<br />
50792206b4075a041495e118<br />
50792218b4075a041495e11a<br />
&#8230;</p>
<p>Voila, the last- and firstname have now been turned into anchors. When clicking upon them the edit() function of their coherent timesheet object will be called.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="modalform" name="modalform"></a><strong>Modal Form</strong></p>
<p>When a user clicks edit we want the modal timesheet form to popup pre-populated with the selected timesheet&#8217;s data. But first let us modify something that we introduced in the previous part, namely resetting the form.</p>
<p>The &#8220;Add timesheet&#8221; button is currently bound to the view model&#8217;s resetForm() method. Go ahead and remove this binding.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">id</span><span class="kwrd">="new-timesheet"</span> <span class="attr">class</span><span class="kwrd">="btn btn-success"</span> 
   <span class="attr">data-toggle</span><span class="kwrd">="modal"</span> <span class="attr">href</span><span class="kwrd">="#timesheet-modal"</span><span class="kwrd">&gt;</span>Add timesheet<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Now remove the entire resetForm() method from the view model. Just go ahead and delete it. We&#8217;ll use one of the <a href="http://twitter.github.com/bootstrap/javascript.html#modals" target="_blank">modal&#8217;s events</a>, provided by Bootstrap, to reset the form. Not only do we need to reset the form each time after we&#8217;ve added a timesheet, now we also need to reset after each modification.</p>
<p>Copy / paste the following JavaScript below your view model.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
$('#timesheet-modal').on('hide', function () {
    var form = $('#Timesheet');
    form.validate().resetForm();
    form.get(0).reset();
    form.removeData('timesheet');
    form.find("input[type='hidden'][id='id']").remove();
});</pre>
</div>
<p>When the modal is hidden (hide event) it now resets the form. Doesn&#8217;t matter if we were adding or modifying an existing timesheet. Each time the modal is hidden it will reset the Timesheet form. No need to manually call this code anymore each time you show the modal.</p>
<p><strong>Remark</strong>: Notice that when resetting the form we also remove a hidden input element with the id &#8216;id&#8217; (if present). This hidden stores the ID of the timesheet we&#8217;re currently editing. We&#8217;ll get back to this later.</p>
<p>Currently the modal timesheet form is only displayed when someone clicks the &#8220;Add timesheet&#8221; button, but we also want to show it when a user click upon the first- or lastname of a timesheet. To achieve this you need to correctly setup the anchors to trigger the modal.</p>
<p>Add the following two attributes to both the first- and lastname anchors:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#timesheet-modal"</span> <span class="attr">data-toggle</span><span class="kwrd">="modal"</span> ... <span class="kwrd">&gt;</span>
</pre>
</div>
<p>Now the modal will also be shown when you click upon the first- or lastname.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout21.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout21.png?w=480&#038;h=357" alt="Empty form" title="Empty form" width="480" height="357" class="aligncenter size-full wp-image-4598" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="populating" name="populating"></a><strong>Populating the Form</strong></p>
<p>OK, the modal form is displayed when editing a timesheet, but the fields aren&#8217;t filled in. Let&#8217;s rectivy this.</p>
<p>Modify the click databinding of both anchors as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">data-bind</span><span class="kwrd">="text: firstname, click: function(form) { edit('Timesheet') }"</span> ...<span class="kwrd">&gt;&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span></pre>
</div>
<p>We still call the timesheet object&#8217;s edit function, but now we pass in an additional parameter, namely the ID of the form.</p>
<p>Now we can link the timesheet object to the form using <a href="http://api.jquery.com/jQuery.data/" target="_blank">jQuery&#8217;s data() method</a>.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
function timesheet(timesheet) {
    //...

    this.edit = function (formId) {
        var form = $('#' + formId);
        form.data('timesheet', this);
    }
}</pre>
</div>
<p>Now when you click on one of the links the timesheet object will be associated with the form which resides in the modal.</p>
<p>We can easily pre-populate the form now using another one of the modal&#8217;s events.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
$('#timesheet-modal').on('show', function () {
    var form = $('#Timesheet');
    var timesheet = form.data('timesheet');
    if (!timesheet)
        return;

    $('<span class="kwrd">&lt;</span><span class="html">input</span><span class="kwrd">&gt;</span>').attr('type', 'hidden')
                .attr('id', 'id')
                .attr('name', 'id')
                .val(timesheet.id()).prependTo(form);
    form.find('#FirstName').val(timesheet.firstname());
    form.find('#LastName').val(timesheet.lastname());
    form.find('#Month').val(timesheet.month());
    form.find('#Year').val(timesheet.year());
});</pre>
</div>
<p>When the modal form is shown we check if a timesheet object has been associated with the form. If so, we take use the timesheet object&#8217;s properties to pre-populate the form with data. Note that we also add a hidden input element to the form which stores the timesheet&#8217;s ID. This way we know which timesheet to update it when we submit the form.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="submit" name="submit"></a><strong>Submitting the Form</strong></p>
<p>As you may remember the form&#8217;s submission is already bound to the view modal&#8217;s postTimesheet() function thanks to the magic that is Knockout. Let&#8217;s modify this function so that it can handle adding (POST) and updating (PUT) timesheets.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
postTimesheet: function (form, modalId) {
    form = $(form);
    <span class="kwrd">if</span> (!form.valid())
        <span class="kwrd">return</span>;

    <span class="kwrd">var</span> json = JSON.stringify(<span class="kwrd">this</span>._getTimesheetFromFrom(form));

    <span class="kwrd">var</span> update = form.find(<span class="str">"input[type='hidden'][id='id']"</span>).val();
    <span class="kwrd">var</span> httpVerb = !update ? <span class="str">"POST"</span> : <span class="str">"PUT"</span>;

    <span class="kwrd">var</span> self = <span class="kwrd">this</span>;
    $.ajax({
        url: <span class="str">'@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "timesheets" })'</span>,
        type: httpVerb,
        data: json,
        dataType: <span class="str">'json'</span>,
        contentType: <span class="str">'application/json; charset=utf-8'</span>,
        success: function (jsonObject) {
            <span class="kwrd">if</span> (update) {
                <span class="kwrd">var</span> match = ko.utils.arrayFirst(self.timesheets(), function (item) {
                    <span class="kwrd">return</span> jsonObject.id === item.id();
                });
                match.update(jsonObject);
            }
            <span class="kwrd">else</span> {
                self.timesheets.push(<span class="kwrd">new</span> timesheet(jsonObject));
            }
            $(<span class="str">'#'</span> + modalId).modal(<span class="str">'hide'</span>);
        }
    });
}</pre>
</div>
<p>Only a few things have changed. First we check if the form contains a hidden ID input element. If so we&#8217;ll be updating (POST) a timesheet instead of adding (POST) one. Then when our Ajax call successfully returns we check if we need to add a new timesheet to our observable array or update an existing one.</p>
<p>Note that Knockout monitors an observable array for additions and removals of objects, but it doesn&#8217;t actually monitor the properties of the objects that you&#8217;ve added to the array. Imagine how many resources it would require if it were to scan and monitor each object&#8217;s entire graph. </p>
<p>We need to manually update the object the modified object which resides in the observable array. For this purpose I&#8217;ve added an update() method to the timesheet class.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
function timesheet(timesheet) {
    //...

    this.update = function (timesheet) {
        this.id(timesheet.id);
        this.firstname(timesheet.firstname);
        this.lastname(timesheet.lastname);
        this.month(timesheet.month);
        this.year(timesheet.year);
    };
}</pre>
</div>
<p>After updating a timesheet we first locate it in the observable array and then call it&#8217;s update method passing in the JSON object (= timesheet) which we received from our REST controller.</p>
<p>And that wraps up the third article of this Knockout.js series. The first post showed you how to implement the READ part, the second demonstrated the CREATE part and this one explained the UPDATE part. Only one remaining, namely DELETE, but I&#8217;ll keep that one for the fourth and final part.</p>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/knockout-js/'>Knockout.js</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4564/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4564&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/10/15/single-page-application-with-knockout-js-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout.png" medium="image">
			<media:title type="html">Knockout.js</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout13.png" medium="image">
			<media:title type="html">Timesheets</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout21.png" medium="image">
			<media:title type="html">Empty form</media:title>
		</media:content>
	</item>
		<item>
		<title>Single-page Application with Knockout.js, Part 2</title>
		<link>http://cgeers.com/2012/10/10/single-page-application-with-knockout-js-part-2/</link>
		<comments>http://cgeers.com/2012/10/10/single-page-application-with-knockout-js-part-2/#comments</comments>
		<pubDate>Wed, 10 Oct 2012 19:30:04 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Knockout.js]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Knockout]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Twitter Bootstrap]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4504</guid>
		<description><![CDATA[Introduction Let&#8217;s start where we left off. Go ahead and download the source code of the previous part, unzip it and open it up in Visual Studio. Last time we retrieved a list of timesheets, pushed it into an observable array and used declarative bindings (data-bind) to associate DOM elements with our view model. In [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4504&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/10/knockout.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout.png?w=80&#038;h=80" alt="Knockout.js" title="Knockout.js" width="80" height="80" class="alignright wp-image-4454" /></a></p>
<p>Let&#8217;s start where we left off. Go ahead and download the <a href="http://dl.dropbox.com/u/40603470/SinglePageApplicationPart1.zip" target="_blank">source code</a> of the previous part, unzip it and open it up in Visual Studio. </p>
<p>Last time we retrieved a list of timesheets, pushed it into an observable array and used declarative bindings (data-bind) to associate DOM elements with our view model. In other words we databound it to a table. Knockout then automagically rendered a row for each timesheet in the array.</p>
<p>Let&#8217;s proceed with the next step in our little CRUD application and add support for creating new timesheets.</p>
<p><span id="more-4504"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#modal">Modal</a></li>
<li><a href="#form">The Form</a></li>
<li><a href="#reset">Resetting the Form</a></li>
<li><a href="#postit">POST-it</a></li>
</ul>
<p><a title="modal" name="modal"></a><strong>Modal</strong></p>
<p>Let&#8217;s present the user with an option to add a new timesheet. Copy / paste the following HTML code just below the table on the Index.cshtml view.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="pull-right"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">id</span><span class="kwrd">="new-timesheet"</span> <span class="attr">class</span><span class="kwrd">="btn btn-success"</span>
       <span class="attr">data-toggle</span><span class="kwrd">="modal"</span> <span class="attr">href</span><span class="kwrd">="#timesheet-modal"</span><span class="kwrd">&gt;</span>Add timesheet<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>This will render the following button beneath the bottom right hand corner of the table.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout4.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout4.png?w=480" alt="Add timesheet" title="Add timesheet"   class="aligncenter size-full wp-image-4512" /></a></p>
<p>This demonstrates some of Twitter Bootstrap&#8217;s base CSS for quickly rendering cool looking <a href="http://twitter.github.com/bootstrap/base-css.html#buttons" target="_blank">buttons</a>.</p>
<p>The button here is a simple anchor. Notice the data-toggle and href attributes on the anchor? Bootstrap magic at work again. The data-toggle attribute basically tells Bootstrap to show a modal window with the id (href) &#8220;timesheet-modal&#8221; when the button is clicked. The button (data-)toggles the modal window.</p>
<p>Time to add the actual modal. Insert the following HTML beneath the button.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal hide fade"</span> <span class="attr">id</span><span class="kwrd">="timesheet-modal"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-header"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">button</span> <span class="attr">type</span><span class="kwrd">="button"</span> <span class="attr">class</span><span class="kwrd">="close"</span> 
                <span class="attr">data-dismiss</span><span class="kwrd">="modal"</span><span class="kwrd">&gt;</span>×<span class="kwrd">&lt;/</span><span class="html">button</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">h3</span><span class="kwrd">&gt;</span>Timesheet<span class="kwrd">&lt;/</span><span class="html">h3</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    
    <span class="kwrd">&lt;</span><span class="html">form</span> <span class="attr">id</span><span class="kwrd">="Timesheet"</span> 
     <span class="attr">data-bind</span><span class="kwrd">="submit: 
       function(form) { postTimesheet(form, 'timesheet-modal') }"</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-body"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>

    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-footer"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span> <span class="attr">class</span><span class="kwrd">="btn"</span> <span class="attr">data-dismiss</span><span class="kwrd">="modal"</span><span class="kwrd">&gt;</span>Cancel<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">input</span> <span class="attr">type</span><span class="kwrd">="submit"</span> <span class="attr">class</span><span class="kwrd">="btn btn-primary"</span> <span class="attr">value</span><span class="kwrd">="Save"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">form</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>The modal div is initially hidden due to the CSS hide class. It consists out of three parts, namely:</p>
<ul>
<li>header (modal-header)</li>
<li>body (modal-body)</li>
<li>footer (modal-footer)</li>
</ul>
<p>Each part is decorated with a Bootstrap CSS class (modal-header, modal-body&#8230;etc.). The header contains a caption and a button (X) that allows the user to close the modal. The button&#8217;s data-dismiss attribute informs bootstrap that this button closes the modal. The body is empty for now, while the footer contains a regular submit button and another button to close the modal.</p>
<p>Before you run the application there are two other things you need to modify.</p>
<p>First add the following CSS to the site.css file which is included between bootstrap.css and bootstrap-responsive.css to remove the bottom margin of 20px that bootstrap adds to forms. Notice that the modal&#8217;s body and footer are wrapped in a form.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
form { margin: 0; }</pre>
</div>
<p>This form is also bound to our view model.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
 <span class="kwrd">&lt;</span><span class="html">form</span> <span class="attr">id</span><span class="kwrd">="Timesheet"</span> 
  <span class="attr">data-bind</span><span class="kwrd">="submit: function(form) { postTimesheet(form, 'timesheet-modal') }"</span><span class="kwrd">&gt;</span>
...
<span class="kwrd">&lt;/</span><span class="html">form</span><span class="kwrd">&gt;</span></pre>
</div>
<p>This attribute instructs Knockout to call the view model&#8217;s postTimesheet function when the form is submitted. Add this new function to the view model.</p>
<p><strong>Remark</strong>: Notice that here I passed the ID of the modal to the submitTimesheet() function by wrapping the handler in a function literal that takes in the necessary parameters. Knockout supplies the form by default for form submissions, I just added a literal which contains the modal&#8217;s ID. You&#8217;ll see later on why we need it.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
postTimesheet: function (form, modalId) {
        
}</pre>
</div>
<p>Alright, the modal is now completely setup. Compile and run. If you click on the &#8220;Add timesheet&#8221; button now, the modal window will appear.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout5.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout5.png?w=480&#038;h=136" alt="Modal" title="Modal" width="480" height="136" class="aligncenter size-full wp-image-4520" /></a></p>
<p>Five minutes of work and you&#8217;ve got a working modal window! </p>
<p><a href="#top">Top of page</a></p>
<p><a title="form" name="form"></a><strong>The Form</strong></p>
<p>We can now add a form to the body of the modal which the user can fill in to add a new timesheet. Create a partial view called _Timesheet.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout6.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout6.png?w=480" alt="Partial View" title="Partial View"   class="aligncenter size-full wp-image-4525" /></a></p>
<p>Render the partial view in the modal&#8217;s body.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
...
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="modal-body"</span><span class="kwrd">&gt;</span>
@{ Html.RenderPartial("_Timesheet", new Timesheet()); }
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
...</pre>
</div>
<p>The partial view _Timesheet uses the Timesheet type as its model. It renders some input controls for the first name, last name, month and year properties.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
﻿@model MvcApplication.Models.Timesheet

@Html.LabelFor(m =&gt; m.FirstName)
@Html.TextBoxFor(m =&gt; m.FirstName)
@Html.LabelFor(m =&gt; m.LastName)
@Html.TextBoxFor(m =&gt; m.LastName)

@Html.LabelFor(m =&gt; m.Month)
@Html.DropDownListFor(m =&gt; m.Month, Model.Months)
@Html.LabelFor(m =&gt; m.Year)
@Html.TextBoxFor(m =&gt; m.Year, <span class="kwrd">new</span> { disabled=<span class="str">"disabled"</span> })
</pre>
</div>
<p><strong>Remark</strong>: If you take a look at the Timesheet model&#8217;s code you&#8217;ll notice that I added some data annotations (required, display&#8230;etc.) and an IEnumerable of SelectListItem for the months.</p>
<p>Your modal should now look like the following screenshot:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout7.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout7.png?w=480&#038;h=358" alt="Timesheet Form" title="Timesheet Form" width="480" height="358" class="aligncenter size-full wp-image-4529" /></a></p>
<p>Let&#8217;s add some CSS to the site.css file to make sure required fields are nicely marked with a red border.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
select.input-validation-error,
input.input-validation-error {
    border-color: #FF0000;
    border-radius: 7px;
}

select.input-validation-error:focus,
input.input-validation-error:focus { 
    outline: none;
    border-color: #FF0000;
    box-shadow: 0 0 10px #FF0000;
}</pre>
</div>
<p>If you submit the form without filling out a single field you&#8217;ll notice that the first- and last name field will be marked as required.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout8.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout8.png?w=480" alt="Required field" title="Required field"   class="aligncenter size-full wp-image-4531" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="reset" name="reset"></a><strong>Resetting the Form</strong></p>
<p>Close the modal and re-open it. What do you notice? Yup, the fields are still marked as required, red border and all. Same thing if you enter some data, it will be still there next time you re-open the modal. When opening the modal we need to wipe the slate clean; we need to reset the form. </p>
<p>Bind the &#8220;Add timesheet&#8221; button&#8217;s click event to the view model&#8217;s resetForm function as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="pull-right"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">id</span><span class="kwrd">="new-timesheet"</span> <span class="attr">class</span><span class="kwrd">="btn btn-success"</span> 
       <span class="attr">data-toggle</span><span class="kwrd">="modal"</span> <span class="attr">href</span><span class="kwrd">="#timesheet-modal"</span> 
       <span class="attr">data-bind</span><span class="kwrd">="click: resetForm.bind($data, 'Timesheet')"</span><span class="kwrd">&gt;</span>
    Add timesheet<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>We pass a literal parameter to the resetForm function using the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" target="_blank">bind</a> function, which attaches a specific parameter value to a function reference. Here we pass the ID of the form which we want to reset.</p>
<p>As for the resetForm function&#8217;s implementation, it&#8217;s pretty straightforward. Just add the following function to your view model.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
resetForm: function (formId) {
    var form = $('#' + formId);
    form.validate().resetForm();
    form.get(0).reset();
}</pre>
</div>
<p>Using jQuery validation the form&#8217;s validation information is reset and the the actual form itself. If you re-open the modal now the fields are empty and no longer marked as required.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="postit" name="postit"></a><strong>POST-it</strong></p>
<p>Everything is in place now. The form is finished, let&#8217;s post the data entered by the user and create a new timesheet. Time to implement the view model&#8217;s postTimesheet function we added earlier.</p>
<p>Let&#8217;s go through it step by step. First we check if the form passes the required validation.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
form = $(form);
if (!form.valid())
    return;</pre>
</div>
<p>Then we extract the entered information form the form and serialize it as JSON.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var json = JSON.stringify(this._getTimesheetFromFrom(form));</pre>
</div>
<p>The _getTimesheetsFromForm() is a &#8220;private&#8221; method on our view model which is implemented as follows:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
_getTimesheetFromFrom: function (form) {
    form = $(form);
    var timesheet = {};
    form.find('input[type!=submit],select').each(function () {
        timesheet[this.name] = $(this).val();
    });
    return timesheet;
}</pre>
</div>
<p>It takes all the INPUT and SELECT input elements from the form and returns the information as a JSON object.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
{"FirstName":"Dan","LastName":"Harrington","Month":"11","Year":"2012"} </pre>
</div>
<p>OK, let&#8217;s continue with the implementation of the postTimesheet() function. The form&#8217;s data has been validated, the JSON payload has been assembled. Time to POST the data to our Timesheets API controller (REST).</p>
<p>Easy Peasy Lemon Squeezy. Just perform an $.ajax call and POST the JSON data. When you get a reply, which is the newly added timesheet serialized as JSON, we push it on our observable array of timesheets. Last, but not least we use the modalId parameter to hide the modal window.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
var self = this;
$.ajax({
    url: '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "timesheets" })',
    type: 'POST',
    data: json,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (jsonObject) {
        self.timesheets.push(new timesheet(jsonObject));
        $('#' + modalId).modal('hide');
    }
});</pre>
</div>
<p>Thanks to the magic of Knockout our list of timesheets will update automatically.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout9.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout9.png?w=480&#038;h=287" alt="New timesheet" title="New timesheet" width="480" height="287" class="aligncenter size-full wp-image-4550" /></a></p>
<p>The previous post showed you how to implement the READ part of our CRUD application, while this part demonstrated the CREATE. In the third article of this series we&#8217;ll reuse much of what we learned here and implement the UPDATE. The fourth and last post will wrap everything up with the DELETE. </p>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/knockout-js/'>Knockout.js</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4504/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4504&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/10/10/single-page-application-with-knockout-js-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout.png" medium="image">
			<media:title type="html">Knockout.js</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout4.png" medium="image">
			<media:title type="html">Add timesheet</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout5.png" medium="image">
			<media:title type="html">Modal</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout6.png" medium="image">
			<media:title type="html">Partial View</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout7.png" medium="image">
			<media:title type="html">Timesheet Form</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout8.png" medium="image">
			<media:title type="html">Required field</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout9.png" medium="image">
			<media:title type="html">New timesheet</media:title>
		</media:content>
	</item>
		<item>
		<title>Single-page Application with Knockout.js, Part 1</title>
		<link>http://cgeers.com/2012/10/06/single-page-application-with-knockout-js-part-1/</link>
		<comments>http://cgeers.com/2012/10/06/single-page-application-with-knockout-js-part-1/#comments</comments>
		<pubDate>Sat, 06 Oct 2012 12:38:16 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Knockout.js]]></category>
		<category><![CDATA[Knockout]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Twitter Bootstrap]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4453</guid>
		<description><![CDATA[Introduction The last two posts were introductory posts to Twitter Bootstrap and MongoDB. Let&#8217;s combine these two technologies with ASP.NET MVC 4, Web API and Knockout.js to create a simple Single-page Application. The goal is to fit all the necessary code &#8211; HTML, JavaScript and CSS on one single page, hence the name. This results [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4453&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/10/knockout.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout.png?w=80&#038;h=80" alt="Knockout.js" title="Knockout.js" width="80" height="80" class="alignright wp-image-4454" /></a></p>
<p>The last two posts were introductory posts to <a href="http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/" target="_blank">Twitter Bootstrap</a> and <a href="http://cgeers.com/2012/09/29/an-introduction-to-mongodb/" target="_blank">MongoDB</a>. Let&#8217;s combine these two technologies with ASP.NET MVC 4, Web API and Knockout.js to create a simple Single-page Application.</p>
<p>The goal is to fit all the necessary code &#8211; HTML, JavaScript and CSS on one single page, hence the name. This results in a more fluid user experience. We will not be doing any full page reloads or transfer control to another page. All interaction with the server will consist solely out lightweight JSON communication.</p>
<p><span id="more-4453"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#template">Project Template</a></li>
<li><a href="#webapi">Timesheets API</a></li>
<li><a href="#data">Data</a></li>
<li><a href="#knockoutjs">A Simple List with Knockout.js</a></li>
</ul>
<p><a title="template" name="template"></a><strong>Project Template</strong></p>
<p>The last two posts discuss how you can quickly bootstrap a site and get up and running with MongoDB. To avoid repeating these steps I created an ASP.NET MVC 4 project which already contains a Bootstrap enabled layout and a REST service (Web API) which uses a MongoDB database to store and fetch its resources.</p>
<p>Download the solution and open it in Visual Studio.</p>
<p><a href="https://dl.dropbox.com/u/40603470/SinglePageApplication.zip" target="_blank">Single-page Application Project</a></p>
<p>Before you compile and run the project make sure you&#8217;ve <a href="http://cgeers.com/2012/09/29/an-introduction-to-mongodb/" target="_blank">set up MongoDB</a> correctly.</p>
<p>When you compile and run the application you should get the following page:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout11.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout11.png?w=480" alt="Timesheets" title="Timesheets"   class="aligncenter size-full wp-image-4464" /></a></p>
<p>The site contains a <a href="http://twitter.github.com/bootstrap/components.html#navbar" target="_blank">basic navbar</a> which contains two menu items, Timesheets and About. The About page just contains some <a href="http://www.lipsum.com/" target="_blank">Lorem Ipsum</a> speak. We&#8217;ll be focussing on the Timesheets page for our SPA application.</p>
<p>Apart from using Twitter Bootstrap, I also included a couple of JavaScript libraries such as jQuery, jQuery Validation and ofcourse the latest version of <a href="http://knockoutjs.com/" target="_blank">Knockout.js</a>.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="webapi" name="webapi"></a><strong>Timesheets API</strong></p>
<p>Our SPA will be a simple <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" target="_blank">CRUD</a> application which allows the user to manage timesheets. Now a timesheet in our case in a very simple object.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> Timesheet : Entity
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    <span class="kwrd">public</span> <span class="kwrd">int</span> Month { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    <span class="kwrd">public</span> <span class="kwrd">int</span> Year { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Per timesheet you can specify a name, month and year. That&#8217;s it, very basic. We won&#8217;t go as far as to specify individual days per month. That&#8217;s beyond the scope of this article. Let&#8217;s keep it simple. </p>
<p>As you can see, the Timesheet object descends from the Entity base class.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> Entity
{
    <span class="kwrd">public</span> ObjectId Id { <span class="kwrd">get</span>; <span class="kwrd">protected</span> <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Nothing special here, it just contains one property, namely the ObjectId that comes with each document in a MongoDB collection. Check out the post &#8220;<a href="http://cgeers.com/2012/09/29/an-introduction-to-mongodb/" target="_blank">An Introduction to MongoDB</a>&#8221; for more information if required.</p>
<p>I used <a href="http://www.asp.net/web-api" target="_blank">Web API</a> to create a TimesheetsController.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> TimesheetsController : ApiController
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> MongoDatabase _mongoDb;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> MongoCollection&lt;Timesheet&gt; _repository;

    <span class="kwrd">public</span> TimesheetsController()
    {
        <span class="kwrd">var</span> connectionString = 
          ConfigurationManager.AppSettings[<span class="str">"MongoDBTimesheets"</span>];
        _mongoDb = MongoDatabase.Create(connectionString);

        _repository = _mongoDb.GetCollection&lt;Timesheet&gt;(
          <span class="kwrd">typeof</span> (Timesheet).Name);
    }

    <span class="rem">//...</span>
}</pre>
</div>
<p>When an instance of the TimesheetsController is created it establishes a connection to MongoDB and creates a repository (MongoCollection) for our timesheets.</p>
<p>The controllers supports the default HTTP verbs:</p>
<ul>
<li><strong>GET</strong>: Retrieve all (or one) timesheet</li>
<li><strong>POST</strong>: Add a timesheet</li>
<li><strong>PUT</strong>: Update a timesheet</li>
<li><strong>DELETE</strong>: Delete a timesheet</li>
</ul>
<p>For example:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="rem">// GET /api/timesheets/4fd63a86f65e0a0e84e510de</span>
[HttpGet]
<span class="kwrd">public</span> Timesheet Get(<span class="kwrd">string</span> id)
{
    <span class="kwrd">var</span> query = Query.EQ(<span class="str">"_id"</span>, <span class="kwrd">new</span> ObjectId(id));
    <span class="kwrd">return</span> _repository.Find(query).Single();
}</pre>
</div>
<p>A very basic implementation of a REST API that uses MongoDB to persist its resources. Check out the source code if you are interested in seeing how the other HTTP verbs are implemented. A bit of Web API knowledge is required though, but there are plenty of good tutorials on that topic available.</p>
<p><strong>Remark</strong>: If you download the code you&#8217;ll notice that I use these two entities as the actual models of the MVC app. They are decorated with some data annotations and JSON.NET serialization attributes. You can split this up if you want to, to avoid any dependencies, and create your own dedicated models and entities. I just want to keep the project as simple as possible. The main purpose is to demonstrate Knockout.js.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="data" name="data"></a><strong>Data</strong></p>
<p>We&#8217;ll be demonstrating the data binding features of Knockout in a bit, but in order to bind some data, we actually need some data. So place the following code in your Index action of the HomeController and fire up the site.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> mongoDb = MongoDatabase.Create(ConfigurationManager.AppSettings[<span class="str">"MongoDBTimesheets"</span>]);
<span class="kwrd">var</span> repository = mongoDb.GetCollection&lt;Timesheet&gt;(<span class="kwrd">typeof</span>(Timesheet).Name);
<span class="kwrd">var</span> timesheets = <span class="kwrd">new</span> List&lt;Timesheet&gt;
{
    <span class="kwrd">new</span> Timesheet { FirstName = <span class="str">"Christophe"</span>, LastName = <span class="str">"Geers"</span>, Month = 8, Year = 2012},
    <span class="kwrd">new</span> Timesheet { FirstName = <span class="str">"Ruben"</span>, LastName = <span class="str">"Geers"</span>, Month = 8, Year = 2012 }
};
<span class="kwrd">foreach</span> (<span class="kwrd">var</span> timesheet <span class="kwrd">in</span> timesheets)
    repository.Insert(timesheet);
</pre>
</div>
<p>This will populate the Timesheet collection with a couple of timesheets. Feel free to add as many as you like. Just delete the code after you are done. Voila, we&#8217;ve now got some data we can work with.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="knockoutjs" name="knockoutjs"></a><strong>A Simple List with Knockout.js</strong></p>
<p>OK, we&#8217;ve got our skeleton application up and running. Let&#8217;s display a simple list of timesheets using Knockout.js. Open up the Index.cshtml file in Visual Studio and add the following HTML to render a basic table.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
 <span class="kwrd">&lt;</span><span class="html">table</span> <span class="attr">id</span><span class="kwrd">="timesheets"</span> <span class="attr">class</span><span class="kwrd">="table table-striped table-hover table-condensed"</span><span class="kwrd">&gt;</span>   
<span class="kwrd">&lt;</span><span class="html">thead</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">tr</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">th</span><span class="kwrd">&gt;</span>First Name<span class="kwrd">&lt;/</span><span class="html">th</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">th</span><span class="kwrd">&gt;</span>Last Name<span class="kwrd">&lt;/</span><span class="html">th</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">th</span><span class="kwrd">&gt;</span>Month<span class="kwrd">&lt;/</span><span class="html">th</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">th</span><span class="kwrd">&gt;</span>Year<span class="kwrd">&lt;/</span><span class="html">th</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">tr</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">thead</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">tbody</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">tbody</span><span class="kwrd">&gt;</span>
 <span class="kwrd">&lt;/</span><span class="html">table</span><span class="kwrd">&gt;</span></pre>
</div>
<p>This renders a basic table, using some <a href="http://twitter.github.com/bootstrap/base-css.html#tables" target="_blank">bootstrap CSS</a>, which has one row to display the column captions. </p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout2.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout2.png?w=480" alt="" title="knockout2"   class="aligncenter size-full wp-image-4484" /></a></p>
<p>The actual rows containing the timesheets aren&#8217;t being rendered yet. We&#8217;ll get to them soon.</p>
<p>We now need to create a view model for our page. Add the following JavaScript at the bottom of the index.cshtml file.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;</span>

$(<span class="kwrd">function</span> () {
    ko.applyBindings(viewModel);
    viewModel.loadTimesheets();
});

<span class="kwrd">var</span> viewModel = {
    timesheets: ko.observableArray([]),
    
    loadTimesheets: <span class="kwrd">function</span> () {
        <span class="rem">//...</span>
    }
};

<span class="kwrd">&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Here you declare a view model which has one property, timesheets, which is an array. Using Knockout you instruct the application to observe this array.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
timesheets: ko.observableArray([])</pre>
</div>
<p>This instructs Knockout to monitor the array for any changes. If you add or remove elements from the array then Knockout will automatically update any UI elements bound to this array.</p>
<p>Using jQuery you instruct Knockout to bind the view model (viewModel) to the page using the ko.applyBindings(viewModel) call. Once bound you instruct the view model to load the timesheets (viewModel.loadTimesheets()).</p>
<p>Let&#8217;s bind the rows of our table to this array. Replace the &lt;tbody&gt; tag of the table with the following HTML.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">tbody</span> <span class="attr">data-bind</span><span class="kwrd">="foreach: viewModel.timesheets"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">tr</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">td</span> <span class="attr">data-bind</span><span class="kwrd">="text: firstname"</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">td</span> <span class="attr">data-bind</span><span class="kwrd">="text: lastname"</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">td</span> <span class="attr">data-bind</span><span class="kwrd">="text: month"</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">td</span> <span class="attr">data-bind</span><span class="kwrd">="text: year"</span><span class="kwrd">&gt;&lt;/</span><span class="html">td</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">tr</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">tbody</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Notice the <strong>data-bind</strong> attribute on the row and cells. This is a HTML5 data- attribute used by Knockout to bind your data to DOM elements. First your instruct Knockout to render a row for each timesheet in the view model&#8217;s timesheets array. </p>
<p>When a row is being rendered, the context switches from the view model to an individual timesheet object. Hence you can bind each cell of a row to the properties of a timesheet.</p>
<p>Timsheet object? This is the type of object we&#8217;ll eventually add to the timesheets observable array. Let&#8217;s define the object in JavaScript.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
function timesheet(timesheet) {
    this.id = ko.observable(timesheet.id);
    this.firstname = ko.observable(timesheet.firstname);
    this.lastname = ko.observable(timesheet.lastname);
    this.month = ko.observable(timesheet.month);
    this.year = ko.observable(timesheet.year);
}</pre>
</div>
<p>A very simple JavaScript object, which initializes 5 properties (id, firstname, lastname&#8230;etc.) based on a timesheet object we pass into its &#8220;constructor&#8221;. Now let&#8217;s complete the loadTimesheets() function of our view model.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
loadTimesheets: function () {
    var self = this;
    $.getJSON(
        '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "timesheets" })',
        function (timesheets) {
            self.timesheets.removeAll();
            $.each(timesheets, function (index, item) {
                self.timesheets.push(new timesheet(item));
            });
        }
    );
}</pre>
</div>
<p>A single $.getJSON call to our Timesheets API controller. This will perform a GET request and thus will be handled by the Get(&#8230;) method defined on the TimesheetsController. It will retrieve all of the timesheets and return them as JSON data.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[{"firstname":"Christophe","lastname":"Geers","month":7,"year":2012},
 {"firstname":"Ruben","lastname":"Geers","month":8,"year":2012}]</pre>
</div>
<p>Once we receive this data we foreach over it and add an object to our observed array for each timesheet. If you refresh the page now you&#8217;ll notice that Knockout automatically rendered a row for each of our timesheets and that each individual property is bound to its respective cell.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/10/knockout3.png"><img src="http://cgeers.files.wordpress.com/2012/10/knockout3.png?w=480&#038;h=209" alt="DataBound Table" title="DataBound Table" width="480" height="209" class="aligncenter size-full wp-image-4498" /></a></p>
<p>Nice huh? That concludes the first part of the series on Knockout.js. In the next part I&#8217;ll start where we left off and show you how you can add timesheets using Knockout.js and Twitter Bootstrap&#8217;s <a href="http://twitter.github.com/bootstrap/javascript.html#modals" target="_blank">modal</a>.</p>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/knockout-js/'>Knockout.js</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4453/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4453&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/10/06/single-page-application-with-knockout-js-part-1/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout.png" medium="image">
			<media:title type="html">Knockout.js</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout11.png" medium="image">
			<media:title type="html">Timesheets</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout2.png" medium="image">
			<media:title type="html">knockout2</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/10/knockout3.png" medium="image">
			<media:title type="html">DataBound Table</media:title>
		</media:content>
	</item>
		<item>
		<title>An Introduction To MongoDB</title>
		<link>http://cgeers.com/2012/09/29/an-introduction-to-mongodb/</link>
		<comments>http://cgeers.com/2012/09/29/an-introduction-to-mongodb/#comments</comments>
		<pubDate>Sat, 29 Sep 2012 11:16:56 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4380</guid>
		<description><![CDATA[Introduction Next up, after GitHub and Bootstrap, in the session I presented last month during a company trip, is MongoDB. MongoDB is a NoSQL database, instead of storing data in tables, it stores structured data in JSON-like documents, also known as BSON (Binary JSON). This article isn&#8217;t about NoSQL, it just shows you how you [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4380&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap1.png"></a><a href="http://cgeers.files.wordpress.com/2012/09/mongodb.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb.png?w=90&#038;h=90" alt="MongoDB" title="MongoDB" width="90" height="90" class="alignright wp-image-4381" /></a></p>
<p>Next up, after <a href="http://cgeers.com/2012/09/15/getting-started-with-github/" target="_blank">GitHub</a> and <a href="http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/" target="_blank">Bootstrap</a>, in the session I presented last month during a company trip, is <a href="http://www.mongodb.org/" target="_blank">MongoDB</a>. </p>
<p>MongoDB is a NoSQL database, instead of storing data in tables, it stores structured data in JSON-like documents, also known as BSON (Binary JSON). </p>
<p>This article isn&#8217;t about NoSQL, it just shows you how you can quickly set up MongoDB and work with it in a .NET environment. Let&#8217;s walk through the necessary steps to get MongoDB up and running.</p>
<p><span id="more-4380"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#installation">Installation</a></li>
<li><a href="#windowsservice">Run as Windows Service</a></li>
<li><a href="#mongovue">MongoVUE</a></li>
<li><a href="#driver">MongoDB C# Driver</a></li>
<li><a href="#usage">Driver in Action</a></li>
</ul>
<p><a title="installation" name="installation"></a><strong>Installation</strong></p>
<p>Once you&#8217;ve downloaded <a href="http://www.mongodb.org/downloads" target="_blank">MongoDB</a> for Windows (32 or 64-bit), extract the archive to C:\mongodb (or another drive / directory).</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb2.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb2.png?w=480" alt="MongoDB extracted" title="MongoDB extracted"   class="aligncenter size-full wp-image-4393" /></a></p>
<p>Notice the bin subdirectory. MongoDB is self-contained and does not have any other system dependencies. You can run it from any folder you choose.</p>
<p>MongoDB requires a data folder to store its files. Start a Command Prompt and execute the following commands:</p>
<div class="csharpcode">
<pre>
cd \
md data
md data\db</pre>
</div>
<p>You can place the new data directory on any drive (or in any subdirectory) you want. To start MongoDB, execute the following command from the Command Prompt:</p>
<div class="csharpcode">
<pre>
c:\mongodb\bin\mongod.exe
</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="windowsservice" name="windowsservice"></a><strong>Run as Windows Service</strong></p>
<p>Using this setup you have to manually start MongoDB each time you reboot your PC. This is a bit inconvenient, but it works. If you don&#8217;t want to do this, then you can run MongoDB as a Windows Service. This way it will automatically be started on each reboot.</p>
<p>Open a Command Prompt (Run as Administrator) and execute the following commands:</p>
<div class="csharpcode">
<pre>
md c:\mongodb\log
echo logpath=c:\mongodb\log\mongo.log &gt; c:\mongodb\mongod.cfg
c:\mongodb\bin\mongod.exe --config c:\mongodb\mongod.cfg --install
net start MongoDB
</pre>
</div>
<p>First you create a new folder inside the mongodb folder called &#8220;log&#8221;. The second command creates a MongoDB configuration file and instructs it to store its log files inside the newly created folder. Next you install MongoDB as a Windows service. Last, but not least you start the service.</p>
<p>If you now open the Services app, you should see the Mongo DB service listed.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb3.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb3.png?w=480" alt="Windows Service" title="Windows Service"   class="aligncenter size-full wp-image-4403" /></a></p>
<p>Be sure to check that the startup type is set to Automatic. If not, open the service&#8217;s properties and change it.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb4.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb4.png?w=480" alt="Startup Type" title="Startup Type"   class="aligncenter size-full wp-image-4404" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="mongovue" name="mongovue"></a><strong>MongoVUE</strong></p>
<p>There are a couple of tools out there that allow you to manage MongoDB. Personally I prefer <a href="http://www.mongovue.com/" target="_blank">MongoVUE</a>. It is an easy to use desktop application for Windows. There is a paying version (35$) and a free version. The free one has fewer features, but for our purpose it more than suffices. Go ahead and <a href="http://www.mongovue.com/downloads/" target="_blank">download</a> it. </p>
<p><strong>Remark</strong>: During the installation process be sure to allow the Windows Firewall exception.</p>
<p>When you start MongoVUE it shows you a list of available connections.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb5.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb5.png?w=480" alt="Available Connections" title="Available Connections"   class="aligncenter size-full wp-image-4410" /></a></p>
<p>We need to add one for our localhost development environment. Click the + button and enter the following data:</p>
<ul>
<li><strong>Name</strong>: localhost</li>
<li><strong>Server</strong>: localhost</li>
<li><strong>Port</strong>: 27017</li>
</ul>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb6.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb6.png?w=480" alt="MongoDB Connection" title="MongoDB Connection"   class="aligncenter size-full wp-image-4411" /></a></p>
<p>After you&#8217;ve established a connection you can use the Database Explorer in the lefthand pane to navigate through your MongoDB databases. By default you&#8217;ll only see one database called local which doesn&#8217;t contain any collection (sort of like tables in a RDBMS).</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb7.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb7.png?w=480" alt="MongoDB databases" title="MongoDB databases"   class="aligncenter size-full wp-image-4414" /></a></p>
<p>No need to create them manually, let&#8217;s write some code to do that.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="driver" name="driver"></a><strong>MongoDB C# Driver</strong></p>
<p>Start Visual Studio and create a new blank solution called MongoDB. Next add a Console Application &#8220;Timesheets&#8221; to it. Your solution structure should resemble the following screenshot:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb91.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb91.png?w=480" alt="Solution Explorer" title="Solution Explorer"   class="aligncenter size-full wp-image-4423" /></a></p>
<p>In order to work with MongoDB in .NET you can use the <a href="http://nuget.org/packages/mongocsharpdriver" target="_blank">MongoDB C# driver</a> developed by the creators of MongoDB (<a href="http://www.10gen.com/" target="_blank">10gen</a>). The driver is available as a NuGet package. At the time of writing it is at version 1.6.</p>
<p>Go ahead and install the NuGet package.</p>
<div class="csharpcode">
<pre>
PM&gt; Install-Package mongocsharpdriver
</pre>
</div>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb11.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb11.png?w=480" alt="MongoDB C# driver" title="MongoDB C# driver"   class="aligncenter size-full wp-image-4428" /></a></p>
<p>We&#8217;re now ready to start working with MongoDB.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="usage" name="usage"></a><strong>Driver in Action</strong></p>
<p>Let&#8217;s see the driver in action. First we setup a connection.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">const</span> <span class="kwrd">string</span> connectionstring = <span class="str">"mongodb://localhost/my_first_mongodb_db"</span>;
<span class="kwrd">var</span> database = MongoDatabase.Create(connectionstring);</pre>
</div>
<p>Now add a simple class called Person to the project.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> Person
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
}</pre>
</div>
<p>We&#8217;ll be storing instances of this class in a MongoDB collection. But first we&#8217;ll need to obtain a MongoCollection instance. Each collection has a name, here we&#8217;ll use the type name of Person, but you can use any name you like.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
 <span class="kwrd">var</span> collection = database.GetCollection&lt;Person&gt;(<span class="kwrd">typeof</span> (Person).Name);</pre>
</div>
<p><strong>Remark</strong>: Notice the generic parameter type Person passed to the GetCollection(&#8230;) method. Here we specify that this collection will be working with the Person type.</p>
<p>Let&#8217;s create a new instance of Person and add it to the MongoDB collection.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> person = <span class="kwrd">new</span> Person
{
    FirstName = <span class="str">"Bruce"</span>,
    LastName = <span class="str">"Wayne"</span>
};

collection.Insert(person);</pre>
</div>
<p>Compile and run the application. Afterwards open MongoVUE and check out the Database Explorer. You&#8217;ll notice that a new database called &#8220;my_first_mongodb_db&#8221; has automatically been created for you.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb12.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb12.png?w=480" alt="First MongoDB DB" title="First MongoDB DB"   class="aligncenter size-full wp-image-4434" /></a></p>
<p>It contains one collection called Person and this collection contains one document which represents the instance we inserted into the collection.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb15.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb15.png?w=480" alt="Person Collection" title="Person Collection"   class="aligncenter size-full wp-image-4440" /></a></p>
<p>Notice that although our Person class does not contain an Id property MongoDB automatically assigned an _id (ObjectId) to the newly created document. Almost every MongoDB document has an _id field as its first attribute. ObjectId is the most common type used for it. _id must be unique for each document in a collection.</p>
<p><a href="http://www.mongodb.org/display/DOCS/Object+IDs" target="_blank">ObjectId</a> is a 12-byte binary value consisting out of:</p>
<ul>
<li>4-byte timestamp (seconds sinds epoch)</li>
<li>3-byte machine id</li>
<li>2-byte process id</li>
<li>3-byte counter</li>
</ul>
<p>Let&#8217;s add an Id property of type ObjectId to the Person class type.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> Person
{
    <span class="kwrd">public</span> ObjectId Id { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
    <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Copy the value of this _id in your clipboard. The value of your _id will of course be different.  You can now use this value to retrieve a person from the Person collection.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> query = Query.EQ(<span class="str">"_id"</span>, <span class="kwrd">new</span> ObjectId(<span class="str">"5066d3e332eb55739e8ac5a3"</span>));
<span class="kwrd">var</span> person = collection.Find(query).Single();
Console.WriteLine(<span class="kwrd">string</span>.Format(<span class="str">"{0} {1} {2}"</span>, person.Id, person.FirstName, person.LastName));</pre>
</div>
<p>The output:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/mongodb16.png"><img src="http://cgeers.files.wordpress.com/2012/09/mongodb16.png?w=480&#038;h=72" alt="Retrieve by ObjectId" title="Retrieve by ObjectId" width="480" height="72" class="aligncenter size-full wp-image-4445" /></a></p>
<p>Want to update a person? No problem, just retrieve the person from the collection, modify the necessary properties and save it back to the collection.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
person.FirstName = <span class="str">"Clark"</span>;
person.LastName = <span class="str">"Kent"</span>;
collection.Save(person);</pre>
</div>
<p>As a last example let&#8217;s clean up after ourselves, let&#8217;s delete the person from the collection.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
collection.Remove(Query.EQ(<span class="str">"_id"</span>, <span class="kwrd">new</span> ObjectId(<span class="str">"5066d3e332eb55739e8ac5a3"</span>)));</pre>
</div>
<p>I hope you enjoyed this quick introduction to MongoDB. Be sure to check it out in more detail. It’s very easy to setup and use, has a great community&#8230;etc. Might come in handy when you don&#8217;t want to go through the hassle of setting up (and paying for an) SQL Server / Oracle database.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/nosql/'>NoSQL</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4380/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4380/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4380&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/09/29/an-introduction-to-mongodb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb.png" medium="image">
			<media:title type="html">MongoDB</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb2.png" medium="image">
			<media:title type="html">MongoDB extracted</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb3.png" medium="image">
			<media:title type="html">Windows Service</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb4.png" medium="image">
			<media:title type="html">Startup Type</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb5.png" medium="image">
			<media:title type="html">Available Connections</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb6.png" medium="image">
			<media:title type="html">MongoDB Connection</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb7.png" medium="image">
			<media:title type="html">MongoDB databases</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb91.png" medium="image">
			<media:title type="html">Solution Explorer</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb11.png" medium="image">
			<media:title type="html">MongoDB C# driver</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb12.png" medium="image">
			<media:title type="html">First MongoDB DB</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb15.png" medium="image">
			<media:title type="html">Person Collection</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/mongodb16.png" medium="image">
			<media:title type="html">Retrieve by ObjectId</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting Started with Twitter Bootstrap</title>
		<link>http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/</link>
		<comments>http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/#comments</comments>
		<pubDate>Sun, 23 Sep 2012 12:17:39 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Twitter Bootstrap]]></category>
		<category><![CDATA[Bootstrap]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4295</guid>
		<description><![CDATA[Introduction Last week I wrote a post on how to get started with GitHub. It was part of a session I presented during a company trip early September. The second part of the session showed how you can quickly setup an ASP.NET MVC application and integrate Twitter Bootstrap into it. For those not familiar with [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4295&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap1.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap1.png?w=75&#038;h=75" alt="Twitter Bootstrap" title="Twitter Bootstrap" width="75" height="75" class="alignright wp-image-4300" /></a></p>
<p>Last week I wrote a post on how to <a href="http://cgeers.com/2012/09/15/getting-started-with-github/" target="_blank">get started with GitHub</a>. It was part of a session I presented during a company trip early September. The second part of the session showed how you can quickly setup an ASP.NET MVC application and integrate <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a> into it.</p>
<p>For those not familiar with Bootstrap, it is a collection of CSS and HTML conventions for helping you out with typograpghy, forms, buttons, navigations&#8230;etc. Included as well is a collection of (optional) JavaScript extensions. </p>
<p><span id="more-4295"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#download">Download</a></li>
<li><a href="#aspnetmvc">ASP.NET MVC Project</a></li>
<li><a href="#bootstrapping">Bootstrapping a Site</a></li>
<li><a href="#navbar">Navbar Component</a></li>
<li><a href="#responsivedesign">Responsive Design</a></li>
</ul>
<p><a title="download" name="download"></a><strong>Download</strong></p>
<p>Download the latest version of <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a>. Go ahead and click the big download button. It&#8217;ll download one archive called bootstrap.zip. You can also <a href="http://twitter.github.com/bootstrap/customize.html" target="_blank">customize the Twitter Bootstrap download</a>. Choose the components, jQuery plugins and default look and feel. But for now, the default package will do.</p>
<p>The archive contains a folder called &#8220;bootstrap&#8221;, which in turn contains 3 sub-folders.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap2.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap2.png?w=480" alt="Bootstrap Archive" title="Bootstrap Archive"   class="aligncenter size-full wp-image-4314" /></a></p>
<ul>
<li>The <strong>css</strong> folder contains 2 cascasding stylesheets:
<ul>
<li>bootstrap.css (+ bootstrap.min.css)</li>
<li>bootstrap-responsive.css (+ bootstrap-responsive.min.css)</li>
</ul>
</li>
<li>The <strong>js</strong> folder contains 1 JavaScript library:
<ul>
<li>bootstrap.js (+ bootstrap.min.js)</li>
</ul>
</li>
<li>The <strong>img</strong> folder contains 2 images:
<ul>
<li>glyphicons-halflings.png</li>
<li>glyphicons-halflings-white.png</li>
</ul>
</li>
</ul>
<p>As you can see both a debug and a minified version of the stylesheets and JavaScript library have been included. The glyphicons-halflings.png image contains about 140 icons. The glyphicons-halflings-white.png is just a white variant of the icons. Bootstrap uses the icons from <a href="http://glyphicons.com/" target="_blank">GLYPHICONS</a>. They are referenced in the stylesheets.</p>
<p><strong>Remark</strong>: If you customize the download you&#8217;ll get the same files, but the bootstrap.css and bootstrap-responsive.css have been merged into one file (bootstrap.css). The contents of the bootstrap-responsive.css files have been appended to the bootstrap.css file.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="aspnetmvc" name="aspnetmvc"></a><strong>ASP.NET MVC Project</strong></p>
<p>Integrating Twitter Bootstrap into an ASP.NET MVC site is a piece of cake. Let&#8217;s quickly iterate through the necessary steps. Start Visual Studio and create an new ASP.NET MVC 4 project (empty template), called TwitterBootstrap. Afterwards you should see the following files in your Solution Explorer.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap3.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap3.png?w=480" alt="ASP.NET MVC Project (Empty Template)" title="ASP.NET MVC Project (Empty Template)"   class="aligncenter size-full wp-image-4326" /></a></p>
<p>Extract the bootstrap.zip you downloaded earlier and copy the css, js and image folders into the root of the web application.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap4.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap4.png?w=480" alt="Bootstrap Resources" title="Bootstrap Resources"   class="aligncenter size-full wp-image-4328" /></a></p>
<p>Back in the Solution Explorer click the &#8220;Show All Files&#8221; button and include the 3 new folders into your project.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap5.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap5.png?w=480" alt="Include In Project" title="Include In Project"   class="aligncenter size-full wp-image-4330" /></a></p>
<p>You also need to download the latest <a href="http://jquery.com/" target="_blank">jQuery</a> version. Save it in the js folder and include it in your project.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap6.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap6.png?w=480" alt="jQuery" title="jQuery"   class="aligncenter size-full wp-image-4332" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="bootstrapping" name="bootstrapping"></a><strong>Bootstrapping a Site</strong></p>
<p>The ASP.NET MVC project now includes all the necessary Bootstrap resources. Let&#8217;s create a page which contains a Bootstrap component.</p>
<p>Add a basic master layout (Views\Shared\_master.cshtml) to the project. Add a new folder called Shared to the Views folder and add a new view named _master to it.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap71.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap71.png?w=480" alt="Master Layout" title="Master Layout"   class="aligncenter size-full wp-image-4339" /></a></p>
<p>A basic page containing some boilerplate HTML will be generated for you. Make sure the DOCTYPE declaration is set to the HTML 5 DOCTYPE as Bootstrap uses certain HTML 5 tags.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
﻿<span class="kwrd">&lt;!</span><span class="html">DOCTYPE</span> <span class="attr">html</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Include bootstrap.css (or bootstrap.min.css) and jQuery in the HEAD element.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">head</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">title</span><span class="kwrd">&gt;</span>Twitter Bootstrap<span class="kwrd">&lt;/</span><span class="html">title</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">link</span> <span class="attr">href</span><span class="kwrd">="@Url.Content("</span>~/<span class="attr">css</span>/<span class="attr">bootstrap</span>.<span class="attr">css</span><span class="kwrd">")"</span> <span class="attr">rel</span><span class="kwrd">="stylesheet"</span> <span class="attr">type</span><span class="kwrd">="text/css"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">src</span><span class="kwrd">="@Url.Content("</span>~/<span class="attr">js</span>/<span class="attr">jquery-1</span>.<span class="attr">8</span>.<span class="attr">2</span>.<span class="attr">min</span>.<span class="attr">js</span><span class="kwrd">")"</span> <span class="attr">type</span><span class="kwrd">="text/javascript"</span><span class="kwrd">&gt;&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">head</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Just before you close the BODY element include the bootstrap.js (or bootstrap.min.js) file.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">body</span><span class="kwrd">&gt;</span>
...
<span class="kwrd">&lt;</span><span class="html">script</span> <span class="attr">src</span><span class="kwrd">="@Url.Content("</span>~/<span class="attr">js</span>/<span class="attr">bootstrap</span>.<span class="attr">min</span>.<span class="attr">js</span><span class="kwrd">")"</span><span class="kwrd">&gt;&lt;/</span><span class="html">script</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">body</span><span class="kwrd">&gt;</span></pre>
</div>
<p>Alright, we&#8217;ve got a basic master layout now. We need to add at least one page. Add a new controller, HomeController, to the Controllers folder. Make sure the controller has one actoin method called Index.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">public</span> <span class="kwrd">class</span> HomeController : Controller
{
    <span class="kwrd">public</span> ActionResult Index()
    {
        <span class="kwrd">return</span> View();
    }
}</pre>
</div>
<p>Next add a new folder called Home to the Views folder and add a view named Index into this new folder. When creating the view select the _master.cshtml page as its master page.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap81.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap81.png?w=300&#038;h=295" alt="Index View" title="Index View" width="300" height="295" class="aligncenter size-medium wp-image-4351" /></a></p>
<p>OK, one remaining task. You&#8217;ve got to add the @RenderBody() method somewhere on the _master.cshtml page in order to render the Index view.</p>
<p>For example:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">body</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span><span class="kwrd">&gt;</span>
    @RenderBody()    
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    ...
<span class="kwrd">&lt;/</span><span class="html">body</span><span class="kwrd">&gt;</span></pre>
</div>
<p>If you compile and run the project you should get the following output:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap9.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap9.png?w=480" alt="Index" title="Index"   class="aligncenter size-full wp-image-4354" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="navbar" name="navbar"></a><strong>Navbar Component</strong></p>
<p>Now we can finally start using Twitter Bootstrap. Let&#8217;s demonstrate it using Bootstrap&#8217;s <a href="http://twitter.github.com/bootstrap/components.html#navbar" target="_blank">Navbar component</a>.</p>
<p>Just copy the following HTML directly below the BODY&#8217;s opening tag in the _master.cshtml file.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="navbar"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="navbar-inner"</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="container"</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">button</span> <span class="attr">type</span><span class="kwrd">="button"</span> <span class="attr">class</span><span class="kwrd">="btn btn-navbar"</span> 
                    <span class="attr">data-toggle</span><span class="kwrd">="collapse"</span> <span class="attr">data-target</span><span class="kwrd">=".nav-collapse"</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">class</span><span class="kwrd">="icon-bar"</span><span class="kwrd">&gt;&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">class</span><span class="kwrd">="icon-bar"</span><span class="kwrd">&gt;&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">span</span> <span class="attr">class</span><span class="kwrd">="icon-bar"</span><span class="kwrd">&gt;&lt;/</span><span class="html">span</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;/</span><span class="html">button</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">class</span><span class="kwrd">="brand"</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>Euricom<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">div</span> <span class="attr">class</span><span class="kwrd">="nav-collapse"</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">ul</span> <span class="attr">class</span><span class="kwrd">="nav"</span><span class="kwrd">&gt;</span>
                    <span class="kwrd">&lt;</span><span class="html">li</span> <span class="attr">class</span><span class="kwrd">="active"</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>GitHub<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
                    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>Bootstrap<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
                    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>MongoDB<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
                    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>Knockout<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
                    <span class="kwrd">&lt;</span><span class="html">li</span><span class="kwrd">&gt;&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="#"</span><span class="kwrd">&gt;</span>AppHarbor<span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;&lt;/</span><span class="html">li</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;/</span><span class="html">ul</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span></pre>
</div>
<p>It&#8217;s just a div containing a list of menu items. A couple of Bootstrap CSS classes are used here (navbar, navbar-inner, brand, nav, active). Bootstrap takes care of the rest and turns into a beautiful navigation bar. Go ahead and run it.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap10.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap10.png?w=480&#038;h=153" alt="Navbar" title="Navbar" width="480" height="153" class="aligncenter size-full wp-image-4360" /></a></p>
<p>Bootstrap contains a a chuckload components, JavaScript plugins&#8230;etc. which you can readily use. Just check out the <a href="http://twitter.github.com/bootstrap" target="_blank">Twitter Bootstrap site</a> to discover them.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="responsivedesign" name="responsivedesign"></a><strong>Responsive Design</strong></p>
<p>Just one last thing I want to address is the responsive design of Bootstrap. If you run the web application now and resize the browser to a small size you&#8217;ll get the following effect:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap11.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap11.png?w=480" alt="http://twitter.github.com/bootstrap/j" title="Responsive Design"   class="aligncenter size-full wp-image-4363" /></a></p>
<p>Readable, but not really a nice effect. Let&#8217;s remedy this. You only need to do one thing to achieve this. Include the bootstrap-responsive.css (or bootstrap-responsive.min.css) file just below the bootstrap.css link in the HEAD section.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">&lt;</span><span class="html">link</span> <span class="attr">href</span><span class="kwrd">="@Url.Content("</span>~/<span class="attr">css</span>/<span class="attr">bootstrap-responsive</span>.<span class="attr">css</span><span class="kwrd">")"</span> <span class="attr">rel</span><span class="kwrd">="stylesheet"</span> <span class="attr">type</span><span class="kwrd">="text/css"</span> <span class="kwrd">/&gt;</span></pre>
</div>
<p>Refresh the page.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap12.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap12.png?w=480" alt="Responsive Navbar" title="Responsive Navbar"   class="aligncenter size-full wp-image-4367" /></a></p>
<p>The menu items have been hidden (collapsed). Instead a button is shown. You can click this button to toggle the menu items.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/bootstrap13.png"><img src="http://cgeers.files.wordpress.com/2012/09/bootstrap13.png?w=480" alt="Navbar button" title="Navbar button"   class="aligncenter size-full wp-image-4369" /></a></p>
<p>Very easy if you quickly want to create a site which renders nicely on a desktop, tablet or smart phone.</p>
<p>If you take a look at the HTML code for the navbar you&#8217;ll notice that it contains a button which is initially hidden if the browser window is large enough, but is shown once the viewport is too small too display all the menu items. </p>
<p>Notice the HTML5 data- attribute (data-toggle) on the button. The menu items on the other hand are contained within a div that has the css class nav-collapse attributed to it. Using this information Bootstrap knows it should hide the menu items and show the button once the viewport is too small.</p>
<p><strong>Remark</strong>: If you want to include your own CSS file, it&#8217;s best to insert it between the bootstrap.css and bootstrap-responsive.min.css file to prevent the responsive part of Bootstrap from messing up your custom style.</p>
<p>I hope you enjoyed this quick introduction to <a href="http://twitter.github.com/bootstrap" target="_blank">Twitter Bootstrap</a>. Be sure to check it out in more detail. It&#8217;s very easy and contains a ton of useful components, plugins&#8230;etc.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/asp-net-mvc/'>ASP.NET MVC</a>, <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>, <a href='http://cgeers.com/category/programming/twitter-bootstrap/'>Twitter Bootstrap</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4295/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4295/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4295&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/09/23/getting-started-with-twitter-bootstrap/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap1.png" medium="image">
			<media:title type="html">Twitter Bootstrap</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap2.png" medium="image">
			<media:title type="html">Bootstrap Archive</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap3.png" medium="image">
			<media:title type="html">ASP.NET MVC Project (Empty Template)</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap4.png" medium="image">
			<media:title type="html">Bootstrap Resources</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap5.png" medium="image">
			<media:title type="html">Include In Project</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap6.png" medium="image">
			<media:title type="html">jQuery</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap71.png" medium="image">
			<media:title type="html">Master Layout</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap81.png?w=300" medium="image">
			<media:title type="html">Index View</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap9.png" medium="image">
			<media:title type="html">Index</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap10.png" medium="image">
			<media:title type="html">Navbar</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap11.png" medium="image">
			<media:title type="html">Responsive Design</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap12.png" medium="image">
			<media:title type="html">Responsive Navbar</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/bootstrap13.png" medium="image">
			<media:title type="html">Navbar button</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting Started with GitHub</title>
		<link>http://cgeers.com/2012/09/15/getting-started-with-github/</link>
		<comments>http://cgeers.com/2012/09/15/getting-started-with-github/#comments</comments>
		<pubDate>Sat, 15 Sep 2012 11:28:01 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[Source Control]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4236</guid>
		<description><![CDATA[Introduction Been a couple of months since I got around to writing a new post for this blog&#8230;busy times. Just got back from a company team building event in Tunisia last weekend. During this event we held 6 sessions about various topics such as Web API (@JefClaes), Roslyn (@svenschelfaut), Solid&#8230;etc. I gave a session about [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4236&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/09/octocat-1.png"><img src="http://cgeers.files.wordpress.com/2012/09/octocat-1.png?w=100&#038;h=100" alt="" title="Octocat" width="100" height="100" class="alignright size-thumbnail wp-image-4238" /></a></p>
<p>Been a couple of months since I got around to writing a new post for this blog&#8230;busy times. Just got back from a company team building event in Tunisia last weekend. During this event we held 6 sessions about various topics such as Web API (<a href="https://twitter.com/JefClaes" target="_blank">@JefClaes</a>), Roslyn (<a href="https://twitter.com/svenschelfaut" target="_blank">@svenschelfaut</a>), Solid&#8230;etc.</p>
<p>I gave a session about using various alternative technologies (read as: non Microsoft) to build a web application from scratch. These included:</p>
<ul>
<li><a href="https://github.com/" target="_blank">GitHub</a></li>
<li><a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a></li>
<li><a href="http://www.mongodb.org/" target="_blank">MongoDB</a></li>
<li><a href="http://knockoutjs.com/" target="_blank">Knockout.js</a></li>
<li><a href="https://appharbor.com/" target="_blank">AppHarbor</a></li>
</ul>
<p>So we&#8217;ve got everything from source control (GitHub), to layout (Bootstrap), database (MongoDB), client-side data binding / UI refreshes / &#8230; (Knockout) and deployment (AppHarbor). </p>
<p>Let&#8217;s discuss the first part in this article, namely GitHub. If you are already familiar with it, then you won&#8217;t learn anything new here. However if you are a Windows developer and have never used Git, this might be an easy way to get familiar with it.</p>
<p><span id="more-4236"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#setup">Signup at GitHub</a></li>
<li><a href="#firstrepository">Your First Repository</a></li>
<li><a href="#cloning">Cloning</a></li>
<li><a href="#shell">Working with the Shell</a></li>
<li><a href="#commands">Shell Commands</a></li>
</ul>
<p><a title="setup" name="setup"></a><strong>Signup at GitHub</strong></p>
<p>Of course you need to <a href="https://github.com/plans" target="_blank">signup at GitHub</a>. For open source it&#8217;s free. With a free account, you can create unlimited public repositories. Paying (and thus private repositories) range from 7$/mo to 200$/mo.</p>
<p>Once you&#8217;ve signed up and your account is in order, go ahead and download the <a href="http://windows.github.com/" target="_blank">GitHub for Windows client</a>. It&#8217;s the easiest way to use Git on Windows. </p>
<p>The installation is straightforward. Wizard-style, click next, next, next&#8230;etc. After you&#8217;ve started the application log in using your GitHub credentials. If you are familiar with Zune you&#8217;ll recognize the UI design.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github2.png"><img src="http://cgeers.files.wordpress.com/2012/09/github2.png?w=480&#038;h=200" alt="GitHub for Windows" title="GitHub for Windows" width="480" height="200" class="aligncenter size-full wp-image-4254" /></a></p>
<p>On the lefthand side you see two categories, <strong>local</strong> and <strong>github</strong>. The local category lists the repositories that you&#8217;ve copied (or cloned in git terms) to your PC. The github category lists the repositories that you&#8217;ve stored remotely on GitHub. As it stands now we don&#8217;t have any local or remote repositories.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="firstrepository" name="firstrepository"></a><strong>Your First Repository</strong></p>
<p>Let&#8217;s create our first repository. I usually do this via the GitHub site. Just go to the main page, you&#8217;ll find a &#8220;New repository&#8221; button somewhere on the righthand side.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github3.png"><img src="http://cgeers.files.wordpress.com/2012/09/github3.png?w=480" alt="New repository" title="New repository"   class="aligncenter size-full wp-image-4257" /></a></p>
<p>Name the new repository &#8220;HelloWorld&#8221; and click &#8220;New repository&#8221;. You&#8217;ll be redirected to a new page where you&#8217;ll have to specify a few details about the new repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github4.png"><img src="http://cgeers.files.wordpress.com/2012/09/github4.png?w=480" alt="Repository Details" title="Repository Details"   class="aligncenter size-full wp-image-4258" /></a></p>
<p>You need to enter the following data:</p>
<ul>
<li>Repository name (HelloWorld)</li>
<li>Description (optional)</li>
<li>Public or Private (only available if you have a paid account)</li>
<li>Initialize the repository with a README file</li>
<li>Specify a .gitignore file</li>
</ul>
<p>Most of these settings are-self explanatory. Make sure you specify a .gitignore file for the programming language in which your application will be written. Obviously I opted for C# here. </p>
<p>Using the .gitignore file you can specify the file types you do not wish to include in the repository (binaries, ReSharper files, archives&#8230;etc.). I always keep a .gitignore file for C# laying around that includes most of the file types that I want to ignore. You can download it here:</p>
<p><a href="https://dl.dropbox.com/u/40603470/.gitignore" target="_blank">https://dl.dropbox.com/u/40603470/.gitignore</a></p>
<p>Once all the details have been filled out go ahead and click on the &#8220;Create repository&#8221; button. Once the repository has been created you&#8217;ll see that it contains two files, namely a README.md and the .gitignore file. Using the Web UI you can directly edit the .gitignore file and copy/paste the contents of my C# .gitignore file. Go ahead and do so if you want.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github5.png"><img src="http://cgeers.files.wordpress.com/2012/09/github5.png?w=480&#038;h=74" alt="HelloWorld repository" title="HelloWorld repository" width="480" height="74" class="aligncenter size-full wp-image-4262" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="cloning" name="cloning"></a><strong>Cloning</strong></p>
<p>Alright, you&#8217;ve now created your first remote repository. Time to clone it to your local hard drive. First you need to specify a default storage directory. Go back to the GitHub Windows client and select &#8220;Tools &gt; Options&#8221;. Specify your default storage directory and click Update to save the settings.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github7.png"><img src="http://cgeers.files.wordpress.com/2012/09/github7.png?w=480" alt="Default storage directory " title="Default storage directory"   class="aligncenter size-full wp-image-4265" /></a></p>
<p>Back in the main screen select your account under the &#8220;github&#8221; category. You&#8217;ll get a list of your remote repositories. Select the HelloWorld repository, right click it and select the Clone option. The remote repository will now be cloned to your local hard drive.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github6.png"><img src="http://cgeers.files.wordpress.com/2012/09/github6.png?w=480" alt="Clone repository" title="Clone repository"   class="aligncenter size-full wp-image-4264" /></a></p>
<p>The remote repository is now cloned to your local storage directory. You should see a HelloWorld directory, that contains two files (README.md &amp; .gitignore) and also a hidden .git folder.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github8.png"><img src="http://cgeers.files.wordpress.com/2012/09/github8.png?w=480" alt="Local repository" title="Local repository"   class="aligncenter size-full wp-image-4267" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="shell" name="shell"></a><strong>Working with the Shell</strong></p>
<p>Up until now we&#8217;ve been using the GitHub site and the Windows client to interact with GitHub. The rest of the work will be done using the git shell or for Windows users the PowerShell that is installed with the Windows client. You can always change the default shell in the options section.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github9.png"><img src="http://cgeers.files.wordpress.com/2012/09/github9.png?w=480" alt="Default shell" title="Default shell"   class="aligncenter size-full wp-image-4269" /></a></p>
<p>I&#8217;m used to working with the PowerShell, so let&#8217;s stick with that one for now. Basically I only use the Windows client to clone my remote repositories. The rest of the git interaction is done via the shell. You can quickly open a shell for a repository by selecting the local repository in the Windows client, right-clicking on it and selecting the option &#8220;Open a shell here&#8221;.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github10.png"><img src="http://cgeers.files.wordpress.com/2012/09/github10.png?w=480" alt="Open a shell here" title="Open a shell here"   class="aligncenter size-full wp-image-4270" /></a></p>
<p>Voila, you&#8217;ve now opened a shell for the HelloWorld repository. As you can see in the screenshot below you&#8217;re currently located on the master branch of the repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github11.png"><img src="http://cgeers.files.wordpress.com/2012/09/github11.png?w=480&#038;h=114" alt="HelloWorld master branch" title="HelloWorld master branch" width="480" height="114" class="aligncenter size-full wp-image-4271" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="commands" name="commands"></a><strong>Shell Commands</strong></p>
<p>Let&#8217;s learn the basic commands you can issue in the shell.</p>
<p><strong><em>git status</em></strong></p>
<p>Use &#8220;git status&#8221; to query the state or your project. Right now we have a clean working directory as we&#8217;ve changed nothing.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github12.png"><img src="http://cgeers.files.wordpress.com/2012/09/github12.png?w=480&#038;h=106" alt="git status" title="git status" width="480" height="106" class="aligncenter size-full wp-image-4276" /></a></p>
<p>Let&#8217;s add a file called &#8220;helloworld.txt&#8221; to the working directory.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github13.png"><img src="http://cgeers.files.wordpress.com/2012/09/github13.png?w=480" alt="New file" title="New file"   class="aligncenter size-full wp-image-4277" /></a></p>
<p>If you run the &#8220;git status&#8221; command again, you&#8217;ll get the following result.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github14.png"><img src="http://cgeers.files.wordpress.com/2012/09/github14.png?w=480&#038;h=106" alt="Untracked file" title="Untracked file" width="480" height="106" class="aligncenter size-full wp-image-4278" /></a></p>
<p>Git noticed you&#8217;ve added one new untracked file (helloworld.txt). </p>
<p><strong><em>git add</em></strong></p>
<p>To have git track the new file you need to use the &#8220;git add&#8221; command.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github15.png"><img src="http://cgeers.files.wordpress.com/2012/09/github15.png?w=480&#038;h=63" alt="git add" title="git add" width="480" height="63" class="aligncenter size-full wp-image-4280" /></a></p>
<p>If you change a file that&#8217;s already being tracked you also need to &#8220;re-add&#8221; it using the &#8220;git add&#8221; command. You can add each new (or changed) file manually or you can use the shorthand command &#8220;git add .&#8221;. This will add all the new / changed files in one go.</p>
<p><strong><em>git commit</em></strong></p>
<p>Let&#8217;s make our first commit. When committing something in git you are always required to enter a comment to describe your commit. Luckily it&#8217;s not optional. It&#8217;s still up to you to enter a good commit message. &#8220;Fixed bug&#8221; or &#8220;So my boss wanted this button&#8230;&#8221; are not good example of commit messages.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github16.png"><img src="http://cgeers.files.wordpress.com/2012/09/github16.png?w=480&#038;h=97" alt="git commit" title="git commit" width="480" height="97" class="aligncenter size-full wp-image-4282" /></a></p>
<p><strong><em>git push</em></strong></p>
<p>If you perform the &#8220;git status&#8221; command, you&#8217;ll see that you have a clean working directory once again. But if you check the commit history on your remote repository using the GitHub site you won&#8217;t find the commit anywhere. That&#8217;s because all the commits happen locally. You need to issue the &#8220;git push&#8221; command to effectively push your local commits to your remote repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github17.png"><img src="http://cgeers.files.wordpress.com/2012/09/github17.png?w=480&#038;h=106" alt="git push" title="git push" width="480" height="106" class="aligncenter size-full wp-image-4283" /></a></p>
<p>If you check the commit history now, you&#8217;ll see that your local commits have been pushed to the remote repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github18.png"><img src="http://cgeers.files.wordpress.com/2012/09/github18.png?w=480" alt="Commit history" title="Commit history"   class="aligncenter size-full wp-image-4284" /></a></p>
<p><strong><em>git pull</em></strong></p>
<p>What if someone else pushed commits to the remote repository and you are working on a outdated local version? Easy, just open the shell and issue the &#8220;git pull&#8221; command. This will fetch from a remote repository and try to merge the changes into the current branch.</p>
<p>You can try this by first editing the helloworld.txt file using the GitHub site. If you then issue the &#8220;git pull&#8221; command git will merge the changes into your local repository.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/09/github19.png"><img src="http://cgeers.files.wordpress.com/2012/09/github19.png?w=480&#038;h=148" alt="git pull" title="git pull" width="480" height="148" class="aligncenter size-full wp-image-4288" /></a></p>
<p>I hope you enjoyed this quick introduction to GitHub / Git. If you want to learn more about the git command-line interface, check out the <a href="http://gitref.org/" target="_blank">Git Reference</a>. In the next post I&#8217;ll discuss how you can quickly get a basic site up and running using <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a>. Until then, happy coding.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/github/'>GitHub</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4236/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4236/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4236&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/09/15/getting-started-with-github/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/octocat-1.png?w=150" medium="image">
			<media:title type="html">Octocat</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github2.png" medium="image">
			<media:title type="html">GitHub for Windows</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github3.png" medium="image">
			<media:title type="html">New repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github4.png" medium="image">
			<media:title type="html">Repository Details</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github5.png" medium="image">
			<media:title type="html">HelloWorld repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github7.png" medium="image">
			<media:title type="html">Default storage directory</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github6.png" medium="image">
			<media:title type="html">Clone repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github8.png" medium="image">
			<media:title type="html">Local repository</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github9.png" medium="image">
			<media:title type="html">Default shell</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github10.png" medium="image">
			<media:title type="html">Open a shell here</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github11.png" medium="image">
			<media:title type="html">HelloWorld master branch</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github12.png" medium="image">
			<media:title type="html">git status</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github13.png" medium="image">
			<media:title type="html">New file</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github14.png" medium="image">
			<media:title type="html">Untracked file</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github15.png" medium="image">
			<media:title type="html">git add</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github16.png" medium="image">
			<media:title type="html">git commit</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github17.png" medium="image">
			<media:title type="html">git push</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github18.png" medium="image">
			<media:title type="html">Commit history</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/09/github19.png" medium="image">
			<media:title type="html">git pull</media:title>
		</media:content>
	</item>
		<item>
		<title>SkyDrive: Listing Folders and Files</title>
		<link>http://cgeers.com/2012/05/01/skydrive-listing-folders-and-files/</link>
		<comments>http://cgeers.com/2012/05/01/skydrive-listing-folders-and-files/#comments</comments>
		<pubDate>Tue, 01 May 2012 17:56:41 +0000</pubDate>
		<dc:creator>Christophe</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Live SDK]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SkyDrive]]></category>

		<guid isPermaLink="false">http://cgeers.com/?p=4198</guid>
		<description><![CDATA[Introduction The previous article, Getting Started with the Live SDK: Authorization, shows you have to request a user&#8217;s permission to access parts of their Live ID, including SkyDrive. Time to take a closer look at what we can do with the REST API and SkyDrive. Listing a user&#8217;s folders and files stored in his SkyDrive [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4198&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="introduction" name="introduction"></a><strong>Introduction</strong><a href="http://cgeers.files.wordpress.com/2012/04/live.png"><img src="http://cgeers.files.wordpress.com/2012/04/live.png?w=480" alt="Live SDK" title="Live SDK"   class="alignright size-full wp-image-4149" /></a></p>
<p>The previous article, <a href="http://cgeers.com/2012/04/29/getting-started-with-the-live-sdk-authorization/" target="_blank">Getting Started with the Live SDK: Authorization</a>, shows you have to request a user&#8217;s permission to access parts of their Live ID, including SkyDrive.</p>
<p>Time to take a closer look at what we can do with the REST API and SkyDrive. Listing a user&#8217;s folders and files stored in his SkyDrive seems like as good as any place to start.</p>
<p><span id="more-4198"></span></p>
<p><a title="top" name="top"></a><strong>Table Of Contents</strong></p>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#scopes">Scopes</a></li>
<li><a href="#folders">Folders, Albums, Files, Photos, Videos&#8230;</a></li>
<li><a href="#listing">Listing Folders</a></li>
<li><a href="#othercontent">Other Content Types</a></li>
<li><a href="#foldercontents">Folder Contents</a></li>
</ul>
<p><a title="scopes" name="scopes"></a><strong>Scopes</strong></p>
<p>When the user authorizes your application you can specify the scopes to which you want access. Their profile, work information, postal addresses&#8230;etc. The list goes on, you can find it here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/live/hh243646" target="_blank">http://msdn.microsoft.com/en-us/library/live/hh243646</a></p>
<p>If you want to list the folders and files of the user&#8217;s SkyDrive account you need to make sure you request access for the following scopes:</p>
<ul>
<li><strong>wl.skydrive</strong>: Read access to a user&#8217;s files stored in SkyDrive.</li>
<li><strong>wl.photos</strong>: Read access to a user&#8217;s photos, videos, audio, and albums.</li>
</ul>
<p>So let&#8217;s quickly generate a new access token:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> uri = <span class="str">"https://login.live.com/oauth20_authorize.srf"</span>;

<span class="kwrd">var</span> authorizeUri = <span class="kwrd">new</span> StringBuilder(uri);

authorizeUri.AppendFormat(<span class="str">"?client_id={0}&amp;"</span>, <span class="str">"your_client_id"</span>);
authorizeUri.AppendFormat(<span class="str">"scope={0}&amp;"</span>, 
    <span class="str">"wl.signin%20wl.photos%20wl.skydrive"</span>);
authorizeUri.AppendFormat(<span class="str">"response_type={0}&amp;"</span>, <span class="str">"token"</span>);
authorizeUri.AppendFormat(<span class="str">"redirect_uri={0}"</span>, 
UrlEncode(<span class="str">"http://redirect_uri.com"</span>));</pre>
</div>
<p><strong>Remark</strong>: Each scope value needs to be separated by a space (%20). For brevity&#8217;s sake I&#8217;ve put them in there directly.</p>
<p>The user will asked to grant the necessary permissions:</p>
<p><a href="http://cgeers.files.wordpress.com/2012/05/skydrive1.png"><img src="http://cgeers.files.wordpress.com/2012/05/skydrive1.png?w=480" alt="SkyDrive Scopes" title="SkyDrive Scopes"   class="aligncenter size-full wp-image-4208" /></a></p>
<p>Permissions to which you already have access will not be listed again. Need more information on authorizing your application? Check ouf the <a href="http://cgeers.com/2012/04/29/getting-started-with-the-live-sdk-authorization/" target="_blank">first article</a>.</p>
<p>When the user authorizes your application you will be redirected to the URL you specified and it will contain an authorization token. Get it. Even if it is ridiculously long.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="folders" name="folders"></a><strong>Folders, Albums, Files, Photos, Videos&#8230;</strong></p>
<p>If you take a look at the <a href="http://msdn.microsoft.com/en-us/library/live/hh243648.aspx" target="_blank">REST reference</a> you&#8217;ll find a couple of objects connected to SkyDrive such as Folder, Album, File, Photo, Video&#8230;etc. Most of them share a lot of properties, so let&#8217;s create a base class for them.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> FileSystemInfo
{
    [JsonProperty(PropertyName = <span class="str">"id"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Id { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"name"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"created_time"</span>)]
    [JsonConverter(<span class="kwrd">typeof</span>(IsoDateTimeConverter))]
    <span class="kwrd">public</span> DateTime CreatedTime { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [JsonProperty(PropertyName = <span class="str">"type"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Type { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    <span class="rem">//...</span>
}</pre>
</div>
<p>I&#8217;ve not listed all the properties here, there are too many. Check out the REST reference, compare the objects and add the common properties. The JSON.NET attributes will help us later when deserialing the response.</p>
<p>Photos have a couple of different properties. Let&#8217;s add those to a descendant class.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> Photo : FileSystemInfo
{
    [JsonProperty(<span class="str">"size"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">int</span> Size { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [JsonProperty(<span class="str">"when_taken"</span>)]
    <span class="kwrd">public</span> DateTime? WhenTaken { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    [JsonProperty(<span class="str">"location"</span>)]
    <span class="kwrd">public</span> Location Location { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }

    <span class="rem">//...</span>
}</pre>
</div>
<p>Again not all properties are listed. Check out the <a href="http://msdn.microsoft.com/en-us/library/live/hh243648.aspx#photo" target="_blank">Photo Object</a> if you want to add more.</p>
<p>The same goes for the Video object. I&#8217;ll not list it here, just check out the source code that comes with this article. </p>
<p>Did you notice the Type (string) property on the FileSystemInfo class? This type will tell us what type of object we are dealing with. Folder, photo, video&#8230;etc. It will come in handy when deserializing the returned data.</p>
<p><a href="#top">Top of page</a></p>
<p><a title="listing" name="listing"></a><strong>Listing Folders</strong></p>
<p>To list all the folder of a user&#8217;s SkyDrive account you simply sent a GET request to:</p>
<p><a href="https://apis.live.net/v5.0/me/skydrive/files" target="_blank">https://apis.live.net/v5.0/me/skydrive/files</a></p>
<p>Just don&#8217;t forget to append the access token.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> requestUri = <span class="kwrd">new</span> StringBuilder(<span class="str">"https://apis.live.net/v5.0/me/skydrive/files"</span>);
requestUri.AppendFormat(<span class="str">"?access_token={0}"</span>, <span class="str">"access token"</span>);
<span class="kwrd">var</span> request = (HttpWebRequest)WebRequest.Create(requestUri.ToString());
request.Method = <span class="str">"GET"</span>;</pre>
</div>
<p>The response will, as always, be JSON-formatted. Let&#8217;s deserialize it to an IEnumerable of Folder. But first add the following SkyDrive type to your project.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
[JsonObject(MemberSerialization.OptIn)]
<span class="kwrd">public</span> <span class="kwrd">class</span> SkyDrive
{
    [JsonProperty(PropertyName = <span class="str">"data"</span>)]
    <span class="kwrd">public</span> IEnumerable&lt;Folder&gt; Folders { <span class="kwrd">get</span>; <span class="kwrd">set</span>; }
}</pre>
</div>
<p>Now you can easily deserialize the list of folders.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> response = (HttpWebResponse)request.GetResponse();
<span class="kwrd">using</span> (<span class="kwrd">var</span> reader = <span class="kwrd">new</span> StreamReader(response.GetResponseStream()))
{
    <span class="kwrd">var</span> json = reader.ReadToEnd();

    <span class="kwrd">var</span> skyDrive = JsonConvert.DeserializeObject&lt;SkyDrive&gt;(json);

    <span class="kwrd">foreach</span> (<span class="kwrd">var</span> folder <span class="kwrd">in</span> skyDrive.Folders)
    {
        Console.WriteLine(String.Format(<span class="str">"{0}: {1}"</span>, folder.Id, folder.Name));
    }
}</pre>
</div>
<p>This will output all the folders in the user&#8217;s SkyDrive root.</p>
<p><a href="http://cgeers.files.wordpress.com/2012/05/skydrive2.png"><img src="http://cgeers.files.wordpress.com/2012/05/skydrive2.png?w=480&#038;h=123" alt="SkyDrive Folders" title="SkyDrive Folders" width="480" height="123" class="aligncenter size-full wp-image-4219" /></a></p>
<p><a href="#top">Top of page</a></p>
<p><a title="othercontent" name="othercontent"></a><strong>Other Content Types</strong></p>
<p>The previous example is a bit hopeful. Only store folders and you&#8217;ll be fine. No files please. They will be treated as folders.</p>
<p>To use the other content types (album, photo, video, file&#8230;etc.) you have to inspect the type property. Once you have the JSON response, parse it and inspect the returned data.</p>
<p>For example:</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> json = JObject.Parse(reader.ReadToEnd());

<span class="kwrd">var</span> contents = <span class="kwrd">new</span> List&lt;FileSystemInfo&gt;();
<span class="kwrd">foreach</span> (<span class="kwrd">var</span> item <span class="kwrd">in</span> json[<span class="str">"data"</span>])
{
    <span class="kwrd">var</span> type = item[<span class="str">"type"</span>].ToString();
    <span class="kwrd">switch</span> (type)
    {
        <span class="kwrd">case</span> <span class="str">"photo"</span>:
            contents.Add(JsonConvert.DeserializeObject&lt;Photo&gt;(item.ToString()));
            <span class="kwrd">break</span>;

        <span class="kwrd">case</span> <span class="str">"video"</span>:
            contents.Add(JsonConvert.DeserializeObject&lt;Video&gt;(item.ToString()));
            <span class="kwrd">break</span>;

        <span class="kwrd">case</span> <span class="str">"folder"</span>:
        <span class="kwrd">case</span> <span class="str">"album"</span>:
            contents.Add(JsonConvert.DeserializeObject&lt;Folder&gt;(item.ToString()));
            <span class="kwrd">break</span>;
    }
}</pre>
</div>
<p>Then you can list all the content types and use their specific properties.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">foreach</span> (<span class="kwrd">var</span> item <span class="kwrd">in</span> contents)
{
    Console.WriteLine(String.Format(<span class="str">"{0} : {1}"</span>, item.Type, item.Name));
    <span class="kwrd">if</span> (item <span class="kwrd">is</span> Photo)
    {
        Console.WriteLine(String.Format(<span class="str">"Size: {0} bytes"</span>, ((Photo) item).Size));
    }
}</pre>
</div>
<p><a href="#top">Top of page</a></p>
<p><a title="foldercontents" name="foldercontents"></a><strong>Folder Contents</strong></p>
<p>One last thing I want to address for this post is how to list a folder&#8217;s contents. Listing the folders of the root folder will not return the contents (files, subfolders&#8230;) of these folders.</p>
<p>However requesting the contents of a folder is very similar. Instead of sending a GET request to:</p>
<p><a href="https://apis.live.net/v5.0/me/skydrive/files" target="_blank">https://apis.live.net/v5.0/me/skydrive/files</a></p>
<p>You need to send a request to:</p>
<p><a href="https://apis.live.net/v5.0/{folder_id}/files" target="_blank">https://apis.live.net/v5.0/{folder_id}/files</a></p>
<p>Just replace {folder_id} with the ID of the folder for which you want to list the contents and you are set.</p>
<div class="csharpcode">
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre>
<span class="kwrd">var</span> uri = <span class="str">"https://apis.live.net/v5.0/{0}/files"</span>;
<span class="kwrd">var</span> requestUri = <span class="kwrd">new</span> StringBuilder(String.Format(uri, <span class="str">"your_folder_id"</span>));
requestUri.AppendFormat(<span class="str">"?access_token={0}"</span>, <span class="str">"your_access_token"</span>);
<span class="kwrd">var</span> request = (HttpWebRequest)WebRequest.Create(requestUri.ToString());
request.Method = <span class="str">"GET"</span>;

<span class="kwrd">var</span> response = (HttpWebResponse)request.GetResponse();
<span class="kwrd">using</span> (<span class="kwrd">var</span> reader = <span class="kwrd">new</span> StreamReader(response.GetResponseStream()))
{
    <span class="kwrd">var</span> json = JObject.Parse(reader.ReadToEnd());

    <span class="rem">// Parse the JSON data here</span>
    <span class="rem">// ...</span>
}</pre>
</div>
<p>You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.</p>
<p><a href="#top">Top of page</a></p>
<br />Filed under: <a href='http://cgeers.com/category/programming/c/'>C#</a>, <a href='http://cgeers.com/category/programming/live-sdk/'>Live SDK</a>, <a href='http://cgeers.com/category/programming/'>Programming</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cgeers.wordpress.com/4198/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/cgeers.wordpress.com/4198/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=cgeers.com&#038;blog=2504479&#038;post=4198&#038;subd=cgeers&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://cgeers.com/2012/05/01/skydrive-listing-folders-and-files/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/fb4348981494310223376b6e6e094e0b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cgeers</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/04/live.png" medium="image">
			<media:title type="html">Live SDK</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/05/skydrive1.png" medium="image">
			<media:title type="html">SkyDrive Scopes</media:title>
		</media:content>

		<media:content url="http://cgeers.files.wordpress.com/2012/05/skydrive2.png" medium="image">
			<media:title type="html">SkyDrive Folders</media:title>
		</media:content>
	</item>
	</channel>
</rss>
