<?xml version="1.0" encoding="utf-8"?>
<feed xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xml:lang="en-us" xmlns="http://www.w3.org/2005/Atom">
  <title>satoricode</title>
  <link rel="alternate" type="text/html" href="http://satoricode.net/" />
  <link rel="self" href="http://satoricode.net/SyndicationService.asmx/GetAtom" />
  <icon>favicon.ico</icon>
  <updated>2012-03-08T14:18:20.0614967+01:00</updated>
  <author>
    <name>Marc-Anton Flohr</name>
  </author>
  <subtitle />
  <id>http://satoricode.net/</id>
  <generator uri="http://dasblog.info/" version="2.3.9074.18820">DasBlog</generator>
  <entry>
    <title>Encrypted SQL CE Database in Windows Phone 7</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2012/03/08/EncryptedSQLCEDatabaseInWindowsPhone7.aspx" />
    <id>http://satoricode.net/PermaLink,guid,7c0aca99-48fc-4f85-ab60-352bd543c7dc.aspx</id>
    <published>2012-03-08T13:30:48.5312125+01:00</published>
    <updated>2012-03-08T14:18:20.0614967+01:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="LINQ" label="LINQ" scheme="http://satoricode.net/CategoryView,category,LINQ.aspx" />
    <category term="Windows Phone 7" label="Windows Phone 7" scheme="http://satoricode.net/CategoryView,category,WindowsPhone7.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Porting my new Android game <a href="https://play.google.com/store/apps/details?id=ngry.QuizBurner" target="_blank">QuizBurner</a> to
Windows Phone 7.1 (Mango) was really fun. Microsoft created a clean and .NET _friendly_
environment and makes it easy for .NET developers to get some things done. I can’t
bring myself to call it “.NET”, because it has too many incompatibilities - it’s more
a simplified and in few ways modified copy of the .NET Framework.
</p>
        <img style="float: right; margin-left: 15px" title="Windows Phone 7 LINQ to SQL" border="0" alt="Dependency" src="http://satoricode.net/content/images/EncryptedSQLCEDatabaseForWindowsPhone7/WindowsPhone7LINQToSQL.png" />
        <h2>Access existing Database
</h2>
        <p>
Shipping existing databases within the the application is an essential prerequisite
for my game. We are able to store the database side by side to the assembly, by using
the “appdata” keyword instead of the “isostore” within the connection string.
</p>
        <div style="width: 450px; float: left">
          <pre class="brush: plain">Data Source = 'appdata:/db.sdf'; File Mode = read only;</pre>
        </div>
        <div style="clear: left;">
        </div>
        <p>
Please mention that we only have read only access to that database, so we should also
specify the “read only” parameter.
</p>
        <h2>Database Encryption
</h2>
        <p>
So far so good – assuming that we are able to encrypt CE databases very easily, we
just have to specify a password here too:
</p>
        <pre class="brush: plain">Data Source = 'appdata:/db.sdf'; File Mode = read only; Password = 'oni7sak2';</pre>
        <p>
Since it couldn't have been that easy, we are receiving the following exception:
</p>
        <pre class="brush: plain">The database encryption mode is invalid.  [ Input Encryption Mode = 0 ]</pre>
        <p>
I did some research and found out that the default encryption method in 3.5 is AES128/SHA1
and the default encryption method in 4.0 is AES128/SHA2. 
</p>
        <p>
List of default encryption algorithms used in SQL Compact:
</p>
        <pre class="brush: plain"> .---------------------------------------------------------------------------------.
