<?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>Jason Rowe &#187; .Net</title>
	<atom:link href="http://jasonrowe.com/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://jasonrowe.com</link>
	<description>enjoying the web</description>
	<lastBuildDate>Sun, 13 May 2012 14:05:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>NetMsmqBinding Brain Dump</title>
		<link>http://jasonrowe.com/2012/05/13/netmsmqbinding-brain-dump/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=netmsmqbinding-brain-dump</link>
		<comments>http://jasonrowe.com/2012/05/13/netmsmqbinding-brain-dump/#comments</comments>
		<pubDate>Sun, 13 May 2012 06:14:28 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSMQ]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1940</guid>
		<description><![CDATA[I started experimenting with WCF&#8217;s NetMsmqBinding and found the abstraction to be a bit tricky. WCF takes care of all the MSMQ details and all you need to do is define the contract and do configuration. The following are some &#8230; <a href="http://jasonrowe.com/2012/05/13/netmsmqbinding-brain-dump/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p> I started experimenting with WCF&#8217;s NetMsmqBinding and found the abstraction to be a bit tricky. WCF takes care of all the MSMQ details and all you need to do is define the contract and do configuration. The following are some notes about that process.</p>

<h3>Links</h3>
<p><a href="http://blogs.msdn.com/b/tomholl/archive/2008/07/12/msmq-wcf-and-iis-getting-them-to-play-nice-part-1.aspx">msmq wcf and iis getting them to play nice</a></p>
<p><a href="http://code.google.com/p/autofac/wiki/WcfIntegration#WAS_Hosting_and_Non-HTTP_Activation">AutoFac WAS Hosting and Non-HTTP Activation</a></p>

<h3>Windows Components Installed</h3>
<p>Microsoft Message Queue (MSMQ) Server > MSMQ Server Core</p>
<p>Microsoft .NET Framework > Windows Communication Foundation Non-HTTP Activation</p>

<h3>IIS 7 Configuration</h3>
<ol>
<li>Add net.msmq to the list of enabled protocols. In IIS, Web App -> Advanced Settings -> Enabled Protocols. It is a comma separated list (http,net.msmq).</li>
<li>Make sure Client and Service have correct permissions to access the private queue</li>
</ol>

<h3>MSMQ Config</h3>
<p>Add NETWORK SERVICE to the new MSMQ (windows 7 that is in Computer Managment -> Services and Applications -> Message Queuing</p>

<h3>C# code to create initialize private queue</h3>
<p>The queue name must match the URI of your service&#8217;s .svc file according to <a href="http://blogs.msdn.com/b/tomholl/archive/2008/07/12/msmq-wcf-and-iis-getting-them-to-play-nice-part-1.aspx">this</a></p>

<pre class="brush: csharp; title: ; notranslate">
  // Create and connect to a private Message Queuing queue.
if (!MessageQueue.Exists(@&quot;.\Private$\JangoFettClient/CloneService.svc&quot;))
{
    // Create the queue if it does not exist.
    MessageQueue.Create(@&quot;.\Private$\JangoFettClient/CloneService.svc&quot;);
}
</pre>

<h3>Example Service Config</h3>

<pre class="brush: xml; title: ; notranslate">
&lt;bindings&gt;
    &lt;netMsmqBinding&gt;
        &lt;binding name=&quot;MsmqBindingNonTransactionalNoSecurity&quot;
                        exactlyOnce=&quot;false&quot;&gt;
            &lt;security mode=&quot;None&quot;/&gt;
        &lt;/binding&gt;
    &lt;/netMsmqBinding&gt;
&lt;/bindings&gt;
&lt;services&gt;
&lt;service name=&quot;JangoFettClient.CloneService&quot;&gt;
    &lt;endpoint name=&quot;msmq&quot; 
              address=&quot;net.msmq://localhost/private/JangoFettClient/CloneService.svc&quot;
              binding=&quot;netMsmqBinding&quot; 
              bindingConfiguration=&quot;MsmqBindingNonTransactionalNoSecurity&quot;
              contract=&quot;JangoFettClient.ICloneOrderProcessor&quot; /&gt;
&lt;/service&gt;
&lt;/services&gt;
</pre>

<h3>Example Service</h3>
<p>Example of data contract that would automatically become the listener and pull the items from MSMQ via WCF</p>
<pre class="brush: csharp; title: ; notranslate">
namespace JangoFettClient
{
    public class CloneService : ICloneOrderProcessor
    {
        private readonly ILog _logger;

        public CloneService(ILog logger)
        {
            _logger = logger;
        }

        public void SendMessage(CloneOrder request)
        {
            _logger.Info(&quot;Message received from MSMQ&quot;);
        }
    }
}
</pre>

<h3>Errors with easy fixes</h3>
<p>The protocol &#8216;net.msmq&#8217; is not supported. Add net.msmq to the list of enabled protocols. See IIS 7 Configuration above for more information.</p>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2012/05/13/netmsmqbinding-brain-dump/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Right Click Add To Path</title>
		<link>http://jasonrowe.com/2012/04/25/right-click-add-to-path/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=right-click-add-to-path</link>
		<comments>http://jasonrowe.com/2012/04/25/right-click-add-to-path/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 03:03:41 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[General Programming]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1839</guid>
		<description><![CDATA[I do lots of installs on my windows machine and got tired of having to change the path environment variables manually. I created a AddPath.exe that will do this for me and added a short cut to the right click &#8230; <a href="http://jasonrowe.com/2012/04/25/right-click-add-to-path/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<a href="http://jasonrowe.com/wp-content/uploads/2012/04/addpath.png"><img src="http://jasonrowe.com/wp-content/uploads/2012/04/addpath.png" alt="" title="addpath" width="236" height="93" class="alignleft size-full wp-image-1840" /></a>

<p>I do lots of installs on my windows machine and got tired of having to change the path environment variables manually. I created a AddPath.exe that will do this for me and added a short cut to the right click context menu. </p>

<p>In one right click I can get this result:</p>
<a href="http://jasonrowe.com/wp-content/uploads/2012/04/addpathresult.png"><img src="http://jasonrowe.com/wp-content/uploads/2012/04/addpathresult.png" alt="" title="addpathresult" width="355" height="151" class="alignnone size-full wp-image-1878" /></a>



<p>Here is how it works if you are interested:</p>
<ol>
<li>Compile Code Via &#8211; git@github.com:JasonRowe/AddPath.git or <a href="http://jasonrowe.com/misc/AddPath.zip">Download the zip file</a>.</li>
<li>Put the executable (AddPath.exe) and the dependency file (System.dll) into C:\tools\</li>
<li>This executable needs to run as Admin. Right click on AddPath.exe, click compatibility tab and select &#8220;run this program as an administrator&#8221;</li>
</ol>

<p>To add the right click context menu you need to add a new key to the registry</p>

<img src="http://jasonrowe.com/wp-content/uploads/2012/04/AddPathReg1.png" alt="" title="AddPathReg" width="664" height="229" class="alignleft size-full wp-image-1863" />

<ol>
<li>open the registry editor (Start -> Run -> regedit.exe)</li>
<li>Find the key HKEY_CLASSES_ROOT\Folder. Create a new key named shell if its not already there (HKEY_CLASSES_ROOT\Folder\shell)</li>
<li>In the shell key (possibly just created) create a new key and change its name AddPath or whatever you want to show in the context menu</li>
<li>Under the new key create a new key named command (HKEY_CLASSES_ROOT\Folder\shell\AddPath\command) and change its default value C:\tools\AddPath.exe &#8220;%1&#8243;</li>
</ol>

That %1 in quotes becomes the folder path and is passed to AddPath.exe as a parameter. Here is what the code is doing with the path that is passed in:

<pre class="brush: csharp; title: ; notranslate">
 public static void AddPathSegments(Options options)
        {
            try
            {
                string allPaths = Environment.GetEnvironmentVariable(&quot;PATH&quot;, options.Target);
                if (allPaths != null)
                    allPaths = options.PathSegment + &quot;; &quot; + allPaths;
                else
                    allPaths = options.PathSegment;
                Environment.SetEnvironmentVariable(&quot;PATH&quot;, allPaths, options.Target);

                Console.WriteLine(&quot;Added path segment: {0}&quot;, options.PathSegment);
            }
            catch (Exception ex)
            {
                Console.WriteLine(&quot;could not add path segment: {0} -  error {1}&quot;, 
                                   options.PathSegment, ex);
            }
        }
</pre>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2012/04/25/right-click-add-to-path/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ejabberd offline messages</title>
		<link>http://jasonrowe.com/2011/12/30/ejabberd-offline-messages/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ejabberd-offline-messages</link>
		<comments>http://jasonrowe.com/2011/12/30/ejabberd-offline-messages/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 22:58:26 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[XMPP]]></category>
		<category><![CDATA[ejabberd]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[offline messages]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1600</guid>
		<description><![CDATA[The following is how I created a custom ejabberd module to POST offline messages to a web application. I should mention this is not production ready I&#8217;ve only just started working with Erlang and the XMPP server ejabberd. The main &#8230; <a href="http://jasonrowe.com/2011/12/30/ejabberd-offline-messages/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The following is how I created a custom ejabberd module to POST offline messages to a web application. I should mention this is not production ready I&#8217;ve only just started working with Erlang and the XMPP server ejabberd. The main reason I&#8217;m experimenting with XMPP is to provide apple push notifications once a user closes an iPhone application. My day job is programming in C# so this is going to be from a Windows .Net developer perspective.</p>

<p>Why use ejabberd which is written in a wacky language called Erlang? Well&#8230; you will have to decide for yourself. Erlang is a functional programming language which is known for concurrency and high reliability. Also, it&#8217;s the <a href="https://github.com/languages/Erlang">24th most popular language on GitHub</a> as of writting this so it can&#8217;t be that bad. :)</p>

<p>If you don&#8217;t have ejabberd setup yet see my <a href="http://jasonrowe.com/2011/11/18/strophejs-ejabberd-iis-setup/">previous post</a> on getting strophejs, ejabberd, and IIS all working together.</p>

<p>Step one, take a deep breath and get up to speed on XMPP, ejabberd, and Erlang. Easy right?
Don&#8217;t worry, it will all come together by the end of this post. Well, at least you will write some Erlang by the end of the post. Here are some resource to have handy.</p>

<p><strong>Books:</strong></p>
<ol>
	<li><a href="http://learnyousomeerlang.com/introduction">Learn You Some Erlang</a></li>
	<li><a href="http://books.google.com/books?id=SG3jayrd41cC&#038;dq=xmpp">XMPP, the definitive guide</a></li>
</ol>

<p>Let&#8217;s start with getting the Erlang environment up and running. You need Erlang to compile the new module. The Erlang version is important because it should match the one used in the installed ejabberd server. What version of Erlang was used with your installed ejabberd? You can find that information here using your ejabberd version number (if you don&#8217;t know the version number skip ahead to the next section before following this link): <a href="http://www.ejabberd.im/erlang">http://www.ejabberd.im/erlang</a>.</p>

<p><strong>If you don&#8217;t know your ejabberd version here is how to get it.</strong></p>

<p>Go to start, run, and type cmd to open a command prompt. CD to your ejabberd\bin folder. 
Mine in &#8220;D:\Program Files (x86)\ejabberd-2.1.9\bin&#8221;. Then run the following command:</p>

<code>ejabberdctl status</code>

<p>You should see something like this &#8220;The node ejabberd@localhost is started with status: started
ejabberd 2.1.9 is running in that node&#8221;</p>


<strong>Note on ejabberd start error and erlang cookie</strong>
<p>If you you get an error like the following <strong>&#8220;Failed RPC connection to the node ejabberd@localhost: nodedown&#8221;</strong> 
Try to run the start command:</p>

<code>ejabberdctl start</code>

<p>If you get the same error when trying to start you might have a &#8220;.erlang.cookie&#8221; mismatch. On my box ejabberd runs using the
erlang cookie from &#8220;C:\Windows\.erlang.cookie&#8221;. This needs to match the one in your user folder. My Erlang cookie is located here:
&#8220;C:\Users\rowej\.erlang.cookie&#8221;. If you are getting the error mentioned, copy your erlang cookie from the windows folder
into your user folder.</p>

<p>Now that you have the ejabberd version go to <a href="http://www.ejabberd.im/erlang">ejabberd official site</a> and see which version of erlang was used. This is important so you are using the same
version when you compile your module.</p>

<p>Now open your favorite text editor. I recommend Sublime Text 2 with Erlang syntax highlighting turned on. Also, there are several choices of plugins for NetBeans or Eclipse. The officially recommended IDE is Erlang mode for Emacs.</p>


<p>The next step is to get a basic module installed and make sure it is working. Lets start with a very simple module that does nothing but logs out information. Finally, time to start coding!</p>

<p>Create a file named mod_http_offline.erl.</p>

<p>Lets start with a very simple module that just does logging. This should give us a good idea of how ejabberd handles modules. Fill in the file you created &#8220;mod_http_offline.erl&#8221; with the following code:</p>


<pre class="brush: erlang; title: ; notranslate">

%% name of module must match file name
-module(mod_http_offline).

-author(&quot;Earl The Squirrel&quot;).

%% Every ejabberd module implements the gen_mod behavior
%% The gen_mod behavior requires two functions: start/2 and stop/1
-behaviour(gen_mod).

%% public methods for this module
-export([start/2, stop/1, create_message/3]).

%% included for writing to ejabberd log file
-include(&quot;ejabberd.hrl&quot;).

%% ejabberd functions for JID manipulation called jlib.
-include(&quot;jlib.hrl&quot;).

start(_Host, _Opt) -&gt; 
		post_offline_message(&quot;testFrom&quot;, &quot;testTo&quot;, &quot;testBody&quot;),
		?INFO_MSG(&quot;mod_http_offline loading&quot;, []),
		ejabberd_hooks:add(offline_message_hook, _Host, ?MODULE, create_message, 50).   



stop (_Host) -&gt; 
		?INFO_MSG(&quot;stopping mod_http_offline&quot;, []),
		ejabberd_hooks:delete(offline_message_hook, _Host, ?MODULE, create_message, 50).



create_message(_From, _To, Packet) -&gt;
		Type = xml:get_tag_attr_s(&quot;type&quot;, Packet),
		FromS = xml:get_tag_attr_s(&quot;from&quot;, Packet),
		ToS = xml:get_tag_attr_s(&quot;to&quot;, Packet),
		Body = xml:get_path_s(Packet, [{elem, &quot;body&quot;}, cdata]),
		if (Type == &quot;chat&quot;) -&gt;
			post_offline_message(FromS, ToS, Body)
		end.



post_offline_message(From, To, Body) -&gt;
		?INFO_MSG(&quot;Posting From ~p To ~p Body ~p~n&quot;,[From, To, Body]),
		?INFO_MSG(&quot;post request sent (not really yet)&quot;, []).
</pre>

<p>Now lets get the necessary include files to compile the code. You will have to go to the <a href="http://www.process-one.net/en/ejabberd/downloads/">ejabberd site and download the src</a>.</p>

<p>select &#8220;source code&#8221; from the drop down list. Then use a tool like <a href="http://tartool.codeplex.com/">TarTool</a> to unzip it. Copy jlib.hrl and ejabberd.hrl into the same folder where where you created the module source mod_http_offline.erl</p>

<p>Now open the erlang shell (programs > Erlang), type in:</p>

<p><strong>Remember you must use a slash (forward slash). If you cut and paste from windows explorer you will get back slashes and you won&#8217;t be able to change directories.</strong></p>

<code>cd("path/to/where.you/saved/the-module").</code>

<p>Then compile by doing the following:</p>
<code>c(mod_http_offline).</code>

<p>You should see this result and a .beam file now created in the directory:</p>
<code>./mod_http_offline.erl:8: Warning: behaviour gen_mod undefined</code>

<p>Shut down ejabberd server and copy the resulting .beam file to the directory where all the other ejabberd .beam files are.
\ejabberd-2.1.9\lib\ejabberd-2.1.9\ebin</p>

<p>Configure ejabberd to enable this module via the ejabberd.cfg. Add it to the list of modules in the Module section.</p>
<code>{mod_http_offline,    []}</code>

<p>Start up eJabberd.</p> 

<p>After it starts lets examine the log files to see if our module loaded.
example\path\ejabberd-2.1.9\logs\ejabberd.log</p> 

<p>You should see the following log entries:</p> 

<code>=INFO REPORT==== 2011-12-30 14:55:27 ===
I(<0.36.0>:mod_http_offline:44) : Posting From "testFrom" To "testTo" Body "testBody"

=INFO REPORT==== 2011-12-30 14:55:27 ===
I(<0.36.0>:mod_http_offline:45) : post request sent (not really yet)

=INFO REPORT==== 2011-12-30 14:55:27 ===
I(<0.36.0>:mod_http_offline:21) : mod_http_offline loading</code>

<p>Now we can have fun and send some offline messages. Get two XMPP clients running logged in with two different users. I used my admin account created during the ejabberd setup and a new test account created via the ejabberd Web Admin. I used the agxXMPP client to send messages back and forth but you can use which ever XMPP client is easier for you. You can find a list of them on the official <a href="http://xmpp.org/xmpp-software/clients/">XMPP website client list</a>. Send a few message to a user who is not connected (offline) and check your ejabberd.log file.(example\path\ejabberd-2.1.9\logs\ejabberd.log). Here is what mine looks like after sending a Hello world message.</p>

<code>
=INFO REPORT==== 2011-12-30 13:31:25 ===
I(<0.493.0>:mod_http_offline:44) : Posting From [] To "test@localhost.demo.com" Body "hello world"</code>

<p>Shut down ejabberd and setup a page to handle HTTP POST&#8217;s via Erlang. use your favorite web framework for the page it really doesn&#8217;t matter. If you are using MVC .Net it might look somethign like this.</p>

<pre class="brush: csharp; title: ; notranslate">
 [HttpPost]
        public ActionResult Process()
        {
            var formValues = Request.Form;

            string from;
            string to;
            string body;

            if (!string.IsNullOrEmpty(formValues[&quot;From&quot;]))
            {
                from = formValues[&quot;From&quot;];
            }

            if (!string.IsNullOrEmpty(formValues[&quot;To&quot;]))
            {
                to = formValues[&quot;To&quot;];
            }

            if (!string.IsNullOrEmpty(formValues[&quot;Body&quot;]))
            {
                body = formValues[&quot;Body&quot;];
            }
</pre>

<p>Then from the Erlang console send a post to make sure everything is working with this command:</p>

http:request(post, {&#8220;http://localhost/OfflineDemoWebhost/Message/Process&#8221;,[], &#8220;application/x-www-form-urlencoded&#8221;,&#8221;From=earl the squirrel&#038;To=you&#038;Body=Hello World&#8221;}, [], [])


<p>If you see a response starting with this you are good to go.</p>
<pre class="brush: bash; title: ; notranslate">{ok,{{&quot;HTTP/1.1&quot;,200,&quot;OK&quot;},</pre>

<p><strong>
Now lets change the module to send the post adding in a few more lines of code.</strong></p>

<pre class="brush: erlang; title: ; notranslate">
%% name of module must match file name
-module(mod_http_offline).

-author(&quot;Earl The Squirrel&quot;).

%% Every ejabberd module implements the gen_mod behavior
%% The gen_mod behavior requires two functions: start/2 and stop/1
-behaviour(gen_mod).

%% public methods for this module
-export([start/2, stop/1, create_message/3]).

%% included for writing to ejabberd log file
-include(&quot;ejabberd.hrl&quot;).

%% ejabberd functions for JID manipulation called jlib.
-include(&quot;jlib.hrl&quot;).

start(_Host, _Opt) -&gt; 
		?INFO_MSG(&quot;mod_http_offline loading&quot;, []),
		inets:start(),
		?INFO_MSG(&quot;HTTP client started&quot;, []),
		post_offline_message(&quot;testFrom&quot;, &quot;testTo&quot;, &quot;testBody&quot;),
		ejabberd_hooks:add(offline_message_hook, _Host, ?MODULE, create_message, 50).   



stop (_Host) -&gt; 
		?INFO_MSG(&quot;stopping mod_http_offline&quot;, []),
		ejabberd_hooks:delete(offline_message_hook, _Host, ?MODULE, create_message, 50).



create_message(_From, _To, Packet) -&gt;
		Type = xml:get_tag_attr_s(&quot;type&quot;, Packet),
		FromS = xml:get_tag_attr_s(&quot;from&quot;, Packet),
		ToS = xml:get_tag_attr_s(&quot;to&quot;, Packet),
		Body = xml:get_path_s(Packet, [{elem, &quot;body&quot;}, cdata]),
		if (Type == &quot;chat&quot;) -&gt;
			post_offline_message(FromS, ToS, Body)
		end.



post_offline_message(From, To, Body) -&gt;
		?INFO_MSG(&quot;Posting From ~p To ~p Body ~p~n&quot;,[From, To, Body]),
		 http:request(post, {&quot;http://localhost/OfflineDemoWebhost/Message/Process&quot;,[], 
		 &quot;application/x-www-form-urlencoded&quot;,
		 lists:concat([&quot;From=&quot;, From,&quot;&amp;To=&quot;, To,&quot;&amp;Body=&quot;, Body])}, [], []),
		?INFO_MSG(&quot;post request sent&quot;, []).
</pre>

<p>Shut down ejabberd again and recompile. Copy the beam file overitting the old version. Now start up the server and you should have offline messages posting to your web application.</p>
]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2011/12/30/ejabberd-offline-messages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Factory Pattern using Windsor and MVC</title>
		<link>http://jasonrowe.com/2011/07/15/factory-pattern-using-windsor-and-mvc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=factory-pattern-using-windsor-and-mvc</link>
		<comments>http://jasonrowe.com/2011/07/15/factory-pattern-using-windsor-and-mvc/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 21:56:56 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Named]]></category>
		<category><![CDATA[Typed Factory]]></category>
		<category><![CDATA[Windsor]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1477</guid>
		<description><![CDATA[I ran into a situation where I wanted to return a dynamically drawn image based on the file name . For example, if someone requested somedomain.com/image/legacypage42.foo the &#8220;legacypage42.foo&#8221; would be the name of the Windsor component used to draw the &#8230; <a href="http://jasonrowe.com/2011/07/15/factory-pattern-using-windsor-and-mvc/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[I ran into a situation where I wanted to return a dynamically drawn image based on the file name . For example, if someone requested somedomain.com/image/legacypage42.foo the &#8220;legacypage42.foo&#8221; would be the name of the Windsor component used to draw the image. The first thing I needed to do was change that page into a parameter which is very simple with MVC .net routing:

<pre class="brush: csharp; title: ; notranslate">  
routes.MapRoute(&quot;MyImageRoute&quot;,
                &quot;image/{filename}&quot;,
                new { controller = &quot;Images&quot;, action = &quot;Index&quot; });
</pre>

So now filename becomes the parameter in the controller. Now comes the tricky part. How to resolve a component in Windsor by name. Windsor does allow you to set the name using this syntax:

<pre class="brush: csharp; title: ; notranslate">  
kernel.Register(
    Component.For&lt;IMyImageComponent&gt;()
        .ImplementedBy&lt;MyImageComponent&gt;()
        .Named(&quot;SomeImage&quot;));
</pre>

Although, using that syntax is going to make for a nightmare if I have many different image components so I&#8217;ll use the built in <a href="http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx">Windsor Type Factory</a>. The first step is to cleanly register all my image components setting the name. To do that I created an interface all my images will use so I can easily set the named value.

<pre class="brush: csharp; title: ; notranslate">  
Interface example:

    public interface IMyImageComponent
    {
        Bitmap BuildImage();

        string GetFileName();
    }
</pre>

Here is how I use the interface to setup my Windsor components and named values.

<pre class="brush: csharp; title: ; notranslate">  
var type = typeof(IMyImageComponent);
var styles = AppDomain.CurrentDomain.GetAssemblies().ToList()
        .SelectMany(s =&gt; s.GetTypes())
        .Where(type.IsAssignableFrom);

    foreach (var style in styles)
    {
        if (!style.IsClass || style.IsNotPublic || style.IsAbstract) 
            continue;

        object o = Activator.CreateInstance(style);
        var propertyInfo = style.GetMethod(&quot;GetFileName&quot;);
        var name = (string)propertyInfo.Invoke(o, null);
        container.Register(Component.For&lt;IMyImageComponent&gt;()
                    .ImplementedBy(o.GetType()).Named(name));
</pre>

If you want to use the power of Windsor inside your classes that implement IMyImageComponent. You could use the following instead. The only downside is you have to register the components twice in Windsor but only on the initial start up.

<pre class="brush: csharp; title: ; notranslate">  

container.Register(AllTypes.FromAssembly(typeof(YourClassNameHere).Assembly)
               .BasedOn&lt;IMyImageComponent&gt;());

var myImageStyles = container.ResolveAll&lt;IMyImageComponent&gt;();

var myImageTypes = myImageStyles .Select(style =&gt; style.GetType()).ToList();

foreach (var type in myImageTypes )
{
    object o = container.Resolve(type);
    var propertyInfo = type.GetMethod(&quot;GetFileName&quot;);
    var name = (string)propertyInfo.Invoke(o, null);
    container.Register(Component.For&lt;IMyImageComponent&gt;()
        .ImplementedBy(o.GetType()).Named(name));
}
</pre>

Here is how the factory was initialized:

<pre class="brush: csharp; title: ; notranslate">  
container.Register(Component.For&lt;ITypedFactoryComponentSelector&gt;()
         .ImplementedBy&lt;ImageStyleFactorySelector&gt;().Named(&quot;ImageStyleFactorySelector&quot;));

container.Register(Component.For&lt;IMyImageTemplateFactory&gt;()
         .AsFactory(c =&gt; c.SelectedWith(&quot;ImageStyleFactorySelector&quot;)));
</pre>

Notice I used a custom selector in the factory. This is used when the factory is looking up the components. Here is what the FactorySelector looks like.

<pre class="brush: csharp; title: ; notranslate">  
public class ImageStyleFactorySelector : DefaultTypedFactoryComponentSelector
{
   protected override string GetComponentName(MethodInfo method, object[] arguments)
   {
       if (method.Name == &quot;GetByFileName&quot; &amp;&amp; arguments.Length == 1 &amp;&amp; arguments[0] is string)
       {
           return arguments[0].ToString();
       }
       return base.GetComponentName(method, arguments);
   }
}
</pre>

Now inside the controller I use the factory with the function &#8220;GetByFileName&#8221; which uses the custom selector to find the component.

<pre class="brush: csharp; title: ; notranslate">   
var imageComponent = _ImageTemplateFactory.GetByFileName(fileName);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2011/07/15/factory-pattern-using-windsor-and-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional Fun Calculating SMA and EMA</title>
		<link>http://jasonrowe.com/2010/09/12/functional-fun-calculating-sma-and-ema/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=functional-fun-calculating-sma-and-ema</link>
		<comments>http://jasonrowe.com/2010/09/12/functional-fun-calculating-sma-and-ema/#comments</comments>
		<pubDate>Mon, 13 Sep 2010 03:38:34 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1343</guid>
		<description><![CDATA[&#160; To try out F#I decided to make a function to calculate&#160; simple moving average (SMA) and exponential moving average (EMA).&#160; The SMA and EMA have enough math to try many of the features of F# and functional programming. The &#8230; <a href="http://jasonrowe.com/2010/09/12/functional-fun-calculating-sma-and-ema/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p> <p>To try out F#I decided to make a function to calculate&nbsp; simple moving average (SMA) and exponential moving average (EMA).&nbsp; The SMA and EMA have enough math to try many of the features of F# and functional programming. </p> <p>The first thing I learned was F# has a way to quickly execute code. If you haven’t played with F#’s Interactive it’s sort of like a <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a> loop. While coding you can highlight the code and do a Alt-Enter to execute it. It’s very convenient. </p> <p><a href="http://jasonrowe.com/wp-content/uploads/2010/09/FSharpCapture.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="FSharpCapture" border="0" alt="FSharpCapture" src="http://jasonrowe.com/wp-content/uploads/2010/09/FSharpCapture_thumb.png" width="382" height="254"></a> </p> <p>To keep with the functional style of programming I put the SMA and EMA into a type. In OO this would be the equivalent of using a base class for moving averages and then creating classes for SMA and EMA. As you can see in F# this is a very small amount of code using type declaration / discriminators. You can see comments in my code below for things I learned and picked up while doing this exercise.</p>


<pre class="brush: fsharp; title: ; notranslate"> 

type movingAverage =
  | Simple of int * seq&lt;float&gt;
  | Exponential of int * float list



// sma is an example of using a private / utility function
// pipelining operator |&gt; allows execution of a series of operations
let sma(size, seq) =                                  
    Seq.windowed size seq
    |&gt; Seq.map Array.average  



// example of Matching on discriminated unions
let calculate(movingAverage) =
    match movingAverage with

    |Simple(size, seq) -&gt; sma(size, seq)

    |Exponential(period, data) -&gt; 

            let multiplier =  2.0 / (1.0 + (float period))
            
//Calc a sum to use in the SMA to prime the EMA calculation
//http://bit.ly/bG73sx Slice like functionality from a List
            let iniSum =  
                data 
                |&gt; List.toSeq 
                |&gt; Seq.take (int period) 
                |&gt; Seq.sum

//first float from list using period as the start
            let firstItem = 
                data 
                |&gt; List.toSeq 
                |&gt; Seq.skip (int period)  
                |&gt; Seq.head 

//setup first ema with sma
            let firstEma = (iniSum / (float period))

            let out : float array = Array.zeroCreate (List.length data)

//setup initial Ema to previous day
            out.[period - 2] &lt;- firstEma

//calculate the rest of the Ema's
            for i in period - 1 .. (List.length data - 1) do
                let close = data.[i]
                let prev = out.[i - 1]
                out.[i] &lt;- multiplier * (close - prev) + prev

            Array.toSeq out

// F# Note - intrinsic type extensions adds the calculate member to the movingAverage type
type movingAverage with                                                
   member x.calculate() = calculate(x)  


//Test Simple
let simpleMovingAverage = Simple(10, (Seq.map float [|1..30|]))

let avgs = simpleMovingAverage.calculate();

for avg in avgs do
    printfn &quot;%f&quot; avg

//Test Exponential
let expMovingAverage = Exponential(10, [1.0..30.0])

let expAvgs = expMovingAverage.calculate();

for e in expAvgs do
    printfn &quot;%f&quot; e

</pre>

a big thanks to this F# <a href="http://lepensemoi.free.fr/index.php/tag/technical-analysis">technical indicator</a> series. ]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/09/12/functional-fun-calculating-sma-and-ema/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shiny New Toys, Visitor Pattern, and Real World Functional Programming</title>
		<link>http://jasonrowe.com/2010/09/06/shiny-new-toys-visitor-pattern-and-real-world-functional-programming/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=shiny-new-toys-visitor-pattern-and-real-world-functional-programming</link>
		<comments>http://jasonrowe.com/2010/09/06/shiny-new-toys-visitor-pattern-and-real-world-functional-programming/#comments</comments>
		<pubDate>Tue, 07 Sep 2010 04:21:41 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Commentary]]></category>
		<category><![CDATA[General Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1333</guid>
		<description><![CDATA[&#160; Last week in the office I thought to my self, “Holiday weekend coming! I’ll have time to play with WP7 or maybe I’ll play with HTML5”. Then I saw this tweet on twitter. We as developers spend too much &#8230; <a href="http://jasonrowe.com/2010/09/06/shiny-new-toys-visitor-pattern-and-real-world-functional-programming/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p> <p>Last week in the office I thought to my self, “Holiday weekend coming! I’ll have time to play with WP7 or maybe I’ll play with HTML5”. Then I saw this <a href="http://twitter.com/jeremydmiller/status/22798775378">tweet</a> on twitter.</p> <blockquote> <p>We as developers spend too much time playing with baubles and shiny new tools and not enough time on core skills and fundamentals</p></blockquote> <p>I thought well, instead of using some free time this holiday weekend to build something why not do a little research. I happened to have a problem at work which someone suggested using the Visitor Pattern. So I spent some time looking over a few resources and <a href="http://en.wikipedia.org/wiki/Visitor_pattern">Wikipedia</a> has a great explanation. I won’t try to repeat that. One area I was stuck on though was the concept of double dispatch. I found this <a href="http://bit.ly/bZRM74">example</a> on <a href="http://stackoverflow.com/questions/479923/is-c-a-single-dispatch-or-multiple-dispatch-language">StackOverflow.com</a> which solidified the concept. For some reason <a href="http://bit.ly/bZRM74">learning by spaceship and rebel alliance</a> works for me.</p> <p>So now that I had a good understand all I needed to was implement it right? I thought about it and figured that could wait. Now is an opportunity to work on my fundamentals. The Wikipedia article mentioned Common Lisp and how the Visitor Pattern simplified when using dynamic languages. This got me to thinking what would this look like in F# or a functional language? </p> <p>While looking into functional languages I came across this Stack Overflow question “<a href="http://stackoverflow.com/questions/3642328/i-am-a-c-developer-should-i-start-looking-more-on-f-closed">I am a C# developer, Should I start looking more on F# [closed]</a>”.&nbsp; Jon Skeet’s answer influenced me and I figured I would pick up a book <a href="http://manning.com/petricek">Real World Functional Programming</a>. It fits into the category of fundamentals because it’s using C# and F# to teach functional programming. Which I haven’t used in many years.</p> <p>So I start reading with the goal in mind that I would make a quick example of the visitor pattern in F#. Don’t think I am a super geek (not that you would be confused because of my skills). I did take time to drink a few of <a href="http://www.surlybrewing.com/beer/year-round-beers.html">these</a> and go to the Crowded House concert this weekend. By the fourth chapter or so things started to sink in with F# and functional programming. </p> <p>If I were using a declarative functional style of programming, I wouldn’t even need the visitor pattern at all!&nbsp; I don’t have objects that would need to be separated from the algorithm. I would only have types and could use pattern matching and discriminated unions to perform my algorithm. The visitor pattern is needed in my current project because I’m using an implicit OO coding approach.</p> <p>It was really shocking to me that this wasn’t obvious right away. I’ve been doing OO for so long now I’ve completely become accustomed to dealing with objects and state. A programming world without objects had completely slipped from my mind. Glad I took the time to get started on this book as it’s already giving me new ideas and techniques I can use in my daily C# and OO programming. Now to start working on some of the other <a href="http://www.indiangeek.net/wp-content/uploads/Programmer%20competency%20matrix.htm">programmer competencies</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/09/06/shiny-new-toys-visitor-pattern-and-real-world-functional-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WP7 Boot Camp with Jeff Brand</title>
		<link>http://jasonrowe.com/2010/08/03/wp7-boot-camp-with-jeff-brand/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wp7-boot-camp-with-jeff-brand</link>
		<comments>http://jasonrowe.com/2010/08/03/wp7-boot-camp-with-jeff-brand/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 18:38:38 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[wp7]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/2010/08/03/wp7-boot-camp-with-jeff-brand/</guid>
		<description><![CDATA[&#160; Today I went to the WP7 boot camp in Minneapolis. Not many people have actually seen a Windows Phone 7 yet. I was hoping to see the real thing but it wasn’t available. Although, the dev tools are ready &#8230; <a href="http://jasonrowe.com/2010/08/03/wp7-boot-camp-with-jeff-brand/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p> <p>Today I went to the WP7 boot camp in Minneapolis. Not many people have actually seen a Windows Phone 7 yet. I was hoping to see the real thing but it wasn’t available. Although, the dev tools are ready and very robust.</p> <p>Getting started is easy using the <a href="http://developer.windowsphone.com/">developer tools</a> and <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=CA23285F-BAB8-47FA-B364-11553E076A9A&amp;displaylang=en">developer training kit</a>. After downloading and playing around I really hope WP7 is a success. The development experience is slick if you are willing to embrace XAML or XNA. </p> <p>A note about the install. If you have a full version of Visual Studio it will integrate with that. Otherwise it will install Visual Studio express. A few people in the group were confused when they opened express and the tools were not available as they already had VS2010 installed. (Note, it might be safer to use VS Express for now with this beta if you can. The presenter was having issues adding service references with VS Pro but it works in express.)</p> <p></p> <div style="width: 250px" class="wp-caption alignright"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="wp7" border="0" alt="wp7" src="http://jasonrowe.com/wp-content/uploads/2010/08/wp7_thumb.png" width="135" height="244"/> </div>Since the first part of the conversation was about marketing information I ported over a Silverlight 3 test application which uses data binding and notifications to draw lines onto a canvas. All I had to do was copy the code verbatim and it ran on the phone. It took me 5 minutes. The ease of portability was impressive. Although, Silverlight is at a 60 &#8211; 65% <a href="http://riastats.com/">adoption rate</a> so portability is relative depending on market conditions.  <p></p> <p>Below are a list of notes that caught my attention during the talk. This is all based on a beta product so some of this may change. For the latest information download the WP7 Training Kit and visit the wp7 developer site.</p> <p>Basics</p> <ul> <li>$100 fee to upload apps to market place. You get paid after you make the first $100 but Microsoft will take a cut for each sale.  </li><li>Has ability to upload app in trial mode  </li><li>Silverlight capabilities is basically Silverlight 3 plus additional features. </li></ul> <p>Known Issues with Emulator:</p> <ul> <li>Sometimes Emulator will not change from portrait to landscape if keyboard is enabled to be used. Hit PageDown to disable it  </li><li>When using VS Pro some users have not been able to add service references correctly. They didn’t generate the full proxy. </li></ul> <p>Tips and Tricks:</p> <ul> <li>Use PageUp and PageDown keys to enable keyboard in emulator.  </li><li>Emulator can be kept running and will store all opened apps.  </li><li>Blend can be used to test light and dark template available to phone users. </li></ul> <p>Tooling </p> <ul> <li>Code from Silverlight 3 should work on the phone with maybe only small tweaks for things like navigation and UI sizes.  </li><li>List Application (list and details page paradigm)  </li><li>Binding works just like in Silverlight  </li><li>DataContext works like Silverlight  </li><li>Input scopes “TelephoneAreaCode” and “EmailSMTPAdress”&nbsp; allow you to change keyboard layout.<strong> </strong><strong>Developer Note</strong>: You can use Verbose XAML syntax for intellisense. You can’t create your own input scopes right now. Demo in SDK uses reflection to explore input scopes.  </li><li>Accelerometer – can be used with emulator if laptop that has one built one in. Otherwise you can use <a href="http://msdn.microsoft.com/en-us/library/ff637521%28v=VS.92%29.aspx">accelerometer emulator using RX</a>.  </li><li>Audio – leverage raw data override BufferReady event at regular intervals save and manipulate audio. About a 10ms delay. All available in SDK.  </li><li>Video elements – Media support is on the hardware – video decoding is down on the hardware. Only one media element on the page at the time. No video media brush. DRM  </li><li>XNA API can be used to bring in sounds and background sounds.  </li><li>JavaScript can talk to Silverlight in control – Silverlight to script wb.InvokeScript&nbsp; &#8211; script to Silverlight wb_ScriptNotify. Window.external.Notify(string) </li></ul> <p>3rd Party Tools and Links</p> <ul> <li><a href="http://mvvmlight.codeplex.com/">MVVM light for wp7</a>. Design Pattern.  </li><li>&nbsp;<strong></strong><strong>Developer Note</strong>: <a href="http://www.silverlighthack.com/post/2010/03/21/Using-the-Silverlight-Bing-Maps-control-on-the-Windows-Phone-7.aspx">Bing Maps Control</a> not yet available but being developed. </li></ul> <p>Design</p> <ul> <li>All elements can be animated  </li><li>Elements can be projected onto 3d plane  </li><li>Templating – taking a control and laying a XAML rendering over the code base. Microsoft encourages using the metro theme but they did show a puzzle application that used templating to change buttons and panels.  </li><li>Styling can be set in the Application XAML resources or page resources.  </li><li>Two screen resolutions will be available.  </li><li>User can change the Theme  </li><li>Blend can be used to test dark and light themes available to users. Would only need to be done if you go off and build your own template. But if you use the metro theme you get the changes for free. For example, your applications buttons and backgrounds would be updated.  </li><li>App bar should be used to create consistent navigation and controls. <a href="http://msdn.microsoft.com/en-us/library/ff431786%28v=VS.92%29.aspx">How to: Add an Application Bar to Your Application</a> on MSDN.  </li><li>App bar Icon set can be <a href="http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=369b20f7-9d30-4cff-8a1b-f80901b2da93&amp;displayLang=en">downloaded here.</a> </li></ul> <p>Application Components</p> <ul> <li>Host (TaskHost)  </li><li>XAP file  </li><li>Pages (Silverlight)  </li><li>Content (Silverlight)  </li><li>Games (XNA) </li></ul> <p>Application Structure</p> <ul> <li>Apps are built like web sites  </li><li>Functionality is split into pages  </li><li>Forward navigation via links  </li><li>Backward navigation via Back (should use hardware button).  </li><li>Users can navigate across different applications  </li><li>Previous app (pages) are in the back stack. No multi tasking for third party apps. The back stack means your app is shut down. </li></ul> <p>Hardware buttons</p> <ul> <li>Back (only one you can inject into when it fires right now)  </li><li>Start  </li><li>Search  </li><li>Volume  </li><li>Camera </li></ul> <p>Feels like web design.</p> <ul> <li>Application state can be passed between pages by querystring and frame context.  </li><li>hyperlinks can be used to navigate to other pages.  </li><li>UriMapping which is similar to MVC URL routing. </li></ul> <p>Push Notification Service via the cloud (Microsoft Notification service)</p> <ul> <li><strong>Developer Note: When the emulator starts it takes 30 seconds to instantiate</strong> notification service.  </li><li>Phones subscribe to a service on your server for events via a Uri.  </li><li>All communication pushed to phone is via Microsoft.  </li><li>Events are sent from a server to Microsoft push service. </li></ul> <p>Location Service:</p> <ul> <li><strong></strong><strong>Developer Note</strong>: No Emulator Support – <a href="http://msdn.microsoft.com/en-us/library/ff637517%28v=VS.92%29.aspx">MSDN RX emulator can be created</a>.  </li><li>Cell Tower, Satellite GPS, or WIFI can be used  </li><li><strong></strong><strong>Developer Note</strong>: Use cell tower to save battery but less accurate </li></ul> <p>Types of Notifications on the Phone</p> <ul> <li>Tile Notifications –&nbsp; Tile on homepage which has an image, number, and simple text.  </li><li>Toast – pop-up will link back to app.  </li><li>If the app is running raw data can be accessed and displayed. </li></ul> <p>Handling Life Time Events: Obscure VS Deactivated</p> <p>Hidden By Shell UI: Obscured</p> <ul> <li>On Obscure you need to handle it gracefully then when un obscure you need to start. </li></ul> <p>Moved to background: Deactivated</p> <ul> <li>Deactivate event fires  </li><li>Your app becomes suspended (you have a limited time to handle but not specified yet)  </li><li>State will be destroyed eventually if user doesn’t go back. Assume your app is killed.  </li><li>If user goes back to application Activate event will be fired  </li><li>You can load state via isolated storage and resume where you left off </li></ul> <p>Interesting Questions asked during the presentation:</p> <ul> <li><strong>Question</strong>: Are ODBC drivers available or ported? <strong>Answer</strong>: Someone suggested using isolated storage for this instead.  </li><li><strong>Question</strong>: Does page Navigation come with default animation? <strong>Answer</strong>: It doesn’t come with a default animation. But you can add them in by intercepting the navigation event.  </li><li><strong>Question</strong>: How is back stack clean up done and can it be prioritized? <strong>Answer</strong>: Presenter guessed that it might be resource based but not sure yet.  </li><li><strong>Question</strong>: Can you control the Antenna for GPS? Can you turn it off or on and receive notifications when it is ready? <strong>Answer</strong>: Start and Stop service might be used for this but not sure. It looks like the API only tries to use it if available. Look at Location example in SDK. </li></ul> <p>Links</p> <ul> <li><a title="http://www.silverlight.net/" href="http://www.silverlight.net/">http://www.silverlight.net/</a>  </li><li><a title="http://developer.windowsphone.com/" href="http://developer.windowsphone.com/">http://developer.windowsphone.com/</a>  </li><li><a title="http://slickthought.net/" href="http://slickthought.net/">http://slickthought.net/</a> Jeff Brand&#8217;s Site  </li><li><a href="http://blogs.msdn.com/b/microsoft_press/archive/2010/08/02/free-ebook-petzold-s-programming-windows-phone-7-special-excerpt-2.aspx">Programming Windows 7 Phone</a>&nbsp;</li></ul>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/08/03/wp7-boot-camp-with-jeff-brand/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Top 5 Features of Code First Entity Framework CTP4</title>
		<link>http://jasonrowe.com/2010/07/18/top-5-features-of-code-first-entity-framework-ctp4/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=top-5-features-of-code-first-entity-framework-ctp4</link>
		<comments>http://jasonrowe.com/2010/07/18/top-5-features-of-code-first-entity-framework-ctp4/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 16:19:26 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[EF]]></category>
		<category><![CDATA[ORM]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/2010/07/18/top-5-features-of-code-first-entity-framework-ctp4/</guid>
		<description><![CDATA[&#160; The latest release of Entity Framework CTP4 has some nice but unexpected changes. They introduced DbContext and DbSet to simplify model caching, database provisioning, schema creation and connection management. Here are my top 5 favorite features of the release. &#8230; <a href="http://jasonrowe.com/2010/07/18/top-5-features-of-code-first-entity-framework-ctp4/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>  <p>The latest release of Entity Framework CTP4 has some nice but unexpected changes. They introduced DbContext and DbSet to simplify model caching, database provisioning, schema creation and connection management. Here are my top 5 favorite features of the release.</p>  <ol>   <li><strong><em>Less code and fewer Concepts.</em></strong> The coolest part is the use of convention over configuration. See the <a href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4piwalkthrough.aspx">Productivity Improvements</a> walk through and <a href="http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-code-first.aspx">Conventions for code first</a>. I like the extra touch that DbContext&#160; will create the database for you if you want. No code to write. Just use the default CreateDatabaseOnlyIfNotExists. </li>    <li><em><strong>Simplified Database Experience.</strong></em> With the introduction of DbContext and DbSet. EF now takes care of database provisioning, schema creation and connection management. Nice! My favorite part is the Interface IDbConnectionFactory to allow creation of your own conventions. </li>    <li><strong>Backwards Compatible.</strong> Yes, this is a feature when it comes to CTP’s and Betas. Some projects might just throw stuff away or completely change things on you. EF allows you to still use ObjectContext or <a href="http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx">Data Annotations</a> for advanced scenarios where common conventions don’t work for you. </li>    <li><strong>Simplified Configuration Experience.</strong> As I mentioned you can use annotations for this but you also have another cool option. DbContext includes a virtual method that can be overridden to do configuration right in the class. This means no need for separate configuration classes now. I definitely like having it all in one place. Much cleaner and easy to read. </li>    <li><strong>Testability </strong>IDbSet&lt;TEntity&gt; allows you to define an interface that can be implemented by your derived context. This allows the context to be replaced with an in-memory test double for testing. </li> </ol>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/07/18/top-5-features-of-code-first-entity-framework-ctp4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Poor Mans Reverse Search with Lucene.net</title>
		<link>http://jasonrowe.com/2010/07/02/poor-mans-reverse-search-with-lucene-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=poor-mans-reverse-search-with-lucene-net</link>
		<comments>http://jasonrowe.com/2010/07/02/poor-mans-reverse-search-with-lucene-net/#comments</comments>
		<pubDate>Sat, 03 Jul 2010 04:54:21 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Lucene]]></category>
		<category><![CDATA[lucene]]></category>
		<category><![CDATA[search]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1268</guid>
		<description><![CDATA[As I mentioned in my last post I&#8217;ve been reading and learning about Lucene via Lucene in Action 2nd edition. Chapter 9.4, Fast memory-based indices, talks about MemoryIndex and InstantiatedIndex. MemoryIndex, contributed by Wolfgang Hoschek, is a fast RAM-only index &#8230; <a href="http://jasonrowe.com/2010/07/02/poor-mans-reverse-search-with-lucene-net/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As I mentioned in my last <a href="http://jasonrowe.com/2010/06/23/lucene-in-action-net-samples/">post</a> I&#8217;ve been reading and learning about Lucene via Lucene in Action 2nd edition. Chapter 9.4, Fast memory-based indices, talks about MemoryIndex and InstantiatedIndex. </p>  <p>MemoryIndex, contributed by Wolfgang Hoschek, is a fast RAM-only index designed to test whether a single document matches a query. InstantiatedIndex, contributed by Karl Wettin, is similar, except it’s able to index and search multiple documents. Unfortunately, neither of these are yet ported to .Net. I thought about trying to port these but figured I would see if I could build a simple reverse search using the slower built in RamDirectory in Lucene and Lucene.net. </p>  <p>So what I want to create is a reverse search or on-the-fly matchmaking for documents. A simpler way to say that is I take a list of queries and check if they match a data object each time a data object is created. For simplicity sake I&#8217;m only working with the already ported Lucene code. </p>  <p>One cool features in Lucene version 2.9 was the addition of Near Real Time (NRT) searching. This seemed like a good fit for my scenario of trying to create a faster reverse search. It provides a way to search for documents that have not been committed yet. This helps take some of the overhead off when I need to add the one document to the index before running all the queries to test for matches. The explanation from the book says NRT enables you to rapidly search changes made to the index with an open IndexWriter, without having to first close or commit changes to that writer. </p>  <p>The NRT features allows me to do something like this: </p>  <p><em>It seems to be a big memory hog though so I made it disposable.</em></p>  

<pre class="brush: csharp; title: ; notranslate">   
 public class QueryProcessor : IDisposable
    {
        private readonly RAMDirectory _directory;
        private readonly IndexWriter _writer;

        public MetaQueryProcessor()
        {
            _directory = new RAMDirectory();
            _writer = new IndexWriter(_directory, 
                                      new StandardAnalyzer(
                                          Lucene.Net.Util.Version.LUCENE_CURRENT),
                                          IndexWriter.MaxFieldLength.UNLIMITED);
            _writer.SetMergeFactor(2);
        }

        public void Optimize()
        {
            _writer.Optimize();
        }

        public List&lt;string&gt; Search(List&lt;metaqueryrequest&gt; requests, Document doc)
        {
            _writer.AddDocument(doc);

            var results = new List&lt;string&gt;();

            foreach (var request in requests)
            {
                var reader = _writer.GetReader();//Near-real-time search not commited

                var indexSearcher = new IndexSearcher(reader);

                var primitiveQuery = request.LuceneQuery.Rewrite(reader);

                var hits = indexSearcher.Search(primitiveQuery, 1);

                if (hits.totalHits &gt; 0)
                {
                    results.Add(request.QueryName);
                }
            }

            _writer.DeleteAll();

            return results;
        }

        #region IDisposable Members

        public void Dispose()
        {
            _directory.Close();
        }

        #endregion
    }
</pre>

<a href="http://jasonrowe.com/wp-content/uploads/2010/07/reverse_search.png"><img src="http://jasonrowe.com/wp-content/uploads/2010/07/reverse_search.png" alt="" title="reverse_search" class="alignnone size-full wp-image-1274" /></a>
 <p>If you know of a faster way to accomplish this please let me know. For more background information on this topic see these resources. </p>  <ul>   <li><a href="http://lucene.apache.org/java/2_2_0/api/org/apache/lucene/index/memory/MemoryIndex.html">MemoryIndex contrib project Lucene</a> </li>    <li><a href=" http://lucene.apache.org/java/2_4_0/api/contrib-instantiated/org/apache/lucene/store/instantiated/InstantiatedIndex.html">InstantiatedIndex contrib project Lucene</a> </li> </ul></string></metaqueryrequest></string>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/07/02/poor-mans-reverse-search-with-lucene-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lucene in Action .Net Samples</title>
		<link>http://jasonrowe.com/2010/06/23/lucene-in-action-net-samples/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=lucene-in-action-net-samples</link>
		<comments>http://jasonrowe.com/2010/06/23/lucene-in-action-net-samples/#comments</comments>
		<pubDate>Thu, 24 Jun 2010 03:22:39 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Lucene.Net]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1185</guid>
		<description><![CDATA[&#160; I started reading Lucene in Action by Otis Gospodnetic´ and Erik Hatcher.&#160; Lucene is a high performance, scalable Information Retrieval (IR) library. The library is in Java but I’m using the book to understand the Lucene .Net port. Why &#8230; <a href="http://jasonrowe.com/2010/06/23/lucene-in-action-net-samples/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&#160;</p>  <p>I started reading <a href="http://www.manning.com/hatcher3/">Lucene in Action</a> by Otis Gospodnetic´ and Erik Hatcher.&#160; Lucene is a high performance, scalable Information Retrieval (IR) library. The library is in Java but I’m using the book to understand the <a href="http://lucene.apache.org/lucene.net/">Lucene .Net</a> port.</p>  

<p>Why buy a Java book to learn a .net Library? I couldn’t find a book specifically for the .Net version. Also, I wanted a 1000 foot level view of search technologies and because this is my first time working with IR. I was pleased to find the .net version is akin to the Java version presented in the book.</p>  

<p>In some ways, learning from a different language has been beneficial. I invested more time converting the presented samples to C#.  I’ve also read <a href="http://www.amazon.com/Mathematics-Physics-Programmers-Game-Development/dp/1584503300">Mathematics and Physics for Programmers</a> which was completely written in a pseudo language. Again, lots of fun to convert the presented samples to a language I was more comfortable with.</p> 

<p>It was also nice to find that the open source project <a href="http://code.google.com/p/subtext/source/browse/trunk/src/Subtext.Framework/Services/SearchEngine/SearchEngineService.cs">Subtext</a> is using Lucene .Net. They’ve worked out some locking issue recently and seem to be getting things setup in a nice way. Also, my co workers Kevin and Tim put together a nice library for Lucene .Net called <a href="http://code.google.com/p/activelucenenet/">ActiveLucene.Net &#8211; Attributed Lucene.Net</a>. The largest project seems to be <a href="http://linqtolucene.codeplex.com/">Linq to Lucene</a> but I haven&#8217;t looked at it yet. It was helpful to see how others are integrating Lucene into the Microsoft Web Platform.

</p><p>
Anyway, here are the indexer and searcher in my C# interpretation. These are the first snippets presented in the book. These are a great way to get a jump start into understanding the basics.
</p>

<p><strong>Indexer</strong></p> 

<pre class="brush: csharp; title: ; notranslate">   
readonly static SimpleFSLockFactory _LockFactory = new SimpleFSLockFactory();

static void Main(string[] args)
{

    var dataPath = ConfigurationManager.AppSettings[&quot;DataDirectory&quot;];

    var indexPath = ConfigurationManager.AppSettings[&quot;IndexDirectory&quot;];

    if (!System.IO.Directory.Exists(dataPath))
    {
        throw new IOException(dataPath + &quot; directory does not exist&quot;);
    }

    DirectoryInfo indexInfo = new DirectoryInfo(indexPath);

    DirectoryInfo dataInfo = new DirectoryInfo(dataPath);

    Lucene.Net.Store.Directory indexDir = Lucene.Net.Store.FSDirectory.Open(
                                                     indexInfo, _LockFactory);

    var start = DateTime.Now.TimeOfDay;
    var numIndexed = Index(indexDir, dataInfo);
    var end = DateTime.Now.TimeOfDay;

    var delta = end.TotalMilliseconds - start.TotalMilliseconds;

    Console.WriteLine(
       &quot;Indexing &quot; + numIndexed + &quot; files took &quot; + delta.ToString() + &quot; milliseconds
                      );
}

public static int Index(Lucene.Net.Store.Directory indexDir, DirectoryInfo dataInfo)
{
    var writer = new IndexWriter(indexDir, new StandardAnalyzer(
                                      Lucene.Net.Util.Version.LUCENE_29), 
                                      IndexWriter.MaxFieldLength.UNLIMITED);
    writer.SetMergePolicy(new LogDocMergePolicy(writer));
    writer.SetMergeFactor(5);

    try
    {
        var paths = dataInfo.EnumerateFiles(&quot;*.txt&quot;);

        foreach (var path in paths)
        {
            IndexFile(writer, path);
        }
    }
    catch (Exception ex)
    {
        writer.Close();
        throw ex;
    }

    var numIndexed = writer.MaxDoc();
    writer.Optimize();
    writer.Close();

    return numIndexed;
}

private static void IndexFile(IndexWriter writer, FileInfo file)
{
    if (!file.Exists)
    {
        return;
    }

    Console.WriteLine(&quot;Indexing &quot; + file.Name);

    Document doc = new Document();

    var path = file.FullName;

    System.IO.TextReader readFile = new StreamReader(path);

    doc.Add(new Field(&quot;contents&quot;, readFile));

    doc.Add(new Field(&quot;filename&quot;, file.Name,
        Field.Store.YES,
        Field.Index.ANALYZED,
        Field.TermVector.YES));

    writer.AddDocument(doc);
}
</pre>   

<p><strong>Searcher</strong></p> 

<pre class="brush: csharp; title: ; notranslate">   
public static SimpleFSLockFactory _LockFactory = new SimpleFSLockFactory();

static void Main(string[] args)
{
    if (args.Length &lt; 2)
    {
        Console.WriteLine(&quot;Searcher takes two parameters&quot;);
        Console.WriteLine(&quot;Usage: ConsoleSearcher &lt;index dir&gt; &lt;query&gt;&quot;);
    }

    var indexInfo = new DirectoryInfo(args[0]);
    var query = args[1];

    if (!System.IO.Directory.Exists(args[0]))
    {
        throw new IOException(args[0] + &quot; directory does not exist&quot;);
    }

    SearchOption(indexInfo, query);
}

private static void SearchOption(DirectoryInfo indexInfo, string query)
{
    Lucene.Net.Store.Directory indexDir = Lucene.Net.Store.FSDirectory.Open(
                                                     indexInfo, _LockFactory);

    IndexSearcher indexSearcher = new IndexSearcher(indexDir, true);

    QueryParser parser = BuildQueryParser();
    var luceneQuery = parser.Parse(query);

    var start = DateTime.Now.TimeOfDay;

    var hits = indexSearcher.Search(luceneQuery);
    var end = DateTime.Now.TimeOfDay;

    var delta = end.TotalMilliseconds - start.TotalMilliseconds;

    Console.WriteLine(&quot;Found &quot; + hits.Length() + 
        &quot; document (s) (in &quot; + delta.ToString() + 
        &quot; milliseconds) that matched query '&quot; + query + &quot;':&quot;);

    for (int i = 0; i &lt; hits.Length(); i++)
    {
        Document doc = hits.Doc(i);

        Console.WriteLine(doc.Get(&quot;filename&quot;));
    }
}

private static QueryParser BuildQueryParser()
{
var parser = new QueryParser(
    Lucene.Net.Util.Version.LUCENE_29, &quot;contents&quot;, 
     new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));

    parser.SetDefaultOperator(QueryParser.Operator.AND);
    return parser;
}
</pre>   
</query></query>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/06/23/lucene-in-action-net-samples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

