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

<channel>
	<title>Pattern Web Solutions</title>
	<atom:link href="http://www.patternwebsolutions.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.patternwebsolutions.com</link>
	<description>IT should solve problems, not create more.</description>
	<lastBuildDate>Mon, 18 Jul 2011 15:17:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Export securables from SQL Server 2005 or higher.</title>
		<link>http://www.patternwebsolutions.com/2011/07/18/export-securables-from-sql-server-2005-or-higher/</link>
		<comments>http://www.patternwebsolutions.com/2011/07/18/export-securables-from-sql-server-2005-or-higher/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 15:17:53 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[Solutions]]></category>
		<category><![CDATA[tipsandtechniques]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=119</guid>
		<description><![CDATA[Brian Kelley wanted something to store role security for disaster recovery. It came in very handy to get the permissions used on a development system into a live system. Since I was only worried about a single role, I added the condition &#8220;AND dprins.name = @RoleName&#8221; at the end.]]></description>
			<content:encoded><![CDATA[<p>Brian Kelley wanted something to <a href="http://www.mssqltips.com/tip.asp?tip=2142" title="Retrieving SQL Server Permissions for Disaster Recovery">store role security for disaster recovery</a>. It came in very handy to get the permissions used on a development system into a live system.</p>
<p>Since I was only worried about a single role, I added the condition &#8220;AND dprins.name = @RoleName&#8221; at the end.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/07/18/export-securables-from-sql-server-2005-or-higher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Connect to Oracle using FluentNHibernate</title>
		<link>http://www.patternwebsolutions.com/2011/07/10/connect-to-oracle-using-fluentnhibernate/</link>
		<comments>http://www.patternwebsolutions.com/2011/07/10/connect-to-oracle-using-fluentnhibernate/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 15:39:13 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[Solutions]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=108</guid>
		<description><![CDATA[&#8220;Could not create the driver from NHibernate.Driver.OracleDataClientDriver, NHibernate, Version=3.1.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.&#8221; Huh? All I want to do is use FluentNHibernate to connect to an Oracle database. Is it really so hard? Apparently it&#8217;s just a little tricky. The root of the issue is actually the exception &#8220;Unable to find the requested .Net Framework Data Provider. It [...]]]></description>
			<content:encoded><![CDATA[<h2>&#8220;Could not create the driver from NHibernate.Driver.OracleDataClientDriver, NHibernate, Version=3.1.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.&#8221; Huh?</h2>
<p>All I want to do is use FluentNHibernate to connect to an Oracle database. Is it really so hard? Apparently it&#8217;s just a little tricky. The root of the issue is actually the exception &#8220;Unable to find the requested .Net Framework Data Provider. It may not be installed.&#8221;. For someone who&#8217;s only used NHibernate against SQL Server variants, this is a little confusing.</p>
<h2>What is a DbProviderFactory and why should I care?</h2>
<p>A DbProviderFactory is a Microsoft addition to ADO.NET 2. It centralizes creation logic into one place and let&#8217;s you use ICommand, IConnection and other interfaces from System.Data.Common against any database you have an installed provider for. The NHibernate developers liked the idea and ran with it.</p>
<p>So why should you care? Because Oracle only supports this in later versions of the libraries. Unfortunately, it&#8217;s also not as simple as referencing a different version, as the user is expected to have a the full Oracle Client Tools installed on their machine. If you&#8217;re have a more recent version (10.2 release 2 or later) of Oracle client tools, this error is unlikely to occur as the installer will properly register it.</p>
<p>If you just want to let somebody connect to Oracle without all this existing infrastructure, you need to do something else.</p>
<h2>Fixing the issue.</h2>
<p>There are two ways to do this. Tell your clients to install a more recent version of the Oracle Data Access Components. This isn&#8217;t an option in all circumstances unfortunately.</p>
<p>Otherwise, you can use local DLLs using the following method (from Stack Overflow questions <a href="http://stackoverflow.com/questions/70602/what-is-the-minimum-client-footprint-required-to-connect-c-to-an-oracle-database">what-is-the-minimum-client-footprint-required-to-connect-c-to-an-oracle-database</a> and <a href="http://stackoverflow.com/questions/923283/what-is-the-minimal-setup-required-to-deploy-a-net-application-with-oracle-clien">what-is-the-minimal-setup-required-to-deploy-a-net-application-with-oracle-clien</a>.</p>
<p>If any of these links don&#8217;t get you directly to the relevant page, Oracle may be redirecting you to the root downloads page. Look for the Database category in that case.</p>
<ol>
<li>Download the <a href="http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html">Oracle Instant Client</a>. The x86 version is a safe bet, but use 64 bit if you know you need it. I took the Basic package because I&#8217;m dealing with possible internationalization issues &#8211; if you don&#8217;t need multiple language support, you can get the Basic Lite package. Get a package with a version number of at least 11.0.0.</li>
<li>Extract these files into your project root. Add them to the project and set the Copy property of all of them to Copy Always.
<ul>
<li>oci.dll</li>
<li>orannzsb11.dll</li>
<li>oraociei11.dll</li>
</ul>
</li>
<li>Get a copy of msvcr71.dll from somewhere. I used <a href="http://www.dll-files.com/msvcr71.zip?0WDmQ0dHjP">http://www.dll-files.com/msvcr71.zip?0WDmQ0dHjP</a>. Run a virus scan just in case. Put in your project root, add it to the project and set it to Copy Always.</li>
<li>Download the <a href="http://www.oracle.com/technetwork/database/windows/downloads/index-101290.html">Oracle Data Access Client</a> XCopy version. Look for the package with the same version. For Oracle Instant Client 11.2.0.1.0, you need ODAC 11.2 Release something or other (long version number) with Xcopy deployment. Extract the file \odp.net20\bin\OraOps11w.dll and add it to the project root, the solution and with the Copy property Copy Always. Extract the file \odp.net20\odp.net\bin\2.x\oracle.dataaccess.client.dll to your project root and Add Reference to it.</li>
<li>Almost finished.</li>
<li>Find Oracle.DataAccess in the references list and look at it&#8217;s Version property. Make a note of it, mine was 2.112.2.0.</li>
<li>Add the following XML to the configuration element in your App.Config or Web.Config. If the Version number of your Oracle.DataAccess reference is different, then change it in the type details.
<pre class="brush: xml; title: ; notranslate">
    &lt;system.data&gt;
      &lt;DbProviderFactories&gt;
        &lt;add name=&quot;Oracle Data Provider for .NET&quot; invariant=&quot;Oracle.DataAccess.Client&quot; description=&quot;Oracle Data Provider for .NET&quot; type=&quot;Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=2.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342&quot; /&gt;
      &lt;/DbProviderFactories&gt;
    &lt;/system.data&gt;
</pre>
</li>
<li>Test that it works by using this code somewhere. It should write a reference to Oracle.DataAccess.Client and give you a valid factory at the end of it. Obviously without throwing any exceptions.
<pre class="brush: csharp; title: ; notranslate">
            using (DataTable providers = DbProviderFactories.GetFactoryClasses())
            {
                Console.WriteLine(&quot;Available Data Providers:&quot;);
                foreach (DataRow prov in providers.Rows)
                {
                    Console.WriteLine(&quot;Name:{0}&quot;, prov[&quot;Name&quot;]);
                    Console.WriteLine(&quot;Description:{0}&quot;, prov[&quot;Description&quot;]);
                    Console.WriteLine(&quot;Invariant Name:{0}&quot;, prov[&quot;InvariantName&quot;]);
                }
            }

            DbProviderFactory factory = DbProviderFactories.GetFactory(&quot;Oracle.DataAccess.Client&quot;);
</pre>
</li>
<li>Done. Ugly. But done.</li>
</ol>
<p>You should now be able to use this kind of code perfectly happily.</p>
<pre class="brush: csharp; title: ; notranslate">
var sessionFactory = Fluently.Configure()
                .Database(
                    OracleDataClientConfiguration
                        .Oracle10
                        .ConnectionString(c =&gt; c.FromConnectionStringWithKey(&quot;MyConnectionString&quot;))
                        .ShowSql())
                .CurrentSessionContext(&quot;thread_static&quot;)
                .ProxyFactoryFactory(typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory))
                .Mappings(m =&gt; m.FluentMappings.AddFromAssemblyOf&lt;MyORMObject&gt;())
                .BuildSessionFactory();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/07/10/connect-to-oracle-using-fluentnhibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>First Steps into RhinoMocks</title>
		<link>http://www.patternwebsolutions.com/2011/04/25/first-steps-into-rhinomocks/</link>
		<comments>http://www.patternwebsolutions.com/2011/04/25/first-steps-into-rhinomocks/#comments</comments>
		<pubDate>Mon, 25 Apr 2011 15:28:30 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[tipsandtechniques]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=99</guid>
		<description><![CDATA[RhinoMocks has been on my radar for a long time, but today is the first day I have managed to use it to good effect. Up until now, when I wanted to test something, I felt that I had to make a whole database to test my code against. Now, though, I can&#8217;t. My domain [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ayende.com/projects/rhino-mocks.aspx">RhinoMocks</a> has been on my radar for a long time, but today is the first day I have managed to use it to good effect.</p>
<p>Up until now, when I wanted to test something, I felt that I had to make a whole database to test my code against. Now, though, I can&#8217;t. My domain model is a tiny part of a legacy database. Now, I can build up just the pieces of data I need.</p>
<p>I am going to assume you are using an ORM layer (and if not, why aren&#8217;t you?). At work, I&#8217;m on nHibernate but your tastes may run to Entity Framework or something else. Whatever it is, so long as you can easily create new domain objects.</p>
<p>My example is based on a small piece of workflow logic. If an Entity meets certain conditions, it is authorized to progress through the workflow. Specifically, we have a student who is trying to apply for a programme limited to Undergraduates. We will go through our requirements and what we need to test, look at a method of testing using a database and then look at how RhinoMocks can help us.</p>
<p>We start with the very basic data entities.</p>
<pre class="brush: csharp; title: ; notranslate">
public enum StudentCategory
{
  Undergraduate,
  Postgraduate
}

public class Student
{
  public virtual string Id { get;set; }
  public virtual StudentCategory Category { get; set; }

}

public interface IStudentRepository
{
  Student GetStudentById(string Id);
}
</pre>
<p>Now, we worry about the student programme we are trying to assign these poor layabouts, I&#8217;m sorry, students to. This is another Entity with AssignedStudents mapped into the database as a One-To-Many relationship. </p>
<p>The <a href="http://en.wikipedia.org/wiki/Strategy_pattern">Strategy pattern</a> is used here to give the programme its rules on who can be assigned. The class we are implementing only uses one rule. Other options could include using a collection of IAuthorizationRule implementations or implementing IAuthorizationRule with a class that is composed of other rules.</p>
<pre class="brush: csharp; title: ; notranslate">
// The behavior we really care about.
public interface IStudentProgramme
{
  public bool AddStudent(Student newStudent);
  public IEnumerable&lt;Student&gt; AssignedStudents { get; }
}

// Concrete implementation of IStudentProgramme
public class ExampleStudentProgramme : IStudentProgramme
{
  private IAuthorizationRule&lt;Student&gt; rule;

  private IList&lt;Student&gt; assignedStudents { get; set; }

  public ExampleStudentProgramme(IAuthorizationRule&lt;Student&gt; rule)
  {
    this.rules = rule;
    this.assignedStudents = new List&lt;Student&gt;();
  }

  public int Id { get;set; }

  public IEnumerable&lt;Student&gt; AssignedStudents
  {
    get
    {
      return assignedStudents;
    }
  }

  public bool AddStudent(Student newStudent)
  {
    if (rule.Authorize(newStudent))
    {
      AssignedStudents.Add(newStudent);
      return true;
    }
    return false;
  }
}

// Rule used in the Strategy pattern
public class MustBeUnderGrad : IAuthorizationRule&lt;Student&gt;
{
  public bool Authorize(Student student)
  {
    return student.Category == StudentCategory.Undergraduate;
  }
}

// Repository Interface
public interface IProgrammeRepository
{
  IStudentProgramme GetProgrammeById(string Id);
}
</pre>
<p>Testing will be performed from the client perspective. They call us from outside our little black box and they don&#8217;t care how we fulfill their request. We can test the little bits like the MustBeUnderGrad rules by themselves but that will only tell us about the implementation that we have covered. If we test the unit as a whole it gives us much more confidence in the interface we are providing to others.</p>
<p>There are many ways to call into this kind of component. It could be a windows application, an MVC web app, a web service or something else. Whatever it is, we can provide the following interface to consumers of our component:</p>
<pre class="brush: csharp; title: ; notranslate">
public StudentProgrammes
{
  private readonly IProgrammeRepository programmeRepository;

  private readonly IStudentRepository studentRepository;

  public StudentProgrammes(IProgrammeRepository programmeRepository, IStudentRepository studentRepository)
  {
    this.programmeRepository = programmeRepository;
    this.studentRepository = studentRepository;
  }

  public bool AssignStudentToProgramme(int studentId, int programmeId)
  {
    Student student = studentRepository.GetStudentById(studentId);
    IStudentProgramme programme = programmeRepository.GetProgrammeById(programmeId);

    return programme.AddStudent(student);
  }
}
</pre>
<p>Now that we have the example all coded up the next thing to look at is how we can build a test using the database.</p>
<pre class="brush: csharp; title: ; notranslate">
[TestMethod]
public void TestAssignUndergraduateReturnsTrue()
{
  // Arrange
  // Build the nHibernate session and wire up the repositories
  ISession session = TestSupport.BuildSessionFactory();
  IProgrammeRepository programmeRepository = new ProgrammeRepository(session);
  IStudentRepository studentRepository = new StudentRepository(session);
  IStudentProgrammes programmes = new StudentProgrammes(programmeRepository, studentRepository);

  // Act
  bool result = programmes.AssignStudentId(2);

  // Assert
  Assert.IsTrue(result);
}
</pre>
<p>That is an elegant way of dealing with code in the main system but building a session and using data from a real database can cause us problems. What if someone else goes to the database and deletes some of your test data? Where are you maintaining it? How are you sure that a particular ID will exercise the test correctly? When things change, you lose your hair trying to find out why.</p>
<p>That&#8217;s the database method. Now we look at how Rhinomocks can help us instead.</p>
<pre class="brush: csharp; title: ; notranslate">
public void TestAssignUndergraduateReturnsTrue()
{
  // Arrange
  IStudentProgramme exampleProgramme = new ExampleStudentProgramme(new MustBeUnderGrad())
  {
    Id = 1
  };

  Student student = new Student
  {
    Id = 2,
    Category = StudentCategory.Undergraduate
  };

  IStudentRepository studentRepository = MockRepository.GenerateStub&lt;IStudentRepository&gt;();
  IProgrammeRepository programmeRepository = MockRepository.GenerateStub&lt;IProgrammeRepository&gt;();

  programmeRepository.Stub(stuboptions =&gt; programmeRepository.GetProgrammeById(Args.Is(1))).Return(programme);
  studentRepository.Stub(stuboptions =&gt; studentRepository.GetStudentById(Args.Is(2))).Return(student);

  programmeRepository.Replay();
  studentRepository.Replay();

  IStudentProgrammes programmes = new StudentProgrammes(programmeRepository, studentRepository);

  // Act
  bool result = programmes.AssignStudentId(2);

  // Assert
  Assert.IsTrue(result);
}
</pre>
<p>What we are doing here is setting up our input objects in our code so that all the properties that we know are needed are set as we expect them. Using MockRepository.GenerateStub we create a magic proxy object that will return a certain object for a certain input. To tell it what those inputs are, we use the .Stub() call. The magic of RhinoMocks uses the lambda function to figure out what we want to do and then the call to .Return() sets the output to be returned for those inputs.</p>
<p>.Replay() then tells the magic proxy objects that they won&#8217;t be configured anymore and to act in the way we have told them to.</p>
<p>When the code under test calls the magic proxy objects we give it, it gets the objects we want it to have. Then it runs through all its own logic and if we haven&#8217;t screwed up somewhere then it will return the correct value.</p>
<p>This may seem more complicated right now but all the complication is up front. The key benefit is that all of your assumptions are built up here in the test. The only change that can affect your inputs are in your code. We&#8217;ve prevented the major cause of non-determinism affecting our test results.</p>
<p>The other key benefit is that you aren&#8217;t using other systems that you have to reach across a network or through a process barrier that could slow down tests of logic. If it&#8217;s just objects in memory, your tests will blaze through and as we all know, speed is vital in the test-write-retest cycle.</p>
<p>There are ways to clean up what could turn into messy tests too. In most situations, you can factor out the initial object creation because the same or similar objects will be reused a lot. Also, if you&#8217;ve got lots of calls being made into other objects, it may be worth refactoring the code under test and see why it is making so many different calls.</p>
<p>One last note. This isn&#8217;t test driven development since we&#8217;ve written the test last. When this returns green, how do we know that it&#8217;s because our code works and not that our test will always succeed? That&#8217;s too much for now though, go experiment.</p>
<p>What were your results?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/04/25/first-steps-into-rhinomocks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Move Visual Studio&#8217;s folder out of My Documents</title>
		<link>http://www.patternwebsolutions.com/2011/03/29/move-visual-studios-folder-out-of-my-documents/</link>
		<comments>http://www.patternwebsolutions.com/2011/03/29/move-visual-studios-folder-out-of-my-documents/#comments</comments>
		<pubDate>Tue, 29 Mar 2011 09:29:50 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[tipsandtechniques]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=84</guid>
		<description><![CDATA[I&#8217;ve just started in a new office and finding my way around some of their more interesting choices. One of which is to make My Documents a network share and limit the size of it. Everything in that folder gets backed up, so I only want important and useful files in it. The entries in [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just started in a new office and finding my way around some of their more interesting choices. One of which is to make My Documents a network share and limit the size of it. Everything in that folder gets backed up, so I only want important and useful files in it. The entries in the default Visual Studio folder don&#8217;t count.</p>
<p>Thankfully, there is a way to shift everything that Visual Studio creates into another location.</p>
<p>Use Regedit and look in HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0. Change all occurrences of the directory you don&#8217;t want (&#8220;z:\&#8221; in my case) to the one you do (&#8220;c:\local\&#8221;). You&#8217;ll also want to look in the \Profile\ key and the subkeys of \vsmacros\.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/03/29/move-visual-studios-folder-out-of-my-documents/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Connect Website using FacebookSDK and ASP.NET MVC 3</title>
		<link>http://www.patternwebsolutions.com/2011/03/07/facebooksdk-connect-mvc3/</link>
		<comments>http://www.patternwebsolutions.com/2011/03/07/facebooksdk-connect-mvc3/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 17:49:52 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[tipsandtechniques]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=73</guid>
		<description><![CDATA[The goal is to have a login link with Facebook link that lets the site personalize the content if the user wants to log in with their Facebook details. This is based on a days worth of experiments so I&#8217;m not 100% convinced I&#8217;m doing this right. Let me know in the comments if you [...]]]></description>
			<content:encoded><![CDATA[<p>The goal is to have a login link with Facebook link that lets the site personalize the content if the user wants to log in with their Facebook details. This is based on a days worth of experiments so I&#8217;m not 100% convinced I&#8217;m doing this right. Let me know in the comments if you see something wrong.</p>
<p>First, you need to have an application set up on Facebook. To set up your Canvas Page and Canvas URL you must first <a href="http://www.facebook.com/developers/createapp.php?app_id=491999905203">register your Facebook app</a> and enter in your basic app information. With that complete, click the &#8220;Facebook Integration&#8221; tab on the left side of the configuration screen and make a note of the App ID and App Secret Key. Never reveal your secret key to anyone! You do not have to look at the other settings, but it is advisable to go through Facebook&#8217;s documentation and understand what they all mean.</p>
<p>To get started with FacebookSDK in a File|New ASP.NET MVC 3 Project, get the FacebookWebMVC package from NuGet or <a href="http://facebooksdk.codeplex.com/releases/view/60694#ReviewsAnchor">download package 5.0.3</a>. You want the Newtonsoft.Json, Facebook, Facebook.Web and Facebook.Web.MVC assemblies.</p>
<p>Once you have referenced the right assemblies, open &#8220;/Views/Shared/_Layout.cshtml&#8221; and add the following to the bottom before the closing body tag.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;div id=&quot;fb-root&quot;&gt;
    &lt;/div&gt;
    &lt;script src=&quot;http://connect.facebook.net/en_US/all.js&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
        FB.init({ appId: '@Facebook.FacebookContext.Current.AppId', status: true, cookie: true, xfbml: true });
        $('#fbLogin').click(function () {
            FB.login(function (response) {
                if (response.session) {
                    window.location = '@Url.Action(&quot;AboutMe&quot;)'
                } else {
                    // user cancelled login
                }
            });
        });
        $('#fbLogout').click(function () {
            FB.logout(function (response) {window.location = '@Url.Action(&quot;Index&quot;)';});
        });
    &lt;/script&gt;
</pre>
<p>This script block and div initializes Facebook&#8217;s JavaScript SDK and attaches the events that authenticate and authorize this site against Facebook for the current user of the browser.</p>
<p>Replace the contents of &#8220;/Views/Shared/_LogOnPartial.cshtml&#8221; with the following and save the image into the &#8220;/Content/&#8221; directory. </p>
<pre class="brush: xml; title: ; notranslate">
@if (Model != null &amp;&amp; Model.Session != null)
{
    &lt;p&gt;Welcome &lt;b&gt;@Model.DisplayName&lt;/b&gt;! &lt;a href=&quot;#&quot; id=&quot;fbLogout&quot;&gt;Logout&lt;/a&gt;&lt;/p&gt;
}
else
{
    &lt;p&gt;
        &lt;img id=&quot;fbLogin&quot; src=&quot;../../Content/login-button.png&quot; /&gt;
    &lt;/p&gt;
}
</pre>
<p><img src="http://www.patternwebsolutions.com/wp-content/uploads/2011/03/login-button.png" alt="Login with Facebook" title="Login with Facebook" width="154" height="22" class="alignnone size-full wp-image-80" /></p>
<p>There&#8217;s better ways of loading data into the partial. Using a ViewModel with DisplayName and Authenticated properties would be a good start. For now, let&#8217;s carry on with the dynamic model.</p>
<p>Add the following to HomeController.cs</p>
<pre class="brush: csharp; title: ; notranslate">
    using Facebook;
    using Facebook.Web;

// snip  

        public FacebookSession CurrentSession
        {
            get { return new Authorizer().Session; }
        }

        public ActionResult AboutMe()
        {
            dynamic model = new ExpandoObject();

            if (this.CurrentSession != null)
            {
                var app = new FacebookClient(this.CurrentSession.AccessToken);

                dynamic me = app.Get(&quot;me&quot;);
                dynamic friends = app.Get(&quot;/me/friends&quot;);

                model.Name = me.name;
                model.FriendCount = friends.data.Count;
            }
            else
            {
                model.Name = &quot;Guest User&quot;;
                model.FriendCount = 0;
            }

            model.Session = this.CurrentSession;
            return View(model);
        }
</pre>
<p>The AboutMe is doing the heavy lifting. The Authorizer comes from the Facebook namespace and handles the session information. If it is not null we have a logged in user and can personalize data on the page. In this very simple case, a name and a friend count.</p>
<p>If you want to prevent a request with a null CurrentSession (i.e. a request from an unauthenticated Facebook user) add the [FacebookAuthorize] attribute to the Action method.</p>
<p>This works in a simple fashion but CurrentSession could do with being easily mockable and I&#8217;m a little wary of how complex the controller actions could get if I&#8217;m not careful. What would you recommend? </p>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/03/07/facebooksdk-connect-mvc3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>What are MVVM, MVP and MVC?</title>
		<link>http://www.patternwebsolutions.com/2011/02/25/what-are-mvvm-mvp-and-mvc/</link>
		<comments>http://www.patternwebsolutions.com/2011/02/25/what-are-mvvm-mvp-and-mvc/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 23:22:32 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[Essays]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=43</guid>
		<description><![CDATA[Almost anywhere you look these days you can see these acronyms popping up. What do they mean to the .NET developer and are they more than somebody throwing a letters at the screen? All three of these acronyms describe (subtly different) approaches to application development based on the separation of business and user interface logic. [...]]]></description>
			<content:encoded><![CDATA[<p>Almost anywhere you look these days you can see these acronyms popping up. What do they mean to the .NET developer and are they more than somebody throwing a letters at the screen?</p>
<p>All three of these acronyms describe (subtly different) approaches to application development based on the separation of business and user interface logic. In all three, the MV stands for Model-View which is the portion of the approach relating to storing and presenting data. The last letters describe how that data is manipulated within the application. -C is -Controller, -P is Presenter -VM is ViewModel. Hold on, these words will all make more sense soon.</p>
<p>Models are small simple data objects that are responsible for containing valid data and nothing more. A UserAccount is an example of a Model, it can have a FirstName, LastName, EMailAddress, Password and so on. Often the Model will have validation logic, so that a Password must meet defined security rules like being at least 8-10 characters long and include at least one letter and one number.</p>
<p>Views transform data from their internal system representation as a Model to a form that the external user can understand. There can be many Views for a particular Model. For example, the same UserAccount Model can be presented to another user as a profile page or to the active user as an account editing page.</p>
<h2>MVC</h2>
<p>Over the last 3 years, MVC has been popularized in the .NET community by the ASP.NET MVC project. Now at version 3, this project promises to deliver a framework for web development that encourages fine-grained testability and managed complexity. Their <a title="ASP.NET MVC Overview" href="http://www.asp.net/mvc/tutorials/asp-net-mvc-overview-cs">overview</a> goes over these goals in more detail.</p>
<p>MVC has a much longer history though. Much of the early work of the Microsoft teams builds on the work of <a title="Ruby on Rails home" href="http://rubyonrails.org/">Ruby on Rails</a> and there are still many similarities in the core philosophy.</p>
<p>The Controller objects in MVC are groups of related behavior. It can provide functionality to select and manipulate Models and encapsulates all the relevant business logic. The Controller doesn&#8217;t need to know how to validate the data in a Model or to interface with the user.</p>
<p>For example, a User Controller can provide a Search action and an Update action. When a request from the interface to search for a User with a particular name comes in, the Controller looks for Model objects that have that name and provides it to a View which translates the collection of objects into a list the user can see and interact with. When they change something and request that the changes be saved, the Controller runs through all the required logic such as asking the updated Model if it is currently valid and saving it to the persistent store.</p>
<p>This approach works very well when you care about changing the way actions are performed more than how data is presented. It is very easy to add another action to one controller that can be used from anywhere, like TransferToShipping, without having to add a dependency to every view that could possibly use it.</p>
<p>The modern MVC frameworks are most at home on the web because a URL maps easily to a View-independant controller and action. The action-bias is more difficult to present in the current desktop paradigms.</p>
<h2>MVP</h2>
<p>MVP in general is a derivative of MVC in general. It focuses on the View and how to support it in a testable and manageable way. <a title="ASP.NET Web Forms MVP" href="http://webformsmvp.com/">WebformsMVP</a> is a reaction to ASP.NET MVC that intends to bring the same tools to the View-first method of development.</p>
<p>The Presenter of MVP does much the same job as the Controller in MVC. The major difference is which object is the logical container. Controllers take input directly from the interface, instantiate the appropriate View with a Model and provide the View to the interface. The View in MVP handles all input and uses the Presenter to perform actions and format data to be displayed in the widgets on the View.</p>
<p>A View in this approach would be a UserView. It would include all necessary controls to find and display the data from a UserModel. The UserPresenter&#8217;s role is to update the UserView&#8217;s controls with formatted data from the UserModel and perform actions requested by the UserView. To make this less brittle, the UserPresenter is programmed against the IUserView interface. Specific UserView objects could be windows forms, web forms or something else. So long as they provide the relevant properties, all is well.</p>
<p>This approach works great when you want your visual presentation to be the first point of change and you worry most about what users will do from one visual starting point. This is because one Presenter is tied to one View interface.</p>
<p>MVP works equally in Windows Forms and Web Forms because all a Presenter needs is a View that conforms to a particular interface.</p>
<h2>MVVM</h2>
<p>MVVM is a pattern with a very specific job. That job is to separate the code that sets visual properties from Model data when you use WPF and Silverlight. In many ways, it acts like the Presenter in MVP, but instead of coding to an interface it provides properties that can be subscribed to. Jeremiah Morril has written a <a title="MVVM and What it Means to Me" href="http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/432/MVVM-for-Tarded-Folks-Like-Me-or-MVVM-and-What-it-Means-to-Me.aspx">code-based introduction to MVVM</a> that explains the method in much more detail.</p>
<p>A UserViewModel will act much like the Presenter above but instead of setting the properties on an IUserView object, it will set properties on itself. The SilverlightUserView will pick those up and update the interface by itself.</p>
<p>MVVM works when you are using Silverlight or WPF. The ViewModel conversions will be designed for Views written on those frameworks to consume. In other ways, it works in the same way as MVP. <a title="The MVVM Pattern Is Highly Overrated" href="http://davybrion.com/blog/2010/07/the-mvvm-pattern-is-highly-overrated/">However, it has been noted by Davy Brion</a> that adding conversion logic to a Presenter may violate the <a title="Single Responsibility Principle on Wikipedia" href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>.</p>
<p><span style="font-size: 20px; font-weight: bold;">Summary</span></p>
<p>The approach you choose to separate business and UI logic is driven by one distinct choice. Do you care about presenting actions or data to the user. If you want to give someone actions and use the domain model to support that, go with MVC. If you want to to start with data and let the user take actions that relate to what they can see, go for MVP (or MVVM if you are on Silverlight/WPF).</p>
<p>What approach do you use and what for?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/02/25/what-are-mvvm-mvp-and-mvc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spend More, Reduce Costs</title>
		<link>http://www.patternwebsolutions.com/2011/02/08/spend-more-reduce-costs/</link>
		<comments>http://www.patternwebsolutions.com/2011/02/08/spend-more-reduce-costs/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 13:09:49 +0000</pubDate>
		<dc:creator>Simon Gill</dc:creator>
				<category><![CDATA[Essays]]></category>

		<guid isPermaLink="false">http://www.patternwebsolutions.com/?p=25</guid>
		<description><![CDATA[There are many ways to reduce costs but most require investment. This is possible, even in an environment that seems hostile to spending more money. All it takes, is people willing to actually look at systems and change how they work. 

In this article, I look at one example of how small changes can have big ramifications.]]></description>
			<content:encoded><![CDATA[<p>It should be a simple system for a large government organisation. Book a customer an appointment in one of many satellite offices at a particular time on a particular day. Why would someone create an Excel spreadsheet on a shared drive to solve this problem? What are the invisible costs of approaching IT systems in this way?</p>
<p>A little background first. I recently fell into the social safety net for various reasons. As a result, I&#8217;ve seen some of the effects of the new austerity measures on the provision of welfare in England.</p>
<p>First of all, the IT infrastructure hasn&#8217;t been refreshed in a number of years. That&#8217;s OK because these machines shouldn&#8217;t need to run lots of memory- or processor-hungry applications. The advisers shouldn&#8217;t be working on more than accessing the back end databases and writing letters. Any systems that the Jobcentres are using should take account of the fact there are a lot of advisers and a lot of old client hardware out there.</p>
<p>The systems in current usage don&#8217;t take that basic cost constraint into account. I was dealing with a woman who apologised repeatedly for having to open and close programs because having too many open applications at the same time caused her desktop to freeze. All you could see in her taskbar were collapsed icons for the many different applications that she had to keep open to do her job. As the interview progressed, she was constantly opening and closing programs to show me new information or to make changes.</p>
<p>One program in particular caught my attention. This was an old style mainframe application being shown through a terminal emulator. Every single task that was being done required the memorisation of a different alphanumeric code to get to the right screen. For a start, there is a time cost incurred. Every 10 second switch between screens, expanded to 30 seconds because every screen switch unexpectedly required a password to be entered, is time that is not spent on helping the customer. Secondly, how much time and money is spent training people to use systems like this? How much money is spent on hiring administrators to maintain such old (and untaught) technology?</p>
<p>What really made me laugh was finding out that one of the major cost-cutting measures was not giving out little plastic wallets to each customer. These wallets are perfectly sized for the paper documentation that they use as part of the review process and make it harder to accidentally lose one of those pieces of paper.</p>
<p>The example from the opening paragraph shows how crazy this whole thing is. During the initial interview, the adviser schedules you into one of the offices in the local catchment area. To do this, she opens an Excel spreadsheet from one of the many spreadsheet links on her desktop, enters your National Insurance number (Social Security number to anybody not familiar with English government), finds the right sheet, filters the data down to open slots, overtypes &#8220;BOOKED&#8221; into one field next to the slot you choose and then presses a button. Each day, somebody at each office builds a schedule for the day, prints that out, makes sure that each desk is labelled with a box number (printed from a word document, cut to A5 size and stuck to the cubicle wall with sellotape) and distributes it to each of the large number of advisers per office.</p>
<p>At first look, the big cost is the time spent entering the data. But there is plenty of waste elsewhere in the system too, from the over-use of paper to the time spent manually managing the schedules. This system is probably stable by now, but there still needs to be someone available in case of emergency.</p>
<p>What I propose is a module that is part of an over-arching system. This module would already know the national insurance number of the interviewee and their address so it can display the open slots for the appropriate office and the appropriate day for that person. Then, the adviser simply needs to select the time slot chosen by the interviewee and click next. In the offices, schedules can be checked by looking at the data on a screen at the front desk instead of books full of paper for each day.</p>
<p>For those that are more persuaded by the financial numbers than this summary of a systems analysis &#8211; consider these approximate statistics. In December 2010 there were 1.456 million claimants of JSA. Every one of these should have visited a job centre office twice in that time. If one person in a thousand makes a change to their appointment time and one in a hundred of those changes results in a mistake that is still 145 mistakes a fortnight across the country. Assume that a mistake costs 20 man-minutes at the minimum wage rate of £5.93 and that means that £22 thousand pounds a year are spent dealing with these avoidable situations.</p>
<p>Of course, that&#8217;s just mistakes. Look at the cost of printed schedules. Assume an office prints an average 10 pages each day for their schedules. If a page costs 10 pence, then across the fortnight, each office would spend £20 on printing those schedules. Across all 141,ooo individual offices that means £1.41 million in printing costs! Of course, electricity isn&#8217;t free, so you won&#8217;t save all £1.41 million by switching to an electronic monitor based system. In comparison, assuming a reasonable kWh cost of 9.7p, one extra monitor for all 141 thousand job centre offices will cost approximately 0.1 million pounds. That is a factor of ten reduction in costs, just from one change!</p>
<p>All this is back of the envelope math. How much do you think you would spend to figure out if it is worth it? How much would you spend if these savings turn out to be possible? How much more do you think could be saved if an end-to-end rebuild was done?</p>
<p>There are many ways to reduce costs but most require investment. This is possible, even in an environment that seems hostile to spending more money. All it takes is people willing to actually understand systems and change them for the better.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.patternwebsolutions.com/2011/02/08/spend-more-reduce-costs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

