<?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>Elegant Code &#187; StructureMap</title>
	<atom:link href="http://elegantcode.com/tag/structuremap/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>StructureMap and SharePoint</title>
	<atom:link href="http://elegantcode.com/tag/structuremap/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>Elegant Code &#187; StructureMap</title>
	<atom:link href="http://elegantcode.com/tag/structuremap/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>StructureMap and SharePoint</title>
		<link>http://elegantcode.com/2009/11/09/structuremap-and-sharepoint/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=structuremap-and-sharepoint</link>
		<comments>http://elegantcode.com/2009/11/09/structuremap-and-sharepoint/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 18:00:22 +0000</pubDate>
		<dc:creator>Tony Rasa</dc:creator>
				<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[StructureMap]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/09/structuremap-and-sharepoint/</guid>
		<description><![CDATA[I’ve started doing some SharePoint development and have brought some of my favorite tools and practices with me.&#160; Like unit tests.&#160; And IoC.&#160; And that other SOLID stuff.&#160; I’m writing a very basic WebPart to get started with SharePoint – this web part will display a list of links to other applications that the user [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve started doing some SharePoint development and have brought some of my favorite tools and practices with me.&#160; Like unit tests.&#160; And IoC.&#160; And that other SOLID stuff.&#160; </p>  <p>I’m writing a very basic WebPart to get started with SharePoint – this web part will display a list of links to other applications that the user is authorized to use.&#160; The source of this data (names, URLs, etc.) comes from an external-to-SharePoint system, accessed through another C# assembly.&#160; Once the web part gets the data there is some more processing to be done – we need to do more than just blindly display a list of URLs.&#160; Rather than get into details I’m just going to do some handwaving here and say that “if you have access to X, then {stuff happens}, or if you have access to Y then {other stuff happens}.”&#160; You know, business logic, stuff that is good to test.</p>  <p>the first thing I need to do is get business logic out of the WebPart and into something that I can write without having to reset AppPools over and over, not to mention have some unit tests to verify I’m going in the right direction.&#160; So, I created a standard application service class which has a dependency on the external authorization system, via constructor injection.&#160; </p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> AuthorizedAppsService : IAuthorizedAppsService
{
  <span class="kwrd">private</span> <span class="kwrd">readonly</span> ExternalAuthorizeService authService;

  <span class="kwrd">public</span> AuthorizedAppsService(
    ExternalAuthorizeService authService) 
  {
    <span class="kwrd">this</span>.authService = authService;
  }

  <span class="kwrd">public</span> AuthorizedApplications GetAuthorizedApplications(
                                  <span class="kwrd">string</span> userName)
  {
    var allApps = authService.AuthorizedApplications(userName);
    <span class="rem">// business logic stuff happens here</span>
    <span class="kwrd">return</span> thoseResultsWeJustFiguredOut;
  }
}</pre>

<p>Next, I created a StructureMap Registry class to scan my assemblies, as well as adding in the details of how to create this external authorize service, using the typical method: <style type="text/css">




.csharpcode, .csharpcode pre
{
	font-size: x-small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyRegistry : Registry
{
  <span class="kwrd">public</span> MyRegistry()
  {
    Scan(scanner =&gt; {
      scanner.TheCallingAssembly();
      scanner.AssemblyContainingType(<span class="kwrd">typeof</span>(MyRegistry));
      scanner.WithDefaultConventions();
      });

    ForRequestedType&lt;ExternalAuthorizeService&gt;()
      .AsSingletons()
      .TheDefault.Is.ConstructedBy(c =&gt; Provider.GetService());

    <span class="rem">// other dependency configuration...</span>
  }
  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> InitializeForSharepoint()
  {
    ObjectFactory.Initialize(init =&gt; init.AddRegistry&lt;MyRegistry&gt;());
    ObjectFactory.AssertConfigurationIsValid();
  }
}</pre>

<p>And then, what remains is to have SharePoint call my StructureMap initialization when my SharePoint application starts up.&#160; In an MVC or WebForms app, I’d just add code to the appropriate place in Global.asax.cs, but in SharePointLand, this is looked down on.&#160; Instead, the preferred mechanism seems to be to use an HttpModule and a FeatureReceiver to plug the Module into the app’s web.config.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyStartupModule : IHttpModule
{
  <span class="kwrd">public</span> <span class="kwrd">void</span> Init(HttpApplication context)
  {
        ConfigureOtherStuff();
        MyRegistry.InitializeForSharepoint();
  }
  <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose() { }
}</pre>

<p>And then the FeatureReceiver to alter the app’s Web.Config looks something like this (note I borrowed most of this code from another sample SharePoint project:</p>

<p>&#160;</p>

<pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// this is borrowing heavily from http://www.codeplex.com/SPAXO</span>
<span class="rem">// </span>
<span class="kwrd">public</span> <span class="kwrd">class</span> StartupFeatureReceiver : SPFeatureReceiver
{
  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> FeatureActivated(
        SPFeatureReceiverProperties properties)
  {
    var webApp = properties.Feature.Parent <span class="kwrd">as</span> SPWebApplication;
    AddWebConfigEntry(webApp);
    UpdateApp(webApp);
  }

  <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> FeatureDeactivating(
        SPFeatureReceiverProperties properties)
  {
    var webApp = properties.Feature.Parent <span class="kwrd">as</span> SPWebApplication;
    RemoveWebConfigEntry(webApp);
    UpdateApp(webApp);
  }


  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> AddWebConfigEntry(SPWebApplication webApp)
  {
    SPWebConfigModification mod = GetModification();
    var existingModifications = 
             <span class="kwrd">new</span> List&lt;SPWebConfigModification&gt;(
                      webApp.WebConfigModifications);
    <span class="kwrd">if</span> (existingModifications.FindIndex(
                    <span class="kwrd">value</span> =&gt;
                        <span class="kwrd">value</span>.Name == mod.Name &amp;&amp;
                        <span class="kwrd">value</span>.Value == mod.Value &amp;&amp;
                        <span class="kwrd">value</span>.Owner == mod.Owner) == -1)
    {
      <span class="rem">// If the modifcation does not already exist </span>
      <span class="rem">// add the entry to the config</span>
      webApp.WebConfigModifications.Add(mod);
    }
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RemoveWebConfigEntry(
            SPWebApplication webApp)
  {
    SPWebConfigModification mod = GetModification();
    webApp.WebConfigModifications.Remove(mod);
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> SPWebConfigModification GetModification()
  {
    <span class="kwrd">string</span> asmName = <span class="kwrd">typeof</span>(StartupModule).AssemblyQualifiedName;
    <span class="kwrd">string</span> typeName = <span class="kwrd">typeof</span>(StartupModule).FullName;

    <span class="kwrd">return</span> <span class="kwrd">new</span> SPWebConfigModification
      {
        Path = <span class="str">&quot;configuration/system.web/httpModules&quot;</span>,
        Name = String.Format(CultureInfo.InvariantCulture,
                <span class="str">&quot;add[@name='{0}'][@type='{1}']&quot;</span>,
                typeName, asmName),
        Sequence = 0,
        Owner = asmName,
        Type = SPWebConfigModification.
                    SPWebConfigModificationType.EnsureChildNode,
        Value = String.Format(CultureInfo.InvariantCulture,
                  <span class="str">&quot;&lt;add name='{0}' type='{1}' /&gt;&quot;</span>,
                  typeName, asmName)
      };
  }

  <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> UpdateApp(SPWebApplication webApp)
  {
    <span class="rem">// Update the Web App and apply the changes </span>
    <span class="rem">// to all servers in the farm</span>
    webApp.Update();
    webApp.Farm.Services
        .GetValue&lt;SPWebService&gt;()
        .ApplyWebConfigModifications();
  }
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/09/structuremap-and-sharepoint/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

