<?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>iStern Blog</title>
	<atom:link href="http://blog.istern.dk/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.istern.dk</link>
	<description>A simple Code Blog</description>
	<lastBuildDate>Fri, 18 May 2012 14:44:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.istern.dk' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>iStern Blog</title>
		<link>http://blog.istern.dk</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.istern.dk/osd.xml" title="iStern Blog" />
	<atom:link rel='hub' href='http://blog.istern.dk/?pushpress=hub'/>
		<item>
		<title>Queries in Datasource location on Sitecore Layouts</title>
		<link>http://blog.istern.dk/2012/05/15/queries-in-datasource-location-on-sitecore-layouts/</link>
		<comments>http://blog.istern.dk/2012/05/15/queries-in-datasource-location-on-sitecore-layouts/#comments</comments>
		<pubDate>Tue, 15 May 2012 07:28:44 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Sitecore 6]]></category>
		<category><![CDATA[Sitecore]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=218</guid>
		<description><![CDATA[The datasource location specified on layouts is limited to Sitecore paths. But working with multisite solutions it is sometimes necessary to have some items stored locally under Site. This could be done fairly easy hooking in to the Sitecore pipeline “getRenderingDatasource”, found in the web.config under &#8220;/configuration/sitecore/pipelines/getRenderingDatasource&#8221; Below I&#8217;ve inserted my own “PT.Framework.Pipelines.GetDatasourceLocation,PT.Framework.Pipelines” The code [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=218&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The datasource location specified on layouts is limited to Sitecore paths.</p>
<p>But working with multisite solutions it is sometimes necessary to have some items stored locally under Site.</p>
<p>This could be done fairly easy hooking in to the Sitecore pipeline “getRenderingDatasource”, found in the web.config under<br />
&#8220;/configuration/sitecore/pipelines/getRenderingDatasource&#8221;</p>
<p>Below I&#8217;ve inserted my own</p>
<p>“PT.Framework.Pipelines.GetDatasourceLocation,PT.Framework.Pipelines”</p>
<p><pre class="brush: xml;">
&lt;getRenderingDatasource&gt;
 &lt;processor type=&quot;Sitecore.Pipelines.GetRenderingDatasource.GetDatasourceLocation, Sitecore.Kernel&quot; /&gt;
 &lt;processor type=&quot;PT.Framework.Pipelines.GetDatasourceLocation,PT.Framework.Pipelines&quot; /&gt;
 &lt;processor type=&quot;Sitecore.Pipelines.GetRenderingDatasource.SetFallbackDatasourceLocations, Sitecore.Kernel&quot; /&gt;
 &lt;processor type=&quot;Sitecore.Pipelines.GetRenderingDatasource.GetDatasourceTemplate, Sitecore.Kernel&quot; /&gt;
 &lt;processor type=&quot;Sitecore.Pipelines.GetRenderingDatasource.GetTemplatesForSelection, Sitecore.Kernel&quot; /&gt;
 &lt;processor type=&quot;Sitecore.Pipelines.GetRenderingDatasource.CheckDialogState, Sitecore.Kernel&quot; /&gt;
 &lt;processor type=&quot;Sitecore.Pipelines.GetRenderingDatasource.GetDialogUrl, Sitecore.Kernel&quot; /&gt;
 &lt;/getRenderingDatasource&gt;

</pre></p>
<p>The code for this step is really simple:</p>
<p><pre class="brush: csharp;">&lt;/pre&gt;
public void Process(GetRenderingDatasourceArgs args)
 {
 Assert.IsNotNull(args, &quot;args&quot;);
 DatasourceLocation = args.RenderingItem[&quot;Datasource Location&quot;];
 if(QueryInDataSourceLocation())
 ProcessQuery(args);
 }

private void ProcessQuery(GetRenderingDatasourceArgs args)
 {
 ContextItemPath = args.ContextItemPath;
 ContentDataBase = args.ContentDatabase;
 Item datasourceLocation = ResolveDatasourceRootFromQuery();
 if (datasourceLocation != null)
 args.DatasourceRoots.Add(datasourceLocation);
 }

private bool QueryInDataSourceLocation()
 {
 return DatasourceLocation.StartsWith(_query);
 }

private Item ResolveDatasourceRootFromQuery()
 {
 string query = DatasourceLocation.Replace(_query, ContextItemPath);
 return ContentDataBase.SelectSingleItem(query);
 }

private string DatasourceLocation { get; set; }
 private string ContextItemPath { get; set; }
 private Database ContentDataBase { get; set; }
 private const string _query = &quot;query:.&quot;;
&lt;pre&gt;
</pre></p>
<p>Now you can write queries like &#8220;./ancestor-or-self::*[@@templatekey='site']/Spots&#8221;</p>
<p><strong>Update &#8211; Multiple datasource locations</strong></p>
<p>Since one might want to have multiple Datasource Roots i made a change to the code so you can separate queries with the &#8220;|&#8221; delimiter. Note the normal sitecore path is still working and handled by the<br />
&#8220;Sitecore.Pipelines.GetRenderingDatasource.GetDatasourceLocation&#8221;.</p>
<p>Now you can write</p>
<p>query:./ancestor-or-self::*[@@templatekey='main section']/QueryGlobal|/sitecore/content/GlobalSpots|query:./ancestor-or-self::*[@@templatekey='site']/Spots</p>
<p><pre class="brush: csharp;">

public class GetDatasourceLocation
 {
 public void Process(GetRenderingDatasourceArgs args)
 {
 Assert.IsNotNull(args, &quot;args&quot;);
 DatasourceLocation = args.RenderingItem[&quot;Datasource Location&quot;];
 ContextItemPath = args.ContextItemPath;
 ContentDataBase = args.ContentDatabase;
 DatasourceRoots = args.DatasourceRoots;
 if(QueryInDataSourceLocation())
 ProcessQuerys(args);
 }

private void ProcessQuerys(GetRenderingDatasourceArgs args)
 {

ListString possibleQueries = new ListString(DatasourceLocation);
 foreach (string possibleQuery in possibleQueries)
 {
 if (possibleQuery.StartsWith(_query))
 ProcessQuery(possibleQuery);
 }

 }
 private bool QueryInDataSourceLocation()
 {
 return DatasourceLocation.Contains(_query);
 }

private void ProcessQuery(string query)
 {

 Item datasourceLocation = ResolveDatasourceRootFromQuery(query);
 if (datasourceLocation != null)
 DatasourceRoots.Add(datasourceLocation);
 }

private Item ResolveDatasourceRootFromQuery(string query)
 {
 string queryPath = query.Replace(_query, ContextItemPath);
 return ContentDataBase.SelectSingleItem(queryPath);
 }

private string DatasourceLocation { get; set; }
 private string ContextItemPath { get; set; }
 private Database ContentDataBase { get; set; }
 private List&lt;Item&gt; DatasourceRoots { get; set; }
 private const string _query = &quot;query:.&quot;;

}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/218/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=218&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2012/05/15/queries-in-datasource-location-on-sitecore-layouts/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Unit testing Sitecore with Typemock Isolater.</title>
		<link>http://blog.istern.dk/2012/04/27/unit-testing-sitecore-with-typemock-isolater/</link>
		<comments>http://blog.istern.dk/2012/04/27/unit-testing-sitecore-with-typemock-isolater/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 07:29:02 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[Sitecore 6]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Sitecore]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=203</guid>
		<description><![CDATA[In my last post I gave a stub example for a Sitecore Item. With the stub item you could test functionality for retrieving field data, which greatly limits the functionality you can test. So in this post I will have a look at the more advanced mocking framework Isolator from Typemock.  With the Isolator framework [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=203&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my last post I gave a stub example for a Sitecore Item. With the stub item you could test functionality for retrieving field data, which greatly limits the functionality you can test. So in this post I will have a look at the more advanced mocking framework Isolator from <a href="http://typemock.com/">Typemock</a>.  With the Isolator framework it is possible to intercept calls for methods that normally wouldn’t be possible, for example static methods. How may this help us? Since Sitecore hasn’t made it any easier to do unit testing with a great deal of static classes and methods alike, you will be able to mock or stub them out with the Isolator framework. The following is a simple example for testing functionality for Item.Children, ie. Sitecores Childlist.</p>
<p>Here we have a simple piece of code that, given a specific Template ID, adds an item to a list and returns the list.</p>
<p><pre class="brush: csharp;">
public class SectionFactory
{
   public static IEnumerable&lt;Section&gt; CreateCollection(Item columnItem)
   {
      ID sectionTemplateId = new ID(Constants.Templates.Section);
      ChildList children = columnItem.Children;
      List&lt;Item&gt; sections = new List&lt;Section&gt;();
      foreach (Item child in children)
      {
         if (child.TemplateID == sectionTemplateId)
            sections.Add(new Section(child))

      }

     return sections;
 }
}

</pre></p>
<p>Since getting the children for a Item invokes more than a few static methods and classes it is impossible to stub the functionality using most mocking frameworks. But with the Isolator Framework it is possible.</p>
<p><pre class="brush: csharp;">
[TestFixture]
 public class SectionFactoryTest
 {
 [Test]
 public void SectionFactoryNoChildrenReturnEmpyList()
 {
 Item stub = Isolate.Fake.Instance&lt;Item&gt;();
 ChildList childlist = Isolate.Fake.Instance&lt;ChildList&gt;();
 Isolate.WhenCalled(() =&gt; stub.Children).WillReturn(childlist);
 IEnumerable&lt;Section&gt; sectionList = SectionFactory.CreateCollection(stub);
 Assert.AreEqual(new List&lt;Section&gt;(), sectionList);
 }

[Test]
 public void SectionFactoryOneChildReturnEmpyList()
 {
 Item stub = Isolate.Fake.Instance&lt;Item&gt;();
 Item child = Isolate.Fake.Instance&lt;Item&gt;();
 ChildList childlist = Isolate.Fake.Instance&lt;ChildList&gt;();

ID sectionTemplate = new ID(Constants.Templates.Section);
 Isolate.WhenCalled(() =&gt; child.TemplateID).WillReturn(sectionTemplate);
 Isolate.WhenCalled(() =&gt; childlist).WillReturnCollectionValuesOf(new List&lt;Item&gt;(){child});
 Isolate.WhenCalled(() =&gt; stub.Children).WillReturn(childlist);

ID link = new ID(Constants.Fields.Section.Links);
 Isolate.WhenCalled(() =&gt; LinkRepository.GetCollection(child, link)).WillReturn(null);

IEnumerable&lt;Section&gt; sectionList = SectionFactory.CreateCollection(stub);
 Section section = sectionList.FirstOrDefault();
 Assert.That(section, Is.Not.Null);

 }

[Test]
 public void SectionFactoryOneValidSectionChildChildReturnEmpyList()
 {
 Item stub = Isolate.Fake.Instance&lt;Item&gt;();
 Item sectionChild = Isolate.Fake.Instance&lt;Item&gt;();
 Item child = Isolate.Fake.Instance&lt;Item&gt;();
 ChildList childlist = Isolate.Fake.Instance&lt;ChildList&gt;();

ID sectionTemplate = new ID(Constants.Templates.Section);
 Isolate.WhenCalled(() =&gt; sectionChild.TemplateID).WillReturn(sectionTemplate);
 Isolate.WhenCalled(() =&gt; child.TemplateID).WillReturn(null);
 Isolate.WhenCalled(() =&gt; childlist).WillReturnCollectionValuesOf(new List&lt;Item&gt;() { child, sectionChild });
 Isolate.WhenCalled(() =&gt; stub.Children).WillReturn(childlist);

ID link = new ID(Constants.Fields.Section.Links);
 Isolate.WhenCalled(() =&gt; LinkRepository.GetCollection(child, link)).WillReturn(null);

IEnumerable&lt;Section&gt; sectionList = SectionFactory.CreateCollection(stub);

 Assert.AreEqual(1,sectionList.Count());

}
 }

</pre></p>
<p>So with the above test we managed to get a 100% test coverage for the code.<br />
And with the Isolator Framework we could even mock out the Sitecore.Context. The Isolater framework is must a have if you want to do unit testing with Sitecore.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/203/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/203/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/203/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=203&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2012/04/27/unit-testing-sitecore-with-typemock-isolater/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Unit testing with Sitecore Item</title>
		<link>http://blog.istern.dk/2012/02/07/unit-testing-with-sitecore-item/</link>
		<comments>http://blog.istern.dk/2012/02/07/unit-testing-with-sitecore-item/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 08:32:30 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Sitecore 6]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Sitecore]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=167</guid>
		<description><![CDATA[This post is about how to do unit testing  with Sitecore. Off course this is not easily done, because Sitecore requires a &#8220;context&#8221; to work.  There are a couple of blogs out there , that explains how to setup either a custom test runner, where you can xecute tests through a webpage. or alternative setup [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=167&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div>This post is about how to do unit testing  with Sitecore. Off course this is not easily done, because Sitecore requires a &#8220;context&#8221; to work.  There are a couple of blogs out there , that explains how to setup either a custom test runner, where you can xecute tests through a webpage. or alternative setup an app_config file so you can work with Sitecore without a httpcontext. Links to both examples are given in bottom of this posts.</div>
<div>
<div>Both are really good, but I would categorize testing this way more as Integrations tests.  Since they both depend on external resources  such as  Sitecore Database or httpcontext, it would be more fair to  call them Integration tests. Not that you shouldn’t do integration test you SHOULD, but theese are more &#8220;heavy to run&#8221;. A unit is the smallest testable part of an application, and a unit test should not depend on the external things such as a database, file system or a like, and more they should run fast, and by a click of a button. I&#8217;ve recently read the book  Working Effectively with Legacy Code by Michael Feathers, and it got me thinking there got a be an alternative way to do unit testing with Sitecore.</div>
<div>Finally I’ve recently had a discussion with one of collegeues, the discussion was about how you could do unit test with Sitecore and what you would win by doing so. He claimed that test would be more complex then the code it test, and you wouldn’t gain anything from such tests. This inspired me to do some extensive testing. To prove him wrong I found some code he wrote for a Sitecore solution see below, the code is taken from a navigation component and finds the navigation title fom a item,  navigation title is only shown if the item if   &#8221;show in menu&#8221;  checkboxfield is checked. Keep in mind the that I picked this example because it is simple.</div>
<div><pre class="brush: csharp;">
public class NavigationTitleFactory
 {
 public static string Create(Item item)
 {
 bool showInNavigation = item.GetCheckBoxField(new ID(Constants.Fields.Navigation.Show));

if (!showInNavigation)
 {
 return string.Empty;
 }

string navigationTitle = item.GetStringField(new ID(Constants.Fields.Navigation.Title));

 if (string.IsNullOrEmpty(navigationTitle))
 navigationTitle = item.Name;

 return navigationTitle;
 }
 }

</pre></p>
</div>
<div>So the first problem that you meet is that a Sitecore Item is difficult  to mock or stub out for test, it would have been really nice if it had  inherit from a interface or had some virtual methods you could override in  a test implementation of with a mocking framwork.</div>
<div>But it turns out you can actually instantiate a Sitecore Item all  you have to do is passing in a lot of nulls “W.E.W.L.C by  M.Feather page 121” see the result below.</div>
<div><pre class="brush: csharp;">
public class TestItem : Item
 {
 public TestItem(FieldList fieldList,string itemName=&quot;dummy&quot;)
 : base(new ID(new Guid()), new ItemData(new ItemDefinition(new ID(new Guid()), itemName, new ID(new Guid()), new ID(new Guid())), Language.Invariant, new Sitecore.Data.Version(1), fieldList), new Database(&quot;web&quot;))
 {

}
 }
</pre></p>
</div>
<div> With this test item, writing test should now become a lot easier. The itemName is optional because offen you dont care about the name of your item, but for this show case we do.</div>
<div>If you like ,you could pass in addiational arguments to the test item like database name, language, or version. and would still work. The fieldlist arguments should contain the list of field values you gonna use in your test, the item fields can only be referenced with Sitecore id’s as you will see in the example below. Now back to code challenge from my colleague . I want to test the logic for the  navigation title factory liseted above. Here are the test cases.</div>
<div></div>
<div><strong><strong><br />
</strong></strong></div>
<div>
<ol>
<li>An Item with show in navigation not checked &#8211; it should return an empty string.</li>
<li>An item with show in navigation checked but no navigation titel should return the Name of the Item.</li>
<li>An item with show in navigation checked and with a navigation title, it should return the value of the navigation title.</li>
</ol>
<p>The test code i listed below should give 100% test coverage of the code.</p>
<p><pre class="brush: csharp;">
[TestFixture]
 public class NavigationTitleFactoryTest
 {
 [Test]
 public void CreateItemWithShowInMenuFalseShouldReturnEmptyString()
 {
 FieldList stubFieldList = new FieldList();
 stubFieldList.Add(new ID(Constants.Fields.Navigation.Show),&quot;0&quot;);
 stubFieldList.Add(new ID(Constants.Fields.Navigation.Title),&quot;NavigationTitle&quot;);
 Item stub = new TestItem(stubFieldList);

 string navigationTitle = NavigationTitleFactory.Create(stub);

 Assert.IsNullOrEmpty(navigationTitle);
 }

[Test]
 public void CreateItemWithShowInMenuTrueNoNavigationTitleShouldReturnItemName()
 {
 FieldList stubFieldList = new FieldList();
 stubFieldList.Add(new ID(Constants.Fields.Navigation.Show), &quot;1&quot;);
 stubFieldList.Add(new ID(Constants.Fields.Navigation.Title), &quot;&quot;);
 Item stub = new TestItem(stubFieldList,&quot;myItemName&quot;);
 string navigationTitle = NavigationTitleFactory.Create(stub);

Assert.AreEqual(&quot;myItemName&quot;, navigationTitle);
 }

[Test]
 public void CreateItemWithShowInMenuTrueShouldReturnItemNavigationTitle()
 {
 FieldList stubFieldList = new FieldList();
 stubFieldList.Add(new ID(Constants.Fields.Navigation.Show), &quot;1&quot;);
 stubFieldList.Add(new ID(Constants.Fields.Navigation.Title), &quot;NavigationTitle&quot;);
 Item stub = new TestItem(stubFieldList);
 string navigationTitle = NavigationTitleFactory.Create(stub);

Assert.AreEqual(&quot;NavigationTitle&quot;,navigationTitle);
 }
 }
</pre></p>
<div>This is  a simple example of how to do some unit testing with sitecore. Off course there are some problems with this approach you can&#8217;t access more complex attributes and functions of the Sitecore item, for example Children, path, and  functions in general that needs to communicate with Sitecore. But you can test more complex logic that are based in field values alone.</div>
<div>But what did we win with these tests, lets look at it this way. First of i saved time going in to Sitecore creating items setting field values and publishing, agreed it doesn&#8217;t take that long but with test like this i can repeat verification of my code by a click of a button. Also Should the Navigation Title Factory really care about which items it get from sitecore ie  the database  pr which context it runs in ? And it would even be pretty simple to add fallback from navigation title to another field value instead of item name and test this new functionality and ensure that the old functionality still works as excepted. And this is precisely what you want from a unit tests.With a unit test you it should be easy to change/modify ,refactor or add functionality to existing code and easily verify that you didn&#8217;t brake anything.</div>
<div></div>
<div></div>
<div>I wouldn&#8217;t test pure datacontainers, Items that only holds data to be shown. I would prefer to test these with integrationtest.</div>
<p>Allstair Deneys blog on unit testing with<br />
Sitecore using a custom test runnner <a href="http://adeneys.wordpress.com/2010/11/20/unit-testing-in-sitecore-is-not-scary/">can be found here</a>.How to change config files to work with Sitecore without a &#8220;context&#8221;<a href="http://www.experimentsincode.com/?p=343"> here</a>. By Mike Edwards</p>
</div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/167/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/167/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/167/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/167/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/167/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/167/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/167/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/167/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=167&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2012/02/07/unit-testing-with-sitecore-item/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Dropbox integration with Sitecore</title>
		<link>http://blog.istern.dk/2011/11/16/dropbox-integration-with-sitecore/</link>
		<comments>http://blog.istern.dk/2011/11/16/dropbox-integration-with-sitecore/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 09:31:19 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Sitecore 6]]></category>
		<category><![CDATA[Dropbox]]></category>
		<category><![CDATA[Sitecore]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=150</guid>
		<description><![CDATA[In this post I will make a simple integration from dropbox into the sitecore media library. This is an early release or more a sneak peak at what I hope in time will be a feature rich sitecore open source project/module  “Dropbox integration with Sitecore” With visioning and two sync, and any request that might [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=150&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div>In this post I will make a simple integration from dropbox into the sitecore media library. This is an early release or more a sneak peak at what I hope in time will be a feature rich sitecore open source project/module  “Dropbox integration with Sitecore” With visioning and two sync, and any request that might come in.<br />
So consider this an Alpha-release, I’ve used this Dropbox Context we build in the last blog post &#8220;<a title="Introduction to the dropbox api version 1.0" href="http://blog.istern.dk/2011/11/02/introduction-to-the-dropbox-api-version-1-0/">introduction to the dropbox api</a>&#8220;. I’ve changend it a little bit so I can be used to make a static .aspx file where you can build the accestoken file. The changend Dropbox context is shown below</div>
<div><pre class="brush: csharp;">
 public class DropboxContext
    {
        private OAuthToken _accessToken;

        private string _applicationKey;

        private string _applicationSecret;
        private string _accessTokenPath;

        private OAuthRestClient _apiRestClient;
        private OAuthRestClient _contentiRestClient;

        private string _version = &quot;1.0&quot;;

        public DropboxContext(DropBoxSettings settings)
        {
            _applicationKey = settings.ApplicationKey;
            _applicationSecret = settings.ApplicationSecret;
            _accessTokenPath = settings.AccessTokenPath;
            SetupApiRestClient();
            SetupContentRestClient();
        }

        private void SetupApiRestClient()
        {
            _apiRestClient = new OAuthRestClient(&quot;https://api.dropbox.com&quot;);
            _apiRestClient.ConsumerKey = _applicationKey;
            _apiRestClient.ConsumerSecret = _applicationSecret;
            _apiRestClient.Version = _version;
        }

        private void SetupContentRestClient()
        {
            _contentiRestClient = new OAuthRestClient(&quot;https://api-content.dropbox.com&quot;);
            _contentiRestClient.ConsumerKey = _applicationKey;
            _contentiRestClient.ConsumerSecret = _applicationSecret;
            _contentiRestClient.Version = _version;
        }

        public OAuthToken GetRequestToken()
        {

            return new OAuthToken(_apiRestClient.GetRequestToken(&quot;1/oauth/request_token&quot;));

        }

        public void AuthorizeToken(OAuthToken token)
        {
            Process.Start(&quot;https://www.dropbox.com/1/oauth/authorize?oauth_token=&quot; + token.Token);
        }

        public void SetAccesToken()
        {
            OAuthToken accesToken = GetAccesTokenFromStore();
            if (accesToken == null)
            {
                OAuthToken requestToken = GetRequestToken();
                AuthorizeToken(requestToken);
              //  accesToken = UpgradeRequsetTokenToAccesToken(requestToken);
            }

            _accessToken = accesToken;
        }

        public void UpgradeRequsetTokenToAccesToken(OAuthToken requestToken)
        {
            if (requestToken == null)
                return;

            string tokenString = _apiRestClient.GetAccesToken(&quot;1/oauth/access_token&quot;, requestToken);
            OAuthToken token = new OAuthToken(tokenString);
            StoreAccessToken(tokenString);

        }

        public void StoreAccessToken(string tokenString)
        {
            FileStream fs = File.Open(_accessTokenPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(tokenString);
            sw.Close();
            fs.Close();

        }

        private OAuthToken GetAccesTokenFromStore()
        {
            OAuthToken token = null;
            string tokenString = TokenStringFromFile();
            if (!string.IsNullOrEmpty(tokenString))
                token = new OAuthToken(tokenString);

            return token;
        }

        private string TokenStringFromFile()
        {
            FileStream fs = File.Open(_accessTokenPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamReader sw = new StreamReader(fs);

            string tokenString = sw.ReadToEnd();
            sw.Close();
            fs.Close();
            return tokenString;
        }

        public AccountInfo AccountInfo()
        {
            var response = _apiRestClient.QueryServer&lt;AccountInfo&gt;(&quot;1/account/info&quot;, GetAccesTokenFromStore());
            return response;
        }

        public FileEntry GetMetadata(string path)
        {
            string requestPath = &quot;1/metadata/dropbox&quot;;
            if (!String.IsNullOrEmpty(path))
                requestPath = String.Format(&quot;{0}{1}&quot;, requestPath, path.ToLower());
            var response = _apiRestClient.QueryServer&lt;FileEntry&gt;(requestPath, GetAccesTokenFromStore());
            return response;
        }

        public byte[] GetFile(string path)
        {
            var response = _contentiRestClient.GetStream(&quot;1/files/&quot; + path, GetAccesTokenFromStore());
            return response;
        }
    }
</pre></p>
</div>
<div>
<p>Since this i an early release I’ve build this simple .aspx page that provides the user with a link to allow acces to their dropbox and writes the accesToken to a flat file, the file can we then copy to the sitecore data folder for later use.</p>
<p><pre class="brush: xml;">
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head runat=&quot;server&quot;&gt;
    &lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
    &lt;div&gt;

    Token : &lt;%# Token.Token %&gt; &lt;br /&gt;
    Token Secret  &lt;%# Token.TokenSecret %&gt;&lt;br /&gt;

    &lt;a href=&quot;https://www.dropbox.com/1/oauth/authorize?oauth_token=&lt;%# Token.Token %&gt;&quot; target=&quot;_blank&quot;&gt;Autherize Dropbox&lt;/a&gt;

    &lt;asp:Button ID=&quot;Button2&quot; Text=&quot;Store Token&quot; runat=&quot;server&quot; onclick=&quot;Button2_Click&quot; /&gt;
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><br />
<pre class="brush: csharp;">
 public partial class AutherizeDropBox : System.Web.UI.Page
    {
        private OAuthToken token;
        private DropboxContext context;
        protected void Page_Load(object sender, EventArgs e)
        {
            context = new DropboxContext(SitecoreDropboxSettingsRepository.Get());

            if (!IsPostBack)
            {

                DataBind();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {

        }

        protected  OAuthToken Token
        {
            get
            {
                if (ViewState[&quot;token&quot;] != null)
                {
                    token = new OAuthToken();
                    token.Token = ViewState[&quot;token&quot;].ToString();
                    token.TokenSecret = ViewState[&quot;tokenSecret&quot;].ToString();
                }
                if (token == null)
                {
                    token = context.GetRequestToken();
                    ViewState[&quot;token&quot;] = token.Token;
                    ViewState[&quot;tokenSecret&quot;] = token.TokenSecret;
                }
                return token;
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {

                OAuthToken t = Token;
                context.UpgradeRequsetTokenToAccesToken(t);

        }
    }
</pre></p>
<p>For dropbox context to work we need a valid dropboxcontext setting datacontainer. Information for this i stored as settings in the web.config</p>
<p><pre class="brush: xml;">
   &lt;setting name=&quot;ApplicationKey&quot; value=&quot;YOURAPPLIKATIONKEY&quot; /&gt;
   &lt;setting name=&quot;ApplicationSecret&quot; value=&quot;YOURAPPLIKATIONSECRET&quot; /&gt;
   &lt;setting name=&quot;AccessTokenPath&quot; value=&quot;PATHTOYOUFILETHATCONTAINSACCESSTOKEN&quot; /&gt;
</pre></p>
<p>For this simple version of dropbox syncing I’ve build a simple sitecore task to run a “Download all service” from dropbox. It’s start by deleting all old the previously downloaded content from dropbox and the download from all content from dropbox root ie. “dropbox/”.</p>
<p><pre class="brush: csharp;">
public class DropboxDownloadTask
    {
        CreateMediaItemService _createMediaItemService;
        public void Execute()
        {
            _createMediaItemService = new CreateMediaItemService();
            GetRoot();
        }

        private void GetRoot()
        {
            MetatadataRepository metatadataRepository = new MetatadataRepository();
            FileEntry root = metatadataRepository.Get();
            IterateOverChildren(root);
        }

        private void  IterateOverChildren(FileEntry folderEntry)
        {

            foreach (FileEntry entry in folderEntry.Contents)
            {
                if (entry.Is_Dir)
                  IterateOverChildren(GetFileEntry(entry));
                else
                  _createMediaItemService.CreateMediaItem(entry);
            }
        }

        private FileEntry GetFileEntry(FileEntry entry)
        {
            MetatadataRepository metatadataRepository = new MetatadataRepository();
            return metatadataRepository.Get(entry);
        }
    }
</pre></p>
<p>The task uses some file- and metadata-repositories that communicate with dropboxcontext and a simple settings repository.</p>
<p><pre class="brush: csharp;">
 public static class SitecoreDropboxSettingsRepository
    {
        public static DropBoxSettings Get()
        {
            DropBoxSettings settings = new DropBoxSettings();
            settings.ApplicationKey = Settings.GetSetting(&quot;ApplicationKey&quot;);
            settings.ApplicationSecret = Settings.GetSetting(&quot;ApplicationSecret&quot;);
            string path = Settings.GetSetting(&quot;AccessTokenPath&quot;);
            settings.AccessTokenPath = HttpContext.Current.Server.MapPath(path);
            return settings;
        }

    }
</pre><br />
<pre class="brush: csharp;">
public class MetatadataRepository
    {
        private DropboxContext _context;
        public MetatadataRepository()
        {

            _context = new DropboxContext(SitecoreDropboxSettingsRepository.Get());
        }

        public FileEntry Get()
        {
            return _context.GetMetadata(String.Empty);
        }

        public FileEntry Get(FileEntry entry)
        {
          return _context.GetMetadata(entry.Path);
        }
    }
</pre></p>
<p><pre class="brush: csharp;">
 public class FileDataRepository
    {
        private  DropboxContext _context;
        public FileDataRepository()
        {

            _context = new DropboxContext(SitecoreDropboxSettingsRepository.Get());
        }

        public  byte[] Get(FileEntry entry)
        {
          return _context.GetFile(entry.Root+entry.Path);
        }
    }
</pre></p>
<p>Finally the task have a simple service that is responsible for adding a media stream to the sitecore media library.</p>
<p><pre class="brush: csharp;">
 public class CreateMediaItemService
    {

        private MediaCreator _creator;
        private MediaCreatorOptions _mediaOptions;

        public void CreateMediaItem(FileEntry folderName)
        {
                 using (new SecurityDisabler())
                          AddStreamToMediaLibrary(folderName);

        }

        private void AddStreamToMediaLibrary(FileEntry folderName)
        {
             if(folderName.Parent == &quot;dropbox&quot;)
                 SetMediaOptions(folderName.Parent, folderName.Name);
            else
                SetMediaOptions(String.Format(&quot;dropbox/{0}&quot;,folderName.Parent), folderName.Name);
            _creator = new MediaCreator();

            FileDataRepository fileDataRepository = new FileDataRepository();
            byte[] bytes = fileDataRepository.Get(folderName);

            MemoryStream theMemStream = new MemoryStream();

            theMemStream.Write(bytes, 0, bytes.Length);
            try
            {

                    _creator.CreateFromStream(theMemStream, folderName.Name, _mediaOptions);
            }
            catch (Exception e)
            {
                throw new Exception(folderName.Name, e);
            }
        }

        private void SetMediaOptions(string sitecorePath, string itemName)
        {
            _mediaOptions = new MediaCreatorOptions();
            _mediaOptions.FileBased = false;
            _mediaOptions.IncludeExtensionInItemName = false;
            _mediaOptions.KeepExisting = false;
            _mediaOptions.Versioned = false;
            _mediaOptions.Destination = String.Format(&quot;/sitecore/media library/{0}/{1}&quot;, sitecorePath, ItemUtil.ProposeValidItemName(itemName));
            _mediaOptions.Database = Database.GetDatabase(&quot;master&quot;);

        }

    }
</pre></p>
<p>Offcourse there are room for improvement and the code could use some cleaning up to is more “Clean Code” Uncle Bob.  You can download the source code for this project at Pentia. I&#8217;m more then interrested in hearing what features should be on the todo-list so let me know.</p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/150/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=150&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/11/16/dropbox-integration-with-sitecore/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Introduction to the dropbox api version 1.0</title>
		<link>http://blog.istern.dk/2011/11/02/introduction-to-the-dropbox-api-version-1-0/</link>
		<comments>http://blog.istern.dk/2011/11/02/introduction-to-the-dropbox-api-version-1-0/#comments</comments>
		<pubDate>Wed, 02 Nov 2011 13:16:03 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dropbox]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[Rest]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=138</guid>
		<description><![CDATA[In this post i will explore some of the basic functionality of the new Dropbox Api, you can read more about here https://www.dropbox.com/developers/reference/api. As you can see in the description you talk to dropbox using rest, and OAuth as authentication method. I could of course buil my own OAuth helper instead i will use this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=138&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post i will explore some of the basic functionality of the new Dropbox Api, you can read more about here <a href="https://www.dropbox.com/developers/reference/api">https://www.dropbox.com/developers/reference/api</a>. As you can see in the description you talk to dropbox using rest, and OAuth as authentication method. I could of course buil my own OAuth helper instead i will use this OAuth base utility found at <a href="https://www.dropbox.com/developers/reference/api">https://www.dropbox.com/developers/reference/api</a>  not that i that think it written as clean “clean code”  I like it does the job, but i will give some trouble writting clean crisp method of some of the classes in this post. As a restclient  I will use the client from  <a href="http://restsharp.org/">http://restsharp.org/</a>.<br />
Some of the code in this post is also done very naive with no error handling so of course if you want to use the code one should deffently address this issue.</p>
<p>Before you start coding anything you first need to go to dropbox and create an app<br />
<a href="https://www.dropbox.com/developers/apps">https://www.dropbox.com/developers/apps</a></p>
<p>The app key and app secret should be replaced where necessary  through out this post.</p>
<p>The authentication process at dropbox consist of three steps</p>
<ol>
<li>Get a request token</li>
<li>Authorize the request token from step 1</li>
<li>Upgrade the access token from step 1 to an Access token. The Access token should nt be stored and can be used in all future interaction with dropbox.</li>
</ol>
<p>First a Token from dropbox i delivered from a rest response in form given below</p>
<p>oauth_token_secret=b9q1n5il4lcc&amp;oauth_token=mh7an9dkrg59</p>
<p>So i made this simple yet  NOT VERY CLEAN CODE CLASS</p>
<p><pre class="brush: csharp;">
public class OAuthToken
    {
        public OAuthToken()
        {
        }

        public OAuthToken(string tokenString)
        {
            string[] urlParts = tokenString.Split('&amp;');
            string[] secretParts = urlParts[0].Split('=');
            string[] tokenParts = urlParts[1].Split('=');
            TokenSecret = secretParts[1];
            Token = tokenParts[1];
        }

        public string TokenSecret { get; set; }
        public string Token { get; set; }
    }
</pre></p>
<p>Most of the other restquest a response with Json and the restsharp can deserialize them in datacontainers.</p>
<p>Now with token class in place we can create the firs rest call to supply us with at instance of a request token.</p>
<p>We first need some dropbox OAuth settings stored in this datacontainer</p>
<p><pre class="brush: csharp;">
public class DropBoxSettings
    {
        public string ApplicationKey { get; set; }
        public string ApplicationSecret { get; set; }
        public string AccessTokenPath { get; set; }
    }
</pre></p>
<p>With this we can create a new OAuthrestClient</p>
<p><pre class="brush: csharp;">
public class OAuthRestClient
    {
        private OAuthBase _oAuth;
        private RestClient _restClient;

        public OAuthRestClient(string restHost)
        {
            _oAuth = new OAuthBase();
            _restClient = new RestClient(restHost);
        }

        public string GetRequestToken(string resource)
        {
            RestRequest request = AddOAuthParameters(resource);
            RestResponse response = _restClient.Execute(request);
            return response.Content;
        }

        public string GetAccesToken(string resource,OAuthToken token)
        {
            RestRequest request = AddOAuthParameters(resource,token);
            RestResponse response = _restClient.Execute(request);
            return response.Content;
        }

        public T QueryServer&lt;T&gt;(string resource, OAuthToken token) where T : new()
        {
            RestRequest request = AddOAuthParameters(resource, token);
            RestResponse&lt;T&gt; restResponse = _restClient.Execute&lt;T&gt;(request);
            return restResponse.Data;
        }

        public byte[] GetStream(string resource, OAuthToken token)
        {
            RestRequest request = AddOAuthParameters(resource, token,false);
            RestResponse restResponse = _restClient.Execute(request);
            return restResponse.RawBytes;
        }

        private RestRequest AddOAuthParameters(string resource, OAuthToken token=null,bool encodeSignatur=true)
        {
            RestRequest request = new RestRequest(Method.GET);
            string nonce = _oAuth.GenerateNonce();
            string timeStamp = _oAuth.GenerateTimeStamp();
            request.Resource = resource;

            request.AddParameter(&quot;oauth_consumer_key&quot;, ConsumerKey);
            request.AddParameter(&quot;oauth_nonce&quot;, nonce);
            request.AddParameter(&quot;oauth_signature_method&quot;, &quot;HMAC-SHA1&quot;);
            request.AddParameter(&quot;oauth_timestamp&quot;, timeStamp);
            if(token != null)
                request.AddParameter(&quot;oauth_token&quot;, token.Token);
            request.AddParameter(&quot;oauth_version&quot;, &quot;1.0&quot;);
            request.AddParameter(&quot;oauth_signature&quot;, BuildSignatureWithToken(resource, nonce, timeStamp, token, encodeSignatur));
            return request;
        }

        private string BuildSignatureWithToken(string resource, string nonce, string timeStamp, OAuthToken token,bool encodeSignature)
        {
            string normalizedUrl;
            string normalizedRequestParameters;
            string sig;
            if(token == null)
             sig = _oAuth.GenerateSignature(new Uri(string.Format(&quot;{0}/{1}&quot;, _restClient.BaseUrl, resource)), ConsumerKey, ConsumerSecret, &quot;&quot;, &quot;&quot;, &quot;GET&quot;, timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
            else
             sig = _oAuth.GenerateSignature(new Uri(string.Format(&quot;{0}/{1}&quot;, _restClient.BaseUrl,resource)),ConsumerKey, ConsumerSecret,token.Token, token.TokenSecret,&quot;GET&quot;, timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);

            if(encodeSignature)
                sig = HttpUtility.UrlEncode(sig);
            return sig;
        }

        public string Version { get; set; }
        public string ConsumerKey { get; set; }
        public string ConsumerSecret { get; set; }
    }
</pre></p>
<p>There are som input parameters that are bool which i due some restriction bugs in the OAuth base where a token not should be added in the requesttoken call. And the dropbox api where the signature shouldn’t be urlencode when querying api-content.dropbox.com. We can now use this to get a request token.</p>
<p><pre class="brush: csharp;">
  public OAuthToken GetRequestToken()
        {
            OAuthRestClient apiRestClient = new OAuthRestClient(&quot;https://api.dropbox.com&quot;);
            apiRestClient.ConsumerKey = YOUR APP KEY;
            apiRestClient.ConsumerSecret = YOUR APP SECRET;
            apiRestClient.Version = &quot;1.0&quot;;
            return new OAuthToken(_apiRestClient.GetRequestToken(&quot;1/oauth/request_token&quot;));
        }
</pre></p>
<p>Now with request token we can prompt the user for access to his or hers dropbox account this can for now only be done in a browser</p>
<p><pre class="brush: csharp;">
private void AuthorizeToken(OAuthToken token)
        {
            Process.Start(&quot;https://www.dropbox.com/1/oauth/authorize?oauth_token=&quot; + token.Token);
        }
</pre></p>
<p>Now with application authorized we ca upgrade the requesttoken to an accestoken, and store it in a secure place for now we store it as a string in a plaintext file.</p>
<p><pre class="brush: csharp;">
 private OAuthToken UpgradeRequsetTokenToAccesToken(OAuthToken requestToken)
        {
 OAuthRestClient apiRestClient = new OAuthRestClient(&quot;https://api.dropbox.com&quot;);
            apiRestClient.ConsumerKey = YOUR APP KEY;
            apiRestClient.ConsumerSecret = YOUR APP SECRET;
            apiRestClient.Version = &quot;1.0&quot;;
            string tokenString = apiRestClient.GetAccesToken(&quot;1/oauth/access_token&quot;, requestToken);
            OAuthToken token = new OAuthToken(tokenString);
            StoreAccessToken(tokenString);
            return token;
        }

        private void StoreAccessToken(string tokenString)
        {
            FileStream fs = File.Open(_accessTokenPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(tokenString );
            sw.Close();
            fs.Close();

        }

        private OAuthToken GetAccesTokenFromStore()
        {
            OAuthToken token = null;
            string tokenString = TokenStringFromFile();
            if(!string.IsNullOrEmpty(tokenString))
             token = new OAuthToken(tokenString);

            return token;
        }

        private string TokenStringFromFile()
        {
            FileStream fs = File.Open(_accessTokenPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            StreamReader sw = new StreamReader(fs);

            string tokenString =  sw.ReadToEnd();
            sw.Close();
            fs.Close();
            return tokenString;
        }
</pre></p>
<p>Now with an accestoken we can start talking to dropbox to the more fun stuff for example the userinformation</p>
<p><pre class="brush: csharp;">
public class AccountInfo
    {
        public string Uid { get; set; }
        public string Display_Name { get; set; }
        public string Country { get; set; }
        public QuotaInfo Quota_Info { get; set; }
    }
</pre><br />
<pre class="brush: csharp;">
 public class QuotaInfo
    {
        public string Shared { get; set; }
        public string Quota { get; set; }
        public string Normal { get; set; }
    }
</pre></p>
<p>or metadata for a a given path in the users dropbox</p>
<p><pre class="brush: csharp;">
 public class FileEntry
    {
        public string Size { get; set; }
        public string Rev { get; set; }
        public string Thumb_Exists { get; set; }
        public string Bytes { get; set; }
        public string Modified { get; set; }
        public string Path { get; set; }
        public bool Is_Dir { get; set; }
        public string Icon { get; set; }
        public string Root { get; set; }
        public string Mime_Type { get; set; }

        public string Revision { get; set; }
        public List&lt;FileEntry&gt; Contents { get; set; }

        public string Name
        {
            get
            {

                if (String.IsNullOrEmpty(Path)) return String.Empty;
                if (Path == &quot;/&quot;) return &quot;dropbox&quot;;
                    return Path.Substring(Path.LastIndexOf(&quot;/&quot;) + 1);
            }
        }

        public string Parent
        {
            get
            {
                if (String.IsNullOrEmpty(Path)) return String.Empty;
                if (Path.LastIndexOf(&quot;/&quot;) == 0) return &quot;dropbox&quot;;
                return Path.Substring(0,Path.LastIndexOf(&quot;/&quot;));

            }
        }

    }
</pre><br />
<pre class="brush: csharp;">
public AccountInfo AccountInfo()
        {
            OAuthRestClient apiRestClient = new OAuthRestClient(&quot;https://api.dropbox.com&quot;);
            apiRestClient.ConsumerKey = YOUR APP KEY;
            apiRestClient.ConsumerSecret = YOUR APP SECRET;
            apiRestClient.Version = &quot;1.0&quot;;
            var response = apiRestClient.QueryServer&lt;AccountInfo&gt;(&quot;1/account/info&quot;, YOUR ACCES TOKEN);
            return response;
        }&lt;/pre&gt;
&amp;nbsp;
&lt;pre&gt;</pre></p>
<p><span class="Apple-style-span" style="font-family:Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;font-size:13px;line-height:19px;white-space:normal;"><br />
</span><span class="Apple-style-span" style="font-family:Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;font-size:13px;line-height:19px;white-space:normal;">Now we could can the byte[]  for a dropbox entry if it is not a folder, note when calling the api-content.dropbox.com the SIGNATURE PASSED TO DROPBOX SHOULD NOT BE URL -ENCRYPTED why i have no clue</span></p>
<p><pre class="brush: csharp;">
public byte[] GetFile(string path)
        {
          OAuthRestClient apiRestClient = new OAuthRestClient(&quot;https://api-content.dropbox.com&quot;);
            apiRestClient.ConsumerKey = YOUR APP KEY;
            apiRestClient.ConsumerSecret = YOUR APP SECRET;
            apiRestClient.Version = &quot;1.0&quot;;
            var response = apiRestclient.GetStream(&quot;1/files/dropbox/&quot; + HttpUtility.UrlEncode(path), YOURRACCESTOKEN);
            return response;
        }
</pre></p>
<p>I’ve gathered all the functions in a simple Dropbox context.</p>
<p>So this wraps it up for now. in future post I will look into uploading files, but in the next post I will integrate this into the sitecore media library, for now only with download only and always overwrite. Coming soon so stay tuned.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/138/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=138&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/11/02/introduction-to-the-dropbox-api-version-1-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Running Scheduledtasks with the jobmanager in Sitecore</title>
		<link>http://blog.istern.dk/2011/10/06/running-scheduledtasks-with-the-jobmanager-in-sitecore/</link>
		<comments>http://blog.istern.dk/2011/10/06/running-scheduledtasks-with-the-jobmanager-in-sitecore/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 11:14:12 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Sitecore 6]]></category>
		<category><![CDATA[Sitecore]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=124</guid>
		<description><![CDATA[I&#8217;ve recently had the need to execute a scheduled task. The simple way would be to fetch the scheduled task item from Sitecore an instantiate it as a ScheduledItem type found in Sitecore kernel namespace, and the Call the execute method found in the class. This of course Will run the task in the context [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=124&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently had the need to execute a scheduled task. The simple way would be to fetch the scheduled task item from Sitecore an instantiate it as a ScheduledItem type found in Sitecore kernel namespace, and the Call the execute method found in the class.<br />
<pre class="brush: csharp;">

Item item = database.GetItem(taskId);
 ScheduleItem scheduleItem = new ScheduleItem(item);
 scheduleItem.Execute();

</pre></p>
<p>This of course Will run the task in the context of the current user. This could lead to some minor issues where the user running task doesn&#8217;t have the same rights as the Sitecore build JobManager.The solution is to execute the task via the JobManager, which also is used by scheduler. This is done by providing simple JobOptions. The example belows instantiate a new MyTask and runs the execute method.</p>
<p><pre class="brush: csharp;">
 JobOptions options = new JobOptions(&quot;Job Runner&quot;, &quot;schedule&quot;, &quot;scheduler&quot;, new MyTask(), &quot;Execute&quot;, new object[] { scheduleItem.Items,  scheduleItem.CommandItem, scheduleItem });
 options.SiteName = &quot;scheduler&quot;;
 JobManager.Start(options).WaitHandle.WaitOne();

</pre></p>
<p>The last parameter passed in as a new object is the parameter list passed on to the Execute Method.</p>
<p>&nbsp;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/124/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=124&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/10/06/running-scheduledtasks-with-the-jobmanager-in-sitecore/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Loosely couple ninject kernel in MVC applications</title>
		<link>http://blog.istern.dk/2011/07/27/lously-couple-ninject-kernel-in-mvc-applications/</link>
		<comments>http://blog.istern.dk/2011/07/27/lously-couple-ninject-kernel-in-mvc-applications/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 18:18:54 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[IOC]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=112</guid>
		<description><![CDATA[I&#8217;m currently working on a hobby project &#8220;a photosite&#8221;, where I&#8217;m using MVC 3 with Entity Framwork 4 and Ninject IOC container. Maybe I overdid the decoupling of the Ninject kernel for this project, but I was fun to do and I gave material for this post . The goal was to build a MVC [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=112&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on a hobby project &#8220;a photosite&#8221;, where I&#8217;m using MVC 3 with Entity Framwork 4 and Ninject IOC container. Maybe I overdid the decoupling of the Ninject kernel for this project, but I was fun to do and I gave material for this post <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . The goal was to build a MVC project where the repository implementation was placed in separate project together with ninject binding.</p>
<p>So here is the repository Interaface:</p>
<p><pre class="brush: csharp;">
public interface IGalleryRepository
{
   IEnumerable&lt;Gallery&gt; All { get; }
}

</pre></p>
<p>And here is the concrete implementation for the interface</p>
<p><pre class="brush: csharp;">
public class GalleryRepository : IGalleryRepository
{
   PhotoSiteContext context = new PhotoSiteContext();
   public IEnumerable&lt;Gallery&gt; All
   {
    get { return context.Galleries; }
   }
}
</pre></p>
<p>Now we need to alter the global.asax file with the following.</p>
<p><pre class="brush: csharp;">
public class MvcApplication : NinjectHttpApplication
{
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
   {
     filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;);
routes.MapRoute(
&quot;Default&quot;, // Route name
&quot;{controller}/{action}/{id}&quot;, // URL with parameters
new { controller = &quot;Gallery&quot;, action = &quot;Index&quot;, id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();

AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
      {
var kernel = new StandardKernel();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies());
return kernel;
}
}
</pre></p>
<p>By loading the kernel this way Ninject will looke through all dll&#8217;s in the bin folder of MVC project &#8220;main project&#8221; and load all assemblies which inherit from the NinjectModul class.</p>
<p>Now we cant in same project as the implementation of the inteface make a new class which derives from Ninject modul. The class should look like this.</p>
<p><pre class="brush: csharp;">
public class SqlCompactNinjectModule : NinjectModule
{
public override void Load()
{
Bind&lt;IGalleryRepository&gt;().To&lt;GalleryRepository&gt;();
}
}
</pre></p>
<div>With this setup it would be possible to switch the gallery implementation simply by adding a new dll with a NinjectModule and a concrete implementation of the IgalleriInterface.</div>
<div>I hope you find this usefull.</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/112/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=112&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/07/27/lously-couple-ninject-kernel-in-mvc-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple json deserialization in C#</title>
		<link>http://blog.istern.dk/2011/06/06/simple-json-deserialization-in-c/</link>
		<comments>http://blog.istern.dk/2011/06/06/simple-json-deserialization-in-c/#comments</comments>
		<pubDate>Mon, 06 Jun 2011 13:14:15 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://blog.istern.dk/?p=105</guid>
		<description><![CDATA[In This post a brieflyguid to how to deserialize Json encoded strings. Json is string that can be used t describe complex datastruces fx. C# class&#8217;. A simple Json string could look something like this. This corresponding C# class would look something like this      Now given the exaample Json string above we can [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=105&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In This post a brieflyguid to how to deserialize Json encoded strings. Json is string that can be used t describe complex datastruces fx. C# class&#8217;.</p>
<p>A simple Json string could look something like this.</p>
<p><pre class="brush: jscript;">

{&quot;TokenId&quot;:&quot;tokenid&quot;, &quot;TokenSecret&quot;:&quot;secretcode&quot;}

</pre></p>
<p>This corresponding C# class would look something like this</p>
<p><pre class="brush: csharp;">

public class Token
{
public string TokenId { get; set; }
public string TokenSecret { get; set; }
}
</pre></p>
<p><code>     Now given the exaample Json string above we can deserialize using .Net stand javascript deserialze, like this. The Javascriptserializer is placed in System.web.Serializationn.  </code></p>
<p><pre class="brush: csharp;">
   JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
Token deserializedToken = javaScriptSerializer.Deserialize&lt;Token&gt;(&quot;{\&quot;TokenId\&quot;:\&quot;tokenid\&quot;, \&quot;TokenSecret\&quot;:\&quot;secretcode\&quot;}&quot;);
</pre></p>
<p><code>The "deserializedToken" object have now been intialized and both properties "TokenId" and "TokenSecret" has been set to the value folloing the ":" int json string. you can also have more complex structure represented by using in the Json string "[]" you will then have etend your class to contain a list as the example below <code></code></code></p>
<p><pre class="brush: csharp;">

public class Token
{
public string TokenId { get; set; }
public string TokenSecret { get; set; }
public IEnumerable&lt;Token&gt; ChildTokens { get; set; }
}
</pre></p>
<p><code><code>So given the Json string</code></code></p>
<p><pre class="brush: jscript;">

&quot;{\&quot;TokenId\&quot;:\&quot;tokenid\&quot;, \&quot;TokenSecret\&quot;:\&quot;secretcode\&quot; ,\&quot;ChildTokens\&quot; : [{\&quot;TokenId\&quot;:\&quot;tokenid\&quot;, \&quot;TokenSecret\&quot;:\&quot;secretcode\&quot;}]}&quot;
</pre></p>
<p>Your deserialized token object will contain a list with one  ChildToken.</p>
<p>Serialization is left for another post.</p>
<p>I will use this Json deserialization in a feature blogpost  to communicate with a OAuth server.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/105/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/105/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/105/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=105&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/06/06/simple-json-deserialization-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>Bubble Sort algorithm developed with TDD. Code Kata.</title>
		<link>http://blog.istern.dk/2011/05/16/bubble-sort-algorithm-developed-with-tdd-code-kata/</link>
		<comments>http://blog.istern.dk/2011/05/16/bubble-sort-algorithm-developed-with-tdd-code-kata/#comments</comments>
		<pubDate>Mon, 16 May 2011 20:04:57 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Code Kata]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://istern.wordpress.com/?p=93</guid>
		<description><![CDATA[After I&#8217;ve been on a three day course with Uncle Bob in Copehangen, I got inspired by the code kata concept. And now want to do Kata from time to time to train coding. I&#8217;ve wanted to start with something simple so I chose to do a sort algorithm. I was trying to make a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=93&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>After I&#8217;ve been on a three day course with Uncle Bob in Copehangen, I got inspired by the code kata concept. And now want to do Kata from time to time to train coding.</p>
<p>I&#8217;ve wanted to start with something simple so I chose to do a sort algorithm. I was trying to make a video out of it, but got stuck with quicktime. Hoping to get it to work in the future. So for now you will have to settle with the testcases and code. I&#8217;m trying to use the guidelines from Clean Code so no comments will be in the code, functions and variable names should reveal their purpose.  How the code works should be visible from the Testcases.</p>
<p>Test cases.</p>
<p><pre class="brush: java;">

package Sort;

import junit.framework.Assert;
import org.junit.Test;

import java.util.Arrays;

public class SorterTest {
  @Test
  public void SortEmptyList_ShouldReturnEmptyList() {
    Assert.assertTrue(Arrays.equals(new int[]{},
                        Sorter.Sort(new int[]{})));
 }

 @Test
 public void SortListWithOneElement_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1},
                       Sorter.Sort(new int[]{1})));
 }

 @Test
 public void SortListWithTwoElementsInCorrectOrder_ShouldReturnSameList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2},
                       Sorter.Sort(new int[]{1, 2})));
 }

 @Test
 public void SortListWithTwoElementsInReverseOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2},
                       Sorter.Sort(new int[]{2, 1})));
 }

 @Test
 public void SortListWithSameTwoElementsr_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{2, 2},
                       Sorter.Sort(new int[]{2, 2})));
 }

 @Test
 public void SortListWithThreeElementsInCorrectOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{1, 2, 3})));
 }

 @Test
 public void SortListWithThreeElementsFirstTwoSwapped_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{2, 1, 3})));
 }

 @Test
 public void SortListWithThreeElementslastTwoSwapped_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{1, 3, 2})));
 }

 @Test
 public void SortListWithThreeElementslReverseOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3},
                       Sorter.Sort(new int[]{3, 2, 1})));
 }

 @Test
 public void SortListWithNElementaRandomOrder_ShouldReturnSortedList() {
   Assert.assertTrue(Arrays.equals(new int[]{1, 2, 3, 4, 5, 6, 6, 7, 8},
                       Sorter.Sort(new int[]{3, 2, 7, 6, 4, 8, 6, 1, 5})));
 }
}
</pre></p>
<p>And now to the refactored code.</p>
<p><pre class="brush: java;">

package Sort;

public class Sorter {
  public static int[] Sort(int[] unSortedList) {
    if (unSortedList.length &gt; 1)
      SortList(unSortedList);
    return unSortedList;
 }

 private static void SortList(int[] unSortedList) {
   int unsortedLength = unSortedList.length;
   while (unsortedLength &gt; 0) {
     PlacedLargestElementAtEndOfList(unSortedList);
     unsortedLength--;
   }
 }

 private static void PlacedLargestElementAtEndOfList(int[] unSortedList) {
   for (int j = 0; j &lt; i.length - 1; j++)
     SortElements(unSortedList, j);
 }

 private static void SortElements(int[] unSortedList, int j) {
   if (unSortedList[j] &gt; unSortedList[j + 1])
     SwapElements(unSortedList, j);
 }

 private static void SwapElements(int[] unSortedList, int j) {
   int backupelement = unSortedList[j];
   unSortedList[j] = unSortedList[j + 1];
   unSortedList[j + 1] = backupelement;
 }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/93/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=93&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/05/16/bubble-sort-algorithm-developed-with-tdd-code-kata/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
		<item>
		<title>CMS Friendly URL With MVC (Simple)</title>
		<link>http://blog.istern.dk/2011/05/04/cms-friendly-url-with-mvc-simple/</link>
		<comments>http://blog.istern.dk/2011/05/04/cms-friendly-url-with-mvc-simple/#comments</comments>
		<pubDate>Wed, 04 May 2011 19:33:27 +0000</pubDate>
		<dc:creator>istern</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://istern.wordpress.com/?p=90</guid>
		<description><![CDATA[I currently working on HUGE MVC project for a customer through Pentia. They are rebuilding their entire website from .Net webforms to MVC 3 with Razer. So one of the first task was to build som simpel functionality tha could resolve their url delivered from the underlying CMS.Instead of register specific routes for the different [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=90&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I currently working on HUGE MVC project for a customer through Pentia. They are rebuilding their entire website from .Net webforms to MVC 3 with Razer.</p>
<p>So one of the first task was to build som simpel functionality tha could resolve their url delivered from the underlying CMS.Instead of register specific routes for the different pagetypes in the CMS</p>
<p>I came up with this solution shown in this blogpost.</p>
<p>To begin with I registered a new &#8220;CMS route in global.asax&#8221;. All URL shoul hit this route, ofcourse you could make other routes before this.</p>
<p><pre class="brush: csharp;">

//RouteMap for CMS content
routes.MapRoute(&quot;CMSRoute&quot;, &quot;{*url*}&quot;).RouteHandler = new CmsRouteHandler();
</pre></p>
<p>Now to the simple CmsRouteHandler implementation it simply calls the CmsHttpHandler a relying on the handler to find a correct controller to desplaying the current request.</p>
<p><pre class="brush: csharp;">
public class CmsRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new CmsHttpHandler(requestContext);
}
}
</pre></p>
<p>Now the CMSHttpHandle which for this blogpost is simplyfied to always returning the<br />
frontpage. This should offcourse by matching the url to a page i DB and displaying the<br />
and resolve it to the correct controller.</p>
<p><pre class="brush: csharp;">

public class CmsHttpHandler : IHttpHandler
{
private RequestContext RequestContext { get; set; }
private IControllerFactory ControllerFactory { get; set; }
private IController Controller { get; set; }

public CmsHttpHandler(RequestContext requestContext)
{
RequestContext = requestContext;
}

public void ProcessRequest(HttpContext context)
{
HttpContext = context;
InstantiateControllerFactory();
InstantiateController();
SetupRequestContext();
Controller.Execute(RequestContext);
}

private HttpContext HttpContext { get; set; }

private void InstantiateControllerFactory()
{
ControllerFactory = ControllerBuilder.Current.GetControllerFactory();
}

private void InstantiateController()
{
Controller = ControllerFactory.CreateController(RequestContext, Pagetype);
}

private void SetupRequestContext()
{
RequestContext.RouteData.Values.Add(&quot;controller&quot;, Pagetype);
//Always render Index action, all pagetype controllers must implement Index action
RequestContext.RouteData.Values.Add(&quot;action&quot;, &quot;Index&quot;);

AppendQueryStrings();
}

private void AppendQueryStrings()
{
foreach (string name in HttpContext.Request.QueryString)
RequestContext.RouteData.Values.Add(name, HttpContext.Request.QueryString[name]);
}

private static string ResolvePagetypeFromUrl()
{


//Should return apgetype from db/URL
return Pagetype


}

private string _pageType;
private string Pagetype
{
get
{
//Resolve pagetype from DB fx
//For now we will just return the frontpage
/return string should match controller name
return &quot;frontpage&quot;;
}
}

public bool IsReusable
{
get
{
throw new NotImplementedException();
}
}
}
</pre></p>
<p>Hope you find it usefull..</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/istern.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/istern.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/istern.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/istern.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/istern.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/istern.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/istern.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/istern.wordpress.com/90/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.istern.dk&#038;blog=23042455&#038;post=90&#038;subd=istern&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.istern.dk/2011/05/04/cms-friendly-url-with-mvc-simple/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/026d17604808c43894d221651a47369f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">istern</media:title>
		</media:content>
	</item>
	</channel>
</rss>