| Version | Default Encryption | Authentication | Provider                         |
|---------+--------------------+----------------+----------------------------------|
| 3.0     | RC4                | MD5            | PROV_RSA_FULL, MS_ENHANCED_PROV  |
| 3.1     | RC4                | MD5            | PROV_RSA_FULL, MS_ENHANCED_PROV  |
| 3.5     | AES128             | SHA1           | PROV_RSA_AES, MS_ENH_RSA_AES_PRO |
| 4.0     | AES128             | SHA2           | ?                                |
`----------------------------------------------------------------------------------'</pre>
        <p>
Further research showed me that WP7 is based on 3.5 and uses some features of 4.0,
also the encryption methods. It looks like it’s a mixture of both versions.
</p>
        <h2>Conclusion
</h2>
        <p>
That led me to the following conclusion:
</p>
        <p>
Encrypted databases created in Microsoft SQL Server Management Studio (2008) are not
compatible with WP7 and created Databases by WP7 are not compatible with the SSMS.
It appears that the encrypted database created using Mango WPDT can not be opened
in desktop (either using Visual Studio 2010 or SQL Server 2008 Management Studio).
Both VS2010 and SQL Server 2008 MS shows an encryption mode is invalid when trying
to open it.
</p>
        <p>
          <b>There is no (supported) way to use encrypted SQL CE databases in WP7 if they are
not created by WP7 itself.</b>
        </p>
        <p>
Microsoft declines support to that approach by using the following statements:
</p>
        <ul>
          <li>
SQLCE is not directly exposed to 3rd party applications in Windows Phone 7 and beyond.
Microsoft exposes LINQ To SQL, which happens to use SQLCE as the underlying storage
provider in Windows Phone Mango (7.1). 
</li>
          <li>
Previous knowledge of how SQLCE worked in one of its many previous incarnations will
not help much in WP7 app development, as the build on Windows Phone is slightly different
than other flavors. 
</li>
          <li>
Microsoft does not support loading a database which was created on SQLCE for desktop
or any previous version of Windows CE. 
</li>
          <li>
Microsoft does allow the developer to specify a password on the database through LINQ
To SQL. 
</li>
          <li>
Microsoft does not allow you to specify the encryption settings on the LINQ To SQL
connection string. 
</li>
        </ul>
        <p>
Source: <a href="http://forums.create.msdn.com/forums/t/95939.aspx" target="_blank">http://forums.create.msdn.com/forums/t/95939.aspx</a></p>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=7c0aca99-48fc-4f85-ab60-352bd543c7dc" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Advanced Proxy-Classes for Razor-Templating by using DynamicObject</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2012/01/13/AdvancedProxyClassesForRazorTemplatingByUsingDynamicObject.aspx" />
    <id>http://satoricode.net/PermaLink,guid,c51e179c-660d-432e-a428-34b1bc72baab.aspx</id>
    <published>2012-01-13T17:24:12.8934688+01:00</published>
    <updated>2012-01-13T17:24:12.8934688+01:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="C#" label="C#" scheme="http://satoricode.net/CategoryView,category,C.aspx" />
    <category term="MVC" label="MVC" scheme="http://satoricode.net/CategoryView,category,MVC.aspx" />
    <category term="MVVM" label="MVVM" scheme="http://satoricode.net/CategoryView,category,MVVM.aspx" />
    <category term="OOP" label="OOP" scheme="http://satoricode.net/CategoryView,category,OOP.aspx" />
    <category term="Razor" label="Razor" scheme="http://satoricode.net/CategoryView,category,Razor.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
As described in my earlier post <a href="http://satoricode.net/2011/10/03/CreatingProxyClassesForViewModelsMVVMByUsingDynamicObject.aspx">Creating
Proxy-Classes for ViewModel’s (MVVM) by using DynamicObject</a> with <strong>DynamicObject</strong>’s
you have the ability to easily extend and override members of you DomainModel for
binding purposes without changing it in any way. You can use that approach in ASP.NET
MVC to write easy readable templates, without creating <a href="http://blogs.msdn.com/b/pietrobr/archive/2010/12/21/creating-a-razor-helper-for-inline-content-embedding.aspx" target="_blank">@helper</a>’s
for ViewModel related data manipulation.
</p>
        <h2>Domain Model
</h2>
        <p>
Let me explain that approach by a simple example. Assuming that we have to build a
catalog system based on an existing DomainModel where we have some <strong>Article</strong>s,
n corresponding <strong>Price</strong>s and due to normalization corresponding price <strong>PriceCampaign</strong>s
to label and specify the <strong>Price</strong>s.
</p>
        <center>
          <img border="0" alt="DomainModel" src="http://satoricode.net/content/images/AdvancedProxy-ClassesForRazorDynamicObject/DomainModel.png" />
        </center>
        <h2>Creating some Objects
</h2>
        <p>
Let's use the following mocking for our examples:
</p>
        <pre class="brush: c-sharp">var listPriceCampaign = new PriceCampaign() { Name = "list" };
var retailPriceCampaign = new PriceCampaign() { Name = "retail" };

var article = new Article() { OrderNumber = "4202.9", Description = "Doomsday Machine" };

var listPrice = new Price() { Value = 99.99m, Article = article, Campaign = listPriceCampaign };

article.Prices.Add(listPrice);
listPriceCampaign.Prices.Add(listPrice);

var retailPrice = new Price() { Value = 17.99m, Article = article, Campaign = retailPriceCampaign };

article.Prices.Add(retailPrice);
retailPriceCampaign.Prices.Add(retailPrice);
</pre>
        <h2>Template Usage
</h2>
        <p>
We are now able to produce the following output by using our DomainModel:
</p>
        <pre class="brush: plain">OrderNumber: 4202.9
Description: Doomsday Machine
Price: $17.99
ListPrice: $99.99</pre>
        <p>
To map the prices to the Razor template we can do it either the old fashioned way:
</p>
        <pre class="brush: c-sharp">@{
  // bad code for determining list- and retail price
  var listPrice = 0.00m;
  var retailPrice = 0.00m;

  foreach(var price in Model.Prices)
  {
    if (price.Campaign.Name == "list")
      listPrice = price.Value;
    else if (price.Campaign.Name == "retail")
      retailPrice = price.Value;
  }
}
OrderNumber: @Model.OrderNumber
Description: @Model.Description
Price: $@retailPrice
ListPrice: $@listPrice</pre>
        <p>
Or we can do it by using LINQ:
</p>
        <pre class="brush: c-sharp">@{ // good code (still bad approach) for determining list- and retail price }
OrderNumber: @Model.OrderNumber
Description: @Model.Description
Price: $@Model.Prices.Where(p =&gt; p.Campaign.Name == "retail").First().Value
ListPrice: $@Model.Prices.Where(p =&gt; p.Campaign.Name == "list").First().Value</pre>
        <h2>ViewModel-Proxy
</h2>
        <p>
Now let’s create the simplified ViewModel-Proxy by using <strong>DynamicObject</strong> as
described in <a href="http://satoricode.net/2011/10/03/CreatingProxyClassesForViewModelsMVVMByUsingDynamicObject.aspx">Creating
Proxy-Classes for ViewModel’s (MVVM) by using DynamicObject</a>.
</p>
        <pre class="brush: c-sharp">public abstract class BaseViewModelProxy&lt;T&gt; : DynamicObject
{
  protected T _domainModel;

  private PropertyInfo[] _objectProperties;
  private PropertyInfo[] objectProperties
  {
    get
    {
      if (objectProperties == null)
        this._objectProperties = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

      return this._objectProperties;
    }
  }

  public BaseViewModelProxy(T domainModel)
  {
    this._domainModel = domainModel;
  }

  public override bool TryGetMember(GetMemberBinder binder, out object result)
  {
    var pi = this._objectProperties.FirstOrDefault((p) =&gt; p.Name == binder.Name);

    if (pi != null)
    {
      result = this._domainModel != null ? pi.GetValue(this._domainModel, null) : null;
      return true;
    }
    else
      return base.TryGetMember(binder, out result);
  }

  public override bool TrySetMember(SetMemberBinder binder, object value)
  {
    var pi = this._objectProperties.FirstOrDefault((p) =&gt; p.Name == binder.Name);

    if (pi != null)
    {
      if (this._domainModel != null)
      pi.SetValue(this._domainModel, value, null);
    
      return true;
    }
    else
      return base.TrySetMember(binder, value);
  }
}</pre>
        <p>
We also create a <strong>BaseCollectionDictionaryModel&lt;T&gt;</strong> and <strong>BaseModelCollectionDictionaryModel&lt;T,
E&gt;</strong> that implements <strong>IDictionary&lt;string, T&gt;</strong> so we
are able access collection items by associative indices for collection items in our
template.
</p>
        <pre class="brush: c-sharp">public abstract class BaseCollectionDictionaryModel&lt;T&gt; : DynamicObject, IDictionary&lt;string, T&gt;, IList&lt;T&gt;
{
  private IList&lt;T&gt; _domainModelCollection;
  private List&lt;PropertyInfo&gt; _keyFieldPropertyInfoStack;

  public BaseCollectionDictionaryModel(IList&lt;T&gt; domainModelCollection, string keyFieldPath)
  {
  this._domainModelCollection = domainModelCollection;

  this._keyFieldPropertyInfoStack = new List&lt;PropertyInfo&gt;();

  buildPropertyInfoStack(keyFieldPath, typeof(T));
  }

  private void buildPropertyInfoStack(string path, Type type)
  {
  var stack = path.Split(new char[] { '.' });

  var pi = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(p =&gt; p.Name == stack[0]);

  this._keyFieldPropertyInfoStack.Add(pi);

  if (stack.Length &gt; 1)
    buildPropertyInfoStack(path.Substring(stack[0].Length + 1), pi.PropertyType);
  }

  public T this[string key]
  {
  get
  {
    // we could also use LINQ Dynamic Expressions instead
    foreach (T o in this._domainModelCollection)
    {
    Object r = o;

    foreach (PropertyInfo pi in this._keyFieldPropertyInfoStack)
      r = pi.GetValue(r, null);

    if ((string)r == key)
      return o;
    }

    throw new KeyNotFoundException();
  }
  set { throw new NotImplementedException(); }
  }

  // insert some more IDictionary&lt;string, T&gt;, IList&lt;T&gt; implementations here
}

public abstract class BaseModelCollectionDictionaryModel&lt;T, E&gt; : BaseCollectionDictionaryModel&lt;E&gt;, IDictionary&lt;string, T&gt;, IList&lt;T&gt;
{
  public BaseModelCollectionDictionaryModel(IList&lt;E&gt; domainModelCollection, string keyFieldPath)
  : base(domainModelCollection, keyFieldPath)
  {
  }

  public virtual List&lt;T&gt; getModelCollection(IEnumerable&lt;E&gt; items)
  {
  throw new NotImplementedException();
  }

  public virtual T getModel(E item)
  {
  throw new NotImplementedException();
  }

  public ICollection&lt;string&gt; Keys
  {
  get { return base.Keys; }
  }

  public ICollection&lt;T&gt; Values
  {
  get { return getModelCollection(base.Values); }
  }

  public T this[string key]
  {
  get { return getModel(base[key]); }
  set { throw new NotImplementedException(); }
  }

  // insert some more IDictionary&lt;string, T&gt;, IList&lt;T&gt; implementations here
}</pre>
        <p>
Now to the simple part, the implementation. We've to create some ViewModel classes
based on our abstract class <strong>BaseViewModelProxy&lt;T&gt;</strong>. We also
"override" the collection properties so we can use them as <strong>IDictionary&lt;string,
T&gt;</strong> in our template, they will also return our proxified types.
</p>
        <pre class="brush: c-sharp">public class ArticleModel : BaseViewModelProxy&lt;Article&gt;
{
  public ArticleModel(Article article)
  : base(article)
  {
  }

  public PriceModelCollectionDictionaryModel Prices
  {
  get { return new PriceModelCollectionDictionaryModel(this._domainModel.Prices); }
  }
}

public class PriceModel : BaseViewModelProxy&lt;Price&gt;
{
  public PriceModel(Price price)
  : base(price)
  {
  }

  public ArticleModel Article
  {
  get { return new ArticleModel(this._domainModel.Article); }
  }

  public PriceCampaignModel Campaign
  {
  get { return new PriceCampaignModel(this._domainModel.Campaign); }
  }
}

public class PriceCampaignModel : BaseViewModelProxy&lt;PriceCampaign&gt;
{
  public PriceCampaignModel(PriceCampaign priceCampaign)
  : base(priceCampaign)
  {
  }

  public PriceModelCollectionDictionaryModel Prices
  {
  get { return new PriceModelCollectionDictionaryModel(this._domainModel.Prices); }
  }
}

public class PriceModelCollectionDictionaryModel : BaseModelCollectionDictionaryModel&lt;PriceModel, Price&gt;
{
  public PriceModelCollectionDictionaryModel(IList&lt;Price&gt; prices)
  : base(prices, "Campaign.Name")
  {
  }
}

public class PriceCampaignModelCollectionDictionaryModel : BaseModelCollectionDictionaryModel&lt;PriceCampaignModel, PriceCampaign&gt;
{
  public PriceCampaignModelCollectionDictionaryModel(IList&lt;PriceCampaign&gt; priceCampaigns)
  : base(priceCampaigns, "Name")
  {
  }
}</pre>
        <h2>New Template Usage
</h2>
        <p>
The new template usage is much more simpler and that's how all the hard work pays
out:
</p>
        <pre class="brush: c-sharp">OrderNumber: @Model.OrderNumber
Description: @Model.Description
Price: $@Model.Prices["retail"].Value
ListPrice: $@Model.Prices["list"].Value</pre>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=c51e179c-660d-432e-a428-34b1bc72baab" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Creating a Generic 32bit Wrapper Application</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/11/28/CreatingAGeneric32bitWrapperApplication.aspx" />
    <id>http://satoricode.net/PermaLink,guid,8d585ec9-2e4e-40ed-b559-cb9a5999d114.aspx</id>
    <published>2011-11-28T13:12:35.90625+01:00</published>
    <updated>2011-11-28T13:17:27.734375+01:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="C#" label="C#" scheme="http://satoricode.net/CategoryView,category,C.aspx" />
    <category term="Snippets" label="Snippets" scheme="http://satoricode.net/CategoryView,category,Snippets.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <a style="float: right; margin-left: 15px" class="imagebox" title="Visual Studio Platform Target Settings" href="/content/images/Generic32bitWrapperApplication/VisualStudioPlatformTargetSettings.png">
          <img border="0" alt="Visual Studio Platform Target Settings" src="/content/images/Generic32bitWrapperApplication/VisualStudioPlatformTargetSettings.png" width="250" />
        </a>
        <p>
A couple of days ago I was asked if there is a way to interop with a native 32bit
library from within an 64bit .NET application. Since the bitness is defined at process
level and in .NET the bitness of the starting project determines the bitness of the
process, there is only one way to achieve that: you have to spawn a new process, a
32bit process.
</p>
        <p>
The following example of a generic 32bit wrapper application demonstrates how to execute
managed code in a simple manner. The wrapper, targeting the x86 platform, is able
to execute the specified static method "Main" of the given assembly. The assembly
doesn't have to be an executing assembly itself.
</p>
        <pre class="brush: c-sharp">// usage: RunAs32Bit.exe [ASSEMBLY] [ARGS ...]
static void Main(string[] args)
{
  var assembly = Assembly.LoadFile(Path.GetFullPath(args[0]));
  var type = assembly.GetTypes().FirstOrDefault(t =&gt; t.GetMethod("Main") != null);
  var member = type.GetMethod("Main");
  var arguments = args.Where((v, i) =&gt; i &gt; 0).ToArray();

  member.Invoke(type, new object[] { arguments });
}</pre>
        <p>
Spawning a new process that will do some stuff (e.g. interop) may also mean that you
have to do some inter-process communication (IPC). I suggest you to use WCF for that
approach.
</p>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=8d585ec9-2e4e-40ed-b559-cb9a5999d114" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Saving Clicks by replacing Radio Buttons</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/10/18/SavingClicksByReplacingRadioButtons.aspx" />
    <id>http://satoricode.net/PermaLink,guid,aa40b79c-7e41-490e-87a8-a4c859caa294.aspx</id>
    <published>2011-10-19T01:18:13.763+02:00</published>
    <updated>2011-10-19T02:22:06.0196562+02:00</updated>
    <category term="UX" label="UX" scheme="http://satoricode.net/CategoryView,category,UX.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
There are many cases where radio buttons are really useful, but they are also often
misused.
</p>
        <a style="float: right; margin-left: 15px" class="imagebox" title="I'm in space. SPAAACE!" href="http://satoricode.net/content/images/RadioButtons/spaaace.png">
          <img border="0" alt="I'm in space. SPAAACE!" src="http://satoricode.net/content/images/RadioButtons/spaaace.png" width="250" />
        </a>
        <p>
And there are many ways to fail with them. Good placement of radio buttons is very
important to make absolutely clear which radio buttons belong to a group. Therefore
they shouldn't be placed too far from each other and a spacing to other controls and
especially other radio button groups is the key. If you’ve ever seen some radio button
floating incoherent in space, or wrongly grouped ones, you know what I'm talking about.
</p>
        <div style="clear: both">
        </div>
        <p>
Another popular bad usage of radio buttons is when they provoke unnecessary clicks
like in this example when configuring the Server Group Properties of the Microsoft
Team Foundation Server 2010:
</p>
        <center>
          <a class="imagebox" title="Team Foundation Server &quot;Group Properties&quot;" href="http://satoricode.net/content/images/RadioButtons/TeamFoundationServerGroupProperties.png">
            <img border="0" alt="Team Foundation Server &quot;Group Properties&quot;" src="http://satoricode.net/content/images/RadioButtons/TeamFoundationServerGroupProperties.png" width="400" />
          </a>
        </center>
        <p>
Seriously, did you intuitively figured out how the radio buttons behave here?
</p>
        <p>
Another well known example for this is the dialog in Excel when you’re about to delete
some cells:
</p>
        <center>
          <a class="imagebox" title="Excel &quot;Delete&quot; dialog" href="http://satoricode.net/content/images/RadioButtons/ExcelDeleteDialog.png">
            <img border="0" alt="Excel &quot;Delete&quot; dialog" src="http://satoricode.net/content/images/RadioButtons/ExcelDeleteDialog.png" />
          </a>
        </center>
        <p>
In many cases it would be better to drop some action buttons to avoid some extra clicks.
</p>
        <p>
When you open an Office Document in Microsoft SharePoint 2010 you will get the following
dialog:
</p>
        <center>
          <a class="imagebox" title="SharePoint 2010 &quot;Open Document&quot; dialog" href="http://satoricode.net/content/images/RadioButtons/SharePointOpenDocumentDialog.png">
            <img border="0" alt="SharePoint 2010 &quot;Open Document&quot; dialog" src="http://satoricode.net/content/images/RadioButtons/SharePointOpenDocumentDialog.png" />
          </a>
        </center>
        <p>
The preferred design would look like:
</p>
        <center>
          <a class="imagebox" title="Preferred SharePoint 2010 &quot;Open Document&quot; dialog" href="http://satoricode.net/content/images/RadioButtons/PreferredSharePointOpenDocumentDialog.png">
            <img border="0" alt="Preferred SharePoint 2010 &quot;Open Document&quot; dialog" src="http://satoricode.net/content/images/RadioButtons/PreferredSharePointOpenDocumentDialog.png" />
          </a>
        </center>
        <p>
Another example of this would be the "Paste Special" dialog from the Windows Live
Writer:
</p>
        <center>
          <a class="imagebox" title="Windows Live Writer &quot;Paste Special&quot; dialog" href="http://satoricode.net/content/images/RadioButtons/LiveWriterPasteSpecialDialog.png">
            <img border="0" alt="Windows Live Writer &quot;Paste Special&quot; dialog" src="http://satoricode.net/content/images/RadioButtons/LiveWriterPasteSpecialDialog.png" width="400" />
          </a>
        </center>
        <p>
That could look like:
</p>
        <center>
          <a class="imagebox" title="Preferred Windows Live Writer &quot;Paste Special&quot; dialog" href="http://satoricode.net/content/images/RadioButtons/PreferredLiveWriterPasteSpecialDialog.png">
            <img border="0" alt="Preferred Windows Live Writer &quot;Paste Special&quot; dialog" src="http://satoricode.net/content/images/RadioButtons/PreferredLiveWriterPasteSpecialDialog.png" width="300" />
          </a>
        </center>
        <p>
Saving clicks is a especially a common task when it comes to touchscreen optimized
interfaces. There are already many examples how that can be achieved:
</p>
        <center>
          <a class="imagebox" title="Windows 7 &quot;Copy File&quot; dialog" href="http://satoricode.net/content/images/RadioButtons/Windows7CopyFileDialog.png">
            <img border="0" alt="Windows 7 &quot;Copy File&quot; dialog" src="http://satoricode.net/content/images/RadioButtons/Windows7CopyFileDialog.png" height="300" />
          </a>
          <a style="margin-left: 15px" class="imagebox" title="Android radio button submenu" href="http://satoricode.net/content/images/RadioButtons/AndroidRadioButtonSubMenu.png">
            <img border="0" alt="Android radio button submenu" src="http://satoricode.net/content/images/RadioButtons/AndroidRadioButtonSubMenu.png" height="300" />
          </a>
        </center>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=aa40b79c-7e41-490e-87a8-a4c859caa294" />
      </div>
    </content>
  </entry>
  <entry>
    <title>High speed Android "emulation" using VirtualBox with Android-x86</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/10/16/HighSpeedAndroidEmulationUsingVirtualBoxWithAndroidx86.aspx" />
    <id>http://satoricode.net/PermaLink,guid,588e5cea-f457-4e83-be4e-18f537e01bef.aspx</id>
    <published>2011-10-16T04:44:35.458+02:00</published>
    <updated>2012-01-22T14:55:33.4835+01:00</updated>
    <category term="Android" label="Android" scheme="http://satoricode.net/CategoryView,category,Android.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Ever tried to speed up the Android-Emulator? You can tweak the emulator by using a
snapshots to increase the booting performance of the emulator and apply some nasty
registry hacks to tweak the speed at runtime. However, applying all of those tweaks
improve the performance insignificant. Developing and especially debugging android
applications with the emulator provided by the SDK is pain in the ass.
</p>
        <h2>The Android-x86 Project
</h2>
        <p>
There is a solution to increase the debugging performance dramatically. Instead of
running an emulator that emulates a real ARM processor with a lot of overhead, there
is the <a href="http://www.android-x86.org" target="_blank">Android-x86</a> project.
It’s an open source project, that provides the ability to run Android directly on
top of your x86 CPU.
</p>
        <p>
You can run Android-x86 on most popular Virtual Machines like <a href="http://www.vmware.com" target="_blank">VMWare</a>, <a href="http://wiki.qemu.org" target="_blank">QEmu</a> and <a href="http://www.virtualbox.org/" target="_blank">VirtualBox</a>.
I successfully tried to run it on all of those 3 Virtual Machines and I recommend
VirtualBox for this approach, since it’s free and doesn’t need any special configurations
to run smooth and very very fast.
</p>
        <h2>Setting up Android-x86 with VirtualBox
</h2>
        <p>
At the first step we need the installation image of Android-x86. I used the the android-x86-2.3-RC1-eeepc.iso
that can be downloaded here: <a href="http://www.android-x86.org/download">http://www.android-x86.org/download</a>.
</p>
        <p>
Let’s create a Virtual Machine that will be able to run this image. I used the following
setup for my machine:
</p>
        <a style="float: right" class="imagebox" title="VirtualBox Settings" href="http://satoricode.net/content/images/Android-x86/VirtualBoxSettings.png">
          <img border="0" alt="VirtualBox Settings" src="http://satoricode.net/content/images/Android-x86/VirtualBoxSettings.png" width="100" />
        </a>
        <ul>
          <li>
target OS: Linux 
</li>
          <li>
target OS version: other 
</li>
          <li>
1 GB RAM 
</li>
          <li>
a dynamically sized VDI drive, 500 MB</li>
        </ul>
        <div style="clear: both">
        </div>
        <p>
Now mount the image to the machine, boot it and choose "Installation – Install Android-x86
to harddisk".
</p>
        <center>
          <a class="imagebox" title="Android-x86 Installation" href="http://satoricode.net/content/images/Android-x86/Android-x86Installation.png">
            <img border="0" alt="Android-x86 Installation" src="http://satoricode.net/content/images/Android-x86/Android-x86Installation.png" width="400" />
          </a>
        </center>
        <p>
During the installation you have to create a new partition, don’t forget to make it
bootable:
</p>
        <ul>
          <li>
select "Create" by using the arrow keys 
</li>
          <li>
select "Primary" 
</li>
          <li>
set the preferred size, or simply hit enter 
</li>
          <li>
select "Bootable" 
</li>
          <li>
select "Write" 
</li>
          <li>
confirm by typing "yes" 
</li>
          <li>
select "Quit"</li>
        </ul>
        <p>
Once the partition is created properly you will be able to choose and format it.
</p>
        <center>
          <a class="imagebox" title="Choose Partition" href="http://satoricode.net/content/images/Android-x86/Android-x86ChoosePartition.png">
            <img border="0" alt="Choose Partition" src="http://satoricode.net/content/images/Android-x86/Android-x86ChoosePartition.png" width="400" />
          </a>
        </center>
        <p>
Now complete the installation with the following steps:
</p>
        <ul>
          <li>
format sda1 as ext3 
</li>
          <li>
click "yes" to install the Grub boot loader 
</li>
          <li>
you may click also "yes" to install the /system directory as read-write</li>
        </ul>
        <p>
After those steps you have to reboot. Although our installation is complete and bootable,
I suggest to make some changes for enabling other screen resolutions.
</p>
        <h2>
        </h2>
        <h2>Changing Screen-Resolution
</h2>
        <p>
The screen resolution can be added as a booting parameter, or you can use a parameter
that lets you choose the resolution every time the system boots. To do so, we need
to change the configuration of the Grub boot-loader. Since we are not able to access
the configuration from within our installed system, boot again from the image and
choose "Live CD - Debug mode".
</p>
        <p>
Now we have to mount our booting partition and edit the "<strong>menu.lst</strong>",
containing our boot menu and the booting parameters.
</p>
        <pre class="brush: bash">mkdir /boot
mount /dev/sda1 /boot
vi /boot/grub/menu.lst</pre>
        <p>
Let’s take a look at the lines, starting with "<strong>kernel</strong>" – as you can
see, there are already few parameters passed to the kernel. There is also the option
"<strong>androidboot_hardware</strong>" that we want to change to "<strong>generic_x86</strong>",
since we are not using an EeePC.
</p>
        <p>
To select the resolution at start up we have to add the "<strong>vga=ask</strong>"
parameter and could change the line to something like this:
</p>
        <pre class="brush: plain">kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=generic_x86 acpi_sleep=s3_bios,s3_mode vga=ask SRC=/android-2.3-RC1</pre>
        <p>
If you want to add a specific resolution directly to a boot menu entry, simply add
the "<strong>DPI</strong>" and "<strong>UVESA_MODE</strong>" parameters instead:
</p>
        <pre class="brush: plain">kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=generic_x86 acpi_sleep=s3_bios,s3_mode DPI=240 UVESA_MODE=480x720 SRC=/android-2.3-RC1</pre>
        <p>
You have to save the menu.lst after editing (press ESC and type :wq).
</p>
        <p>
We are now ready to start the installed system – don’t forget to unmount the image
first!
</p>
        <h2>Booting the System and getting the Mouse to work
</h2>
        <p>
The booting performance is really great, isn’t it? As you might doubt out, your mouse
is not yet working within the VM – click "Disable Mouse Integration" on the "Machine"
menu or press Host key + I.
</p>
        <center>
          <a class="imagebox" title="VirtualBox Disable Mouse Integration" href="http://satoricode.net/content/images/Android-x86/VirtualBoxDisableMouseIntegration.png">
            <img border="0" alt="VirtualBox Disable Mouse Integration" src="http://satoricode.net/content/images/Android-x86/VirtualBoxDisableMouseIntegration.png" width="400" />
          </a>
        </center>
        <p>
The default keyboard layout of your Android-x86 system:
</p>
        <ul>
          <li>
"Windows Key" corresponds to the Android Home button 
</li>
          <li>
ESC corresponds to the Android back button 
</li>
          <li>
F2 corresponds to the Android menu button 
</li>
          <li>
F3 corresponds to the Android search button 
</li>
          <li>
Alt+F1 switches to console mode 
</li>
          <li>
Alt+F7 switches to GUI mode</li>
        </ul>
        <h2>Connecting as Android Virtual Device
</h2>
        <p>
To establish a connection between the host and the Android-x86 system and using the
VM as AVD you have to configure the networking options of your VM. There are different
ways to get this done. The simplest solution to connect both systems would be the
usage of the "<strong>Host-only Adapter</strong>". Go to your VM network settings
and change the "<strong>Attached to:"</strong> option to "<strong>Host-only Adapter</strong>".
</p>
        <center>
          <a class="imagebox" title="VrtualBox Network Settings: Host only Option" href="http://satoricode.net/content/images/Android-x86/VrtualBoxNetworkSettingsHostOnly.png">
            <img border="0" alt="VrtualBox Network Settings: Host only Option" src="http://satoricode.net/content/images/Android-x86/VrtualBoxNetworkSettingsHostOnly.png" width="400" />
          </a>
        </center>
        <p>
Once you have set up the network, start your VM and use the "<strong>netcfg</strong>"
command to output the actual network configuration of your Android system. You should
get something like 192.168.56.101 for the VM and the host will be bound to 192.168.56.1.
</p>
        <p>
On the host go to your SDK tools and start "<strong>adb</strong>" with the "<strong>connect</strong>"
parameter:
</p>
        <pre class="brush: plain">adb connect 192.168.56.101</pre>
        <p>
Congratulations! You now have a fully functional and very very fast AVD, running inside
of a VM and booting in a blink of an eye.
</p>
        <center>
          <a class="imagebox" title="Devices Eclipse" href="http://satoricode.net/content/images/Android-x86/DevicesEclipse.png">
            <img border="0" alt="Devices Eclipse" src="http://satoricode.net/content/images/Android-x86/DevicesEclipse.png" width="400" />
          </a>
        </center>
        <p>
You are now also able to select the newly created AVD as device in Eclipse.
</p>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=588e5cea-f457-4e83-be4e-18f537e01bef" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Creating Proxy-Classes for ViewModel’s (MVVM) by using DynamicObject</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/10/03/CreatingProxyClassesForViewModelsMVVMByUsingDynamicObject.aspx" />
    <id>http://satoricode.net/PermaLink,guid,a5ae529e-09a1-4563-bad1-2f91e65e4c0a.aspx</id>
    <published>2011-10-04T01:04:06.464+02:00</published>
    <updated>2011-10-04T12:51:43.7206094+02:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="C#" label="C#" scheme="http://satoricode.net/CategoryView,category,C.aspx" />
    <category term="MVC" label="MVC" scheme="http://satoricode.net/CategoryView,category,MVC.aspx" />
    <category term="MVVM" label="MVVM" scheme="http://satoricode.net/CategoryView,category,MVVM.aspx" />
    <category term="OOP" label="OOP" scheme="http://satoricode.net/CategoryView,category,OOP.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <img style="margin-left: 10px" align="right" src="http://satoricode.net/content/images/MVVM-DynamicObject-Proxy/MVVM.png" />
        <p>
The Model-View-ViewModel (MVVM) design pattern is a common approach when it comes
to WPF, Silverlight and ASP.NET MVC development. The separation of DomainModel, View
and ViewModel removes virtually all “code-behind” from the View layer. That makes
the application highly modular. If you have some experience in creating multilayer
applications and creating database layers, the benefits of decoupling Model and View
should be obvious. However, the benefits of creating a ViewModel layer might require
some explanation.
</p>
        <h3>The ViewModel
</h3>
        <p>
The ViewModel provides a view-specific representation of the data. So it’s a subset
or transformation of the DomainModel. It is a “Model made for a View” - a common approach
is to create one ViewModel for every particular View and keep them distinct from the
DomainModel types. In most cases that goes with the principle that the View dictates
the design of the ViewModel and to pass only required and optimal formatted information's
to the View.
</p>
        <p>
Let’s say we have the following DomainModel, containing information's about an Article
we get from our database:
</p>
        <pre class="brush: c-sharp">public class Article
{
  public int Oid { get; set; }
  public string Articlenumber { get; set; }
  public string Description { get; set; }
  public decimal Price { get; set; }
  public DateTime PublicationDate { get; set; }
}</pre>
        <p>
Furthermore we want to display detail information’s about an <strong>Article</strong> inside
an <strong>ArticleDetail</strong> view, so we have to create a ViewModel to pass:
</p>
        <pre class="brush: c-sharp">public class ArticleDetailModel
{
  public string Articlenumber { get; set; }
  public string Description { get; set; }
  public string Price { get; set; }
  public string PublicationDate { get; set; }
}</pre>
        <p>
The ViewModel contains all information’s we want to display inside of the <strong>ArticleDetail</strong> view.
In addition the data provided is already formatted (Price, PublicationDate) to fit
the needs of the view.
</p>
        <p>
That's how the instantiation of the ViewModel may appear in some kind of spaghetti
code:
</p>
        <pre class="brush: c-sharp">ArticleDetailModel m = new ArticleDetailModel();

m.Articlenumber = article.Articlenumber;
m.Description = article.Description;
m.Price = article.Price.ToString(CultureInfo.CurrentUICulture);
m.PublicationDate = article.PublicationDate.ToString(CultureInfo.CurrentUICulture);</pre>
        <p>
If we now choose to add an <strong>ArticleEdit</strong> view for editing an existing <strong>Article</strong>,
we have to create a new ViewModel, most likely including the “Oid” property as reference
to the record.
</p>
        <h3>Proxy Properties
</h3>
        <p>
If you might doubt, that approach results in having many different ViewModel’s for
every View we create and many lines of code to handle the instantiation of the ViewModel’s
and the formatting of data passed.
</p>
        <p>
There are different approaches to make that procedure more elegant. A solution might
be the <a href="http://automapper.org" target="_blank">AutoMapper</a> library, that
provides the functionality to map the DomainModel to the ViewModel. 
</p>
        <p>
Another approach is the implementation of proxy behavior for each property provided
by the ViewModel. Proxy properties usually looks like this:
</p>
        <pre class="brush: c-sharp">public string Price
{
  get { return this._domainModel.Price.ToString(CultureInfo.CurrentUICulture); }
  set { this._domainModel.Price = decimal.Parse(value); }
}</pre>
        <p>
At this point I suggest you to take a look at the <a href="http://www.castleproject.org/dynamicproxy" target="_blank">DynamicProxy</a> library
of the Castle Project. It provides functionality for generating .NET proxies on the
fly at runtime and may fit your requirements in that case too.
</p>
        <h3>DynamicObject Proxy
</h3>
        <img style="margin-right: 10px" align="left" src="http://satoricode.net/content/images/MVVM-DynamicObject-Proxy/ViewModelProxy.png" />
        <p>
My solution of implementing the ability of proxy properties is to use the dynamic
objects of the .NET Framework 4.0. DynamicObject’s allow you to determine at run time
how to handle property requests and let you “extend” your DomainModel that way. With
the power of dynamic objects you are also able to “route” all existing properties
to the underlying DomainModel, so you may only have to touch the ones that require
explicit formatting. You will be also able to flatten existing relations inside of
your DomainModel by using this approach.
</p>
        <p>
The implementation of the DynamicObject Proxy could look like this:
</p>
        <pre class="brush: c-sharp">public abstract class ViewModelProxy&lt;T&gt; : DynamicObject, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler  PropertyChanged;

  protected T _domainModel;

  private PropertyInfo[] _objectProperties;
  private PropertyInfo[] objectProperties
  {
    get
    {
      if (objectProperties == null)
        this._objectProperties = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

      return this._objectProperties;
    }
  }

  public override bool TryGetMember(GetMemberBinder binder, out object result)
  {
    var pi = this._objectProperties.FirstOrDefault((p) =&gt; p.Name == binder.Name);

    if (pi != null)
    {
      result = this._domainModel != null ? pi.GetValue(this._domainModel, null) : null;
      return true;
    }
    else
      return base.TryGetMember(binder, out result);
  }

  public override bool TrySetMember(SetMemberBinder binder, object value)
  {
    var pi = this._objectProperties.FirstOrDefault((p) =&gt; p.Name == binder.Name);

    if (pi != null)
    {
      if (this._domainModel != null)
      pi.SetValue(this._domainModel, value, null);
    
      if(PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(binder.Name);

      return true;
    }
    else
      return base.TrySetMember(binder, value);
  }
}</pre>
        <p>
All ViewModel’s are now able to inherit the <strong>ViewModelProxy&lt;T&gt;</strong> class
to provide access to all properties of our DomainModel type. We are also able to implement
new properties, or “override” existing ones.
</p>
        <p>
That’s how the example <strong>ArticleDetailModel</strong> would look like:
</p>
        <pre class="brush: c-sharp">public class ArticleDetailModel : ViewModelProxy&lt;Article&gt;
{
  public ArticleDetailModel(Article article)
  {
    this._domainModel = article;
  }

  public string Price
  {
    get { return this._domainModel.Price.ToString(CultureInfo.CurrentUICulture); }
    set { this._domainModel.Price = decimal.Parse(value); }
  }
  public string PublicationDate
  {
    get { return this._domainModel.PublicationDate.ToString(CultureInfo.CurrentUICulture); }
    set { this._domainModel.PublicationDate = DateTime.Parse(value); }
  }
}</pre>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=a5ae529e-09a1-4563-bad1-2f91e65e4c0a" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Understanding the benefits of a Dependency Injection Container (IOC)</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/10/01/UnderstandingTheBenefitsOfADependencyInjectionContainerIOC.aspx" />
    <id>http://satoricode.net/PermaLink,guid,40524f9a-741f-4dcd-a3fd-efcb13373cda.aspx</id>
    <published>2011-10-01T09:17:11.984+02:00</published>
    <updated>2011-10-04T08:14:11.9481484+02:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="C#" label="C#" scheme="http://satoricode.net/CategoryView,category,C.aspx" />
    <category term="OOP" label="OOP" scheme="http://satoricode.net/CategoryView,category,OOP.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
Ever wanted to program like a ninja? A couple of days ago I stumbled upon <a href="http://ninject.org" target="_blank">Ninject</a>,
an open source dependency injector (DI) for .NET. The entire design of the project
is hilarious, I felt like a ninja and like I’m doing something really cool and sneaky
by playing around with the framework. Although using dependency injection is very
common, the usage of an DI framework is something new for many developers.
</p>
        <p>
Dependency Injection is an implementation of the Inversion of Control pattern. 
There are two possible implementations for IoC:
</p>
        <ul>
          <li>
            <strong>Service Locator</strong> or <strong>Dependency Lookup</strong>: container
provides callback functionality and lookup context, components are requested by using
the locator (container) API. A dependency to the locator and API <strong>persists</strong>,
central binding and <strong> </strong>contextual binding is possible. 
<center><img title="Service Locator" border="0" alt="Service Locator" src="http://satoricode.net/content/images/DependencyInjection/ServiceLocator.png" /></center></li>
          <li>
            <strong>Dependency Injection</strong>: implementation without dependency to a container
API possible, able to manage lifecycles (scope, request, singleton, thread, transient),
lookup and contextual binding abilities are depending on the DI framework. 
</li>
        </ul>
        <p>
The idea behind DI and Inversion of Control is the use of the so-called “<a href="http://en.wikipedia.org/wiki/Hollywood_principle" target="_blank">Hollywood
Principle</a>” – “don’t call us, we’ll call you!”
</p>
        <h3>Simple Dependency Injection
</h3>
        <p>
Let me provide you an example of DI without using any DI framework. It’s a common
approach, that you likely know.
</p>
        <p>
When an object needs another object to operate properly, we have a dependency. In
the following example we have a <strong>Service</strong> and a <strong>Client</strong>,
where the <strong>Client</strong> class is tightly coupled with the <strong>Service</strong> class:
</p>
        <div style="width: 330px; float: left">
          <pre class="brush: c-sharp">public class Service
{
  public void Serve()
  {
    // do some serving stuff
  }
}

public class Client
{
  private Service _service;

  public Client()
  {
    this._service = new Service();
  }

  public void Start()
  {
    this._service.Serve();

    // do some client stuff
  }
}</pre>
        </div>
        <img style="float: right" title="Dependency" border="0" alt="Dependency" src="http://satoricode.net/content/images/DependencyInjection/Dependency.png" />
        <div style="clear: both">
        </div>
        <p>
Dependency injection eliminates that tight coupling and makes the application more
flexible and reusable:
</p>
        <div style="width: 330px; float: left">
          <pre class="brush: c-sharp">public interface IService
{
  public void Serve();
}

public class Service : IService
{
  public void Serve()
  {
    // do some serving stuff
  }
}

public class Client
{
  private IService _service;

  public Client(IService service)
  {
    this._service = service;
  }

  public void Start()
  {
    this._service.Serve();

    // do some client stuff
  }
}</pre>
        </div>
        <img style="float: right" title="Simple Dependency Injection" border="0" alt="Simple Dependency Injection" src="http://satoricode.net/content/images/DependencyInjection/SimpleDependencyInjection.png" />
        <div style="clear: both">
        </div>
        <p>
Sample Builder-Implementation:
</p>
        <pre class="brush: c-sharp">var client = new Client(new Service());

client.Start();
</pre>
        <p>
The Injection happens in the constructor, by passing the <strong>Service</strong> that
implements the <strong>IService</strong>-Interface. The dependencies are assembled
by a “Builder”, his responsibilities are as follows:
</p>
        <ul>
          <li>
knowing the types of each <strong>IService</strong></li>
          <li>
according to the request, feed the abstract <strong>IService</strong> to the <strong>Client</strong></li>
        </ul>
        <p>
The example above uses Constructor Injection. There are the following 3 possible implementations
of DI:
</p>
        <ul>
          <li>
Interface Injection 
</li>
          <li>
Setter Injection 
</li>
          <li>
Constructor Injection 
</li>
        </ul>
        <h3>What's wrong with the approaches?
</h3>
        <p>
Up till this point, you should no doubt realize the important role the dependency
injection above. In fact, as you may have doped out, there are some issues with the
approaches:
</p>
        <ul>
          <li>
            <strong>It is hardcoded</strong>: it can't be reused across applications, due to hardcoded
factories - that makes the code stringent to particular implementations 
</li>
          <li>
            <strong>Interface dependent</strong>: interfaces are used for decoupling the implementation
and the object creation procedure 
</li>
          <li>
            <strong>Instantiating is custom</strong>: instantiations are very much custom to a
particular implementation 
</li>
          <li>
            <strong>Everything is compile time:</strong> all dependent types for the objects in
the instantiation process (factory) have to be known at compile time 
</li>
        </ul>
        <h3>Service Locator
</h3>
        <p>
A common approach to achieve assembling the <strong>Client</strong> could be the following
implementation, by using service locator to avoid some of the issues described before:
</p>
        <pre class="brush: c-sharp">public class Locator
{
  private static Dictionary&lt;Type, Type&gt; dictionary = new Dictionary&lt;Type, Type&gt;();

  static Locator()
  {
    dictionary.Add(typeof(IService), typeof(Service));
  }

  public object Create(Type type)
  {
    if ((type == null || !dictionary.ContainsKey(type)))
      throw new NullReferenceException();

    return Locator.CreateInstance(dictionary[type]);
  }

  public T Create&lt;T&gt;()
  {
    return (T)Create(typeof(T));
  }
}</pre>
        <p>
Usage:
</p>
        <pre class="brush: c-sharp">var client = new Client(Locator.Create&lt;IService&gt;());</pre>
        <center>
          <img title="Service Locator" border="0" alt="Service Locator" src="http://satoricode.net/content/images/DependencyInjection/ServiceLocator-2.png" />
        </center>
        <p>
Extending the <strong>Locator</strong> looks like a great solution here - by using
a service locator it should be possible to achieve some runtime capabilities and a
clean and modular way to map interfaces to types. The more complex your requirements,
the more complex would be the <strong>Locator</strong>. Implementing the ability to
configure the <strong>Locator</strong> by using a XML configuration file, implement
conditional operation by reflecting types, attributes and even parameter names sounds
like a great solution, didn't it?<br />
What if the <strong>Client</strong> will get some more dependencies to inject? What
if that happens to the implementations of the <strong>IService</strong> too? What
if that happens only to a few implementations of the <strong>IService</strong>? What
about <a href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank">unit testing</a> and
setting up type mappings depending on the environment we are in? What about decoupling
the instantiation process a bit more? What about controlling the life cycle of the
created objects?
</p>
        <p>
          <strong>Good news here!</strong> There is already a solution to achieve those requirements:
the container way :)
</p>
        <p>
If you are interested in more specific information about the service locator pattern
and why it should be avoided I recommend the <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" target="_blank">Service
Locator is an Anti-Pattern</a> blog post from Misko Hevery.
</p>
        <h3>Using Dependency Injection Containers (IOC)
</h3>
        <p>
IOC assigns the responsibility of creating and coupling of objects to a configurable
Framework, according to a component model. The code of the object will become independent
of the environment and the concrete implementation of the class, it depends on and
makes particular unit-testing more easily.
</p>
        <p>
There are <a href="http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx" target="_blank">many</a> dependency
frameworks for .NET to chose from. The following examples are done by using <a href="http://ninject.org" target="_blank">Ninject</a>,
which comes with the following features:
</p>
        <ul>
          <li>
compact and easy to understand 
</li>
          <li>
lightweight, focusing the core functionalities 
</li>
          <li>
fast, it takes advantage of code generation in the CLR 
</li>
          <li>
doesn’t uses XML 
</li>
          <li>
takes advantage of the capabilities of the IDE and IntelliSense 
</li>
          <li>
supports contextual binding 
</li>
        </ul>
        <p>
Let me demonstrate you the power of IOC by implementing it to our <strong>Client</strong>/<strong>Service</strong> example:
</p>
        <pre class="brush: c-sharp">public interface IService
{
  public void Serve();
}

public class Service : IService
{
  public void Serve()
  {
    // do some serving stuff
  }
}

public class Client
{
  private IService _service;

  public Client(IService service)
  {
    this._service = service;
  }

  public void Start()
  {
    this._service.Serve();

    // do some client stuff
  }
}</pre>
        <p>
Did you noticed that there is <strong>no change</strong> of the example at all? The
difference in this example relies only on the usage of the provided classes. Like
many IoC containers, Ninject uses a central object (<strong>kernel</strong>) to provide
concrete implementations of dependencies at run-time. The <strong>StandardKernel</strong> is
the default implementation of such an object. So lets do it the Ninject-Way:
</p>
        <pre class="brush: c-sharp">using (IKernel kernel = new StandardKernel())
{
  kernel.Bind&lt;IService&gt;().To&lt;Service&gt;();

  var client = new Client(kernel.Get&lt;Service&gt;());
}</pre>
        <p>
The example above demonstrates the usage of Ninject but it's far away from impressing,
isn't it? Let us see Ninject performing something more clever:
</p>
        <pre class="brush: c-sharp">using (IKernel kernel = new StandardKernel())
{
  kernel.Bind&lt;IService&gt;().To&lt;Service&gt;();

  var client = kernel.Get&lt;Client&gt;();
}</pre>
        <p>
Did you see some kind of ninja stuff happened here? Ninject is able to build a <strong>Client</strong> and
taking care of providing the dependencies.
</p>
        <p>
Since this post is about IOC in general and not providing detailed information about
Ninject, let us start only a short survey to the more complex ninja abilities.
</p>
        <p>
          <strong>Contextual binding:</strong>
        </p>
        <pre class="brush: c-sharp">// only if we're injecting in to the Client
kernel.Bind&lt;IService&gt;().To&lt;Service&gt;().WhenInjectedInto&lt;Client&gt;();

// assuming we have a a Settings object, providing a boolean property "OnlineMode" and two types implementing the IService interface
kernel.Bind&lt;IService&gt;().To&lt;OnlineService&gt;().When(request =&gt; kernel.Get&lt;Settings&gt;().OnlineMode);
kernel.Bind&lt;IService&gt;().To&lt;LocalService&gt;().When(request =&gt; !kernel.Get&lt;Settings&gt;().OnlineMode);</pre>
        <p>
          <strong>Controlling the life cycle of the objects:</strong>
        </p>
        <p>
Since the kernel provides us the objects of the types we are requesting, it is also
easily able to take control of the different lifecycle-scopes the objects are in.
Ninjects provides the following 4 scopes:
</p>
        <ul>
          <li>
Transient (default) 
</li>
          <li>
Singleton (only one instance) 
</li>
          <li>
Thread (one instance per thread) 
</li>
          <li>
Request (one instance per web request) 
</li>
        </ul>
        <p>
The following example demonstrates how requesting objects in singleton scope works:
</p>
        <pre class="brush: c-sharp">kernel.Bind&lt;IService&gt;().To&lt;Service&gt;().InSingletonScope();

var client1 = kernel.Get&lt;Client&gt;();
var client2 = kernel.Get&lt;Client&gt;();

Assert.Same(client1, client2);</pre>
        <p>
Please note that this is only a short summary of what IOC and especially Ninject can
do for you. If you are interested in becoming an IOC-Ninja, I suggest you to read
the <a href="http://ninject.codeplex.com/wikipage?title=User%20Guide&amp;referringTitle=Home" target="_blank">Ninject
Walkthrough on CodePlex</a>. If you are new to dependency injection at all, my recommendation
is to start with Manual Dependency Injection as described at the beginning of the
post.
</p>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=40524f9a-741f-4dcd-a3fd-efcb13373cda" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Cleaner Event Declarations in C#</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/09/08/CleanerEventDeclarationsInC.aspx" />
    <id>http://satoricode.net/PermaLink,guid,7dc74193-9b02-4c46-ba53-839e5ffc7aea.aspx</id>
    <published>2011-09-08T06:56:04.673+02:00</published>
    <updated>2011-09-08T06:59:24.001125+02:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="C#" label="C#" scheme="http://satoricode.net/CategoryView,category,C.aspx" />
    <category term="Snippets" label="Snippets" scheme="http://satoricode.net/CategoryView,category,Snippets.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
The traditional event declaration in C# looks something like this:
</p>
        <pre class="brush: c-sharp">public event EventHandler Executed;
protected virtual void OnExecuted()
{
  if (this.Executed != null)
    this.Executed(this, EventArgs.Empty);
}</pre>
        <p>
The gratuitous null check in the virtual OnXYZ event caller has always pestered me
and I just learned an interesting alternate syntax to avoid this boiler plate code!
Behold the cleaner alternative:
</p>
        <pre class="brush: c-sharp">public event EventHandler Executed = (o, e) =&gt; { };
protected virtual void OnExecuted()
{
  this.Executed(this, EventArgs.Empty);
}</pre>
        <p>
When declaring the event start by assigning it to a lambda, then your event will never
be null. Of course there is a minor performance impact to this, but we’re not prematurely
optimizing right?
</p>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=7dc74193-9b02-4c46-ba53-839e5ffc7aea" />
      </div>
    </content>
  </entry>
  <entry>
    <title>Randomize List sort order using LINQ</title>
    <link rel="alternate" type="text/html" href="http://satoricode.net/2011/09/06/RandomizeListSortOrderUsingLINQ.aspx" />
    <id>http://satoricode.net/PermaLink,guid,053d35d5-7a75-4257-8b2c-335954af6ca9.aspx</id>
    <published>2011-09-06T06:09:04.485+02:00</published>
    <updated>2011-09-08T07:00:33.8605+02:00</updated>
    <category term=".NET" label=".NET" scheme="http://satoricode.net/CategoryView,category,NET.aspx" />
    <category term="C#" label="C#" scheme="http://satoricode.net/CategoryView,category,C.aspx" />
    <category term="LINQ" label="LINQ" scheme="http://satoricode.net/CategoryView,category,LINQ.aspx" />
    <category term="Snippets" label="Snippets" scheme="http://satoricode.net/CategoryView,category,Snippets.aspx" />
    <author>
      <name>Marc-Anton Flohr</name>
    </author>
    <content type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <p>
I wanted to display 5 random records of a List on my site, imagining a loop that generates
a bunch of random indexes and pulling 5 elements from the list.
</p>
        <p>
I decided to use a more elegant solution, by using LINQ with only two lines of code:
</p>
        <pre class="brush: csharp">var rnd = new Random();
list = list.OrderBy(x =&gt; rnd.Next()).ToList();
</pre>
        <p>
To take n random elements:
</p>
        <pre class="brush: c-sharp">var rnd = new Random();
list = list.OrderBy(x =&gt; rnd.Next()).Take(n).ToList();
</pre>
        <p>
Encapsulated by using extension methods:
</p>
        <pre class="brush: c-sharp">public static IEnumerable&lt;T&gt; OrderByRandom&lt;T&gt;(this IEnumerable&lt;T&gt; source)
{
  var rnd = new Random();
  return source.OrderBy(x =&gt; rnd.Next());
}

public static IEnumerable&lt;T&gt; TakeRandom&lt;T&gt;(this IEnumerable&lt;T&gt; source, int n)
{
  return source.OrderByRandom().Take(n);
}
</pre>
        <img width="0" height="0" src="http://satoricode.net/aggbug.ashx?id=053d35d5-7a75-4257-8b2c-335954af6ca9" />
      </div>
    </content>
  </entry>
</feed>
