<?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</title>
	<atom:link href="http://jasonrowe.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jasonrowe.com</link>
	<description>enjoying the web</description>
	<lastBuildDate>Tue, 03 Jan 2012 02:03:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<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[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;]]></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; ">


%% 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: c#; ">

 [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>
<code>http:request(post, {"http://localhost/OfflineDemoWebhost/Message/Process",[], "application/x-www-form-urlencoded","From=earl the squirrel&#038;To=you&#038;Body=Hello World"}, [], []).</code>

<p>If you see a response starting with this you are good to go.</p>
<code>{ok,{{"HTTP/1.1",200,"OK"},</code>

<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; ">

%% 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>Strophejs ejabberd IIS Setup</title>
		<link>http://jasonrowe.com/2011/11/18/strophejs-ejabberd-iis-setup/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=strophejs-ejabberd-iis-setup</link>
		<comments>http://jasonrowe.com/2011/11/18/strophejs-ejabberd-iis-setup/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 19:08:17 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[XMPP]]></category>
		<category><![CDATA[ejabberd]]></category>
		<category><![CDATA[strophejs]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1547</guid>
		<description><![CDATA[This is a simple guide for getting strophe.js, ejabberd, and IIS all working together on a local dev machine. This assumes you have IIS 7.5 installed and are familiar with the basics of IIS Manager Step 1: Download and install&#8230;]]></description>
			<content:encoded><![CDATA[<p>This is a simple guide for getting strophe.js, ejabberd, and IIS all working together on a local dev machine. This assumes you have IIS 7.5 installed and are familiar with the basics of IIS Manager</p>

<img src="http://jasonrowe.com/wp-content/uploads/2011/11/ej_iis_stro_blog1.png" alt="strophe ejabberd IIS" title="ej_iis_stro_blog" width="400" height="100" class="alignleft size-full wp-image-1563" />

<p><strong>Step 1</strong>: Download and install <a href="http://www.process-one.net/en/ejabberd/downloads">ejabberd</a>. The install is straight forward and the default configuration has everything you need. During the install it will ask you for a domain. I would recommend setting up a host alias &#8220;localhost.demo.com&#8221; because it looks nicer and easier to use but you could also just use localhost. After install check to make sure the http-bind endpoint is working http://localhost:5280/http-bind/. You should see a simple page that has &#8220;ejabberd mod_http_bind&#8221; at the top</p>

<p><strong>Step 1.5</strong>: Setup a host name if needed. If you used localhost you can skip this step. You can do this in Windows 7 via the host file which should be located &#8220;C:\Windows\System32\drivers\etc\hosts&#8221;. Add a line at the bottom with your IP and new local DNS.</p>

<p><strong>Step 2</strong>: Setup new IIS application and copy in strophe.js examples. Go into IIS manager and create a new application named &#8220;xmppExample&#8221;. Then download the latest <a href="http://strophe.im/strophejs/">strophe.js</a> and copy the contents to your new site. You should be able to access the following now. http://localhost.demo.com/xmppExample/strophejs/examples/basic.html. You will have to change the first line in basic.js to setup your endpoint. It should look like this <strong>BOSH_SERVICE = &#8216;http://localhost.demo.com/http-bind&#8217;</strong></p>

<p><strong>Step 3</strong>: Setup proxy for ejabberd http-bind endpoint. To make things simple we need everything on the same domain. Right now, the bosch http-bind endpoint is this http://localhost:5280/http-bind/ and we need it to be this http://localhost.demo.com/http-bind. Download and install the Application Request Routing for IIS. Once installed follow these steps to enable proxy.
</p>

<ol>
	<li>Open IIS Manager</li>
	<li>Select a server node in the tree view on the left hand side and then click on the &#8220;Application Request Routing&#8230;&#8221; the full name shows up as &#8220;Application Request Routing Cache&#8221;</li>
	<li>Then on the far right side click on &#8220;Server Proxy Settings&#8230;</li>
	<li>check the box next to Enable proxy and apply settings (keep everything else default)</li>
</ol>

<p>
Finally, add a rewrite rule to the web.config file in your inetpub root dir. For example, mine is located &#8220;C:\inetpub\wwwroot\web.config&#8221;. Here is my full XML configuration file:
</p>

<pre class="brush: xml; ">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;configuration&gt;
    &lt;system.webServer&gt;
	&lt;rewrite&gt;
    		&lt;rules&gt;
          		&lt;rule name=&quot;ejabberd.BOSH&quot; stopProcessing=&quot;true&quot;&gt;
               			&lt;match url=&quot;^http-bind&quot; /&gt;
               			&lt;action type=&quot;Rewrite&quot; url=&quot;http://localhost.demo.com:5280/http-bind/&quot; /&gt;
          		&lt;/rule&gt;
    		&lt;/rules&gt;
	&lt;/rewrite&gt;
        &lt;validation validateIntegratedModeConfiguration=&quot;false&quot; /&gt;
    &lt;/system.webServer&gt;
&lt;/configuration&gt;

</pre>

<p>Now you should be able to run the demo at http://localhost.demo.com/xmppExample/strophejs/examples/basic.html. You will need to login with admin@localhost.demo.com (if admin is the username you selected during install) and the password you selected during install.</p>

<blockquote>I can also be found on Google+

<a title="Jason Rowe is on Google+" rel="author" href="http://profiles.google.com/jasonrowe?rel=author" alt="Google+" title="Google+">Jason Rowe</a> and twitter <a title="Jason Rowe is on twitter" rel="author" href="http://twitter.com/jsonrow?rel=author" alt="twitter" title="twitter">@jsonrow</a>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2011/11/18/strophejs-ejabberd-iis-setup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting back into JavaScript</title>
		<link>http://jasonrowe.com/2011/11/02/getting-back-into-javascript/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-back-into-javascript</link>
		<comments>http://jasonrowe.com/2011/11/02/getting-back-into-javascript/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 04:17:32 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[General Programming]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[charting]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1498</guid>
		<description><![CDATA[The last time I did any serious JavaScript was around the time Sizzle was added to JQuery, Google Chrome was brand new, and MarketWatch.com started using canvas charts. Note: Here is a quick overview of JavaScript that is as short&#8230;]]></description>
			<content:encoded><![CDATA[<p>The last time I did any serious JavaScript was around the time Sizzle was added to JQuery, Google Chrome was brand new, and MarketWatch.com started using canvas charts.</p> 

<p><strong>Note:</strong> Here is a quick <a href="http://www.2ality.com/2011/10/javascript-overview.html">overview of JavaScript</a> that is as short as possible, but explains every major feature. I would also recommend following the <a href="http://www.2ality.com/">2ality</a> website</p>

<p>Today JavaScript projects have the complexity, size, and structure of projects written in languages like C# and Java. Thankfully, the developer tools for debugging and logging are solid across browsers. *<i>Opera is still a little funky about logging using &#8220;opera.postError.apply(opera, arguments);&#8221;</i>. Looking particularly good, <a href="http://code.google.com/chrome/devtools/">Google&#8217;s version of the webkit dev tools</a> and some API&#8217;s they have in <a href="http://code.google.com/chrome/extensions/dev/experimental.devtools.html">beta</a>. I’ve started to use <a href="http://docs.jquery.com/QUnit">quint</a> for unit testing. I’ve also been looking leveraging these frameworks: <a href="http://documentcloud.github.com/underscore/">underscore.js</a>, <a href="http://jashkenas.github.com/coffee-script/">coffee script</a>, <a href="http://raphaeljs.com/">raphaeljs</a>, and <a href="http://code.google.com/closure/compiler/">closure compiler</a>.</p> <p>It’s amazing how much has changed. Now <a href="https://developer.mozilla.org/en/JavaScript/Reference">examples of good JavaScript</a> are much easier to find. Hell, here is a step by step walkthrough of how to <a href="http://dailyjs.com/tags.html#lmaf">build your very own JavaScript framework</a>.</p> 

<p>So to get some practice I went and found some JS that needed cleanup. I wanted to focus on structure and namespaces and this <a href="http://www.elated.com/res/File/articles/development/javascript/snazzy-animated-pie-chart-html5-jquery/">script</a> needed some love. View source on that page and you will notice global variables and one big pile of code.</p> <p>The first thing I did was break up the logic into separate functional script files that will later be compiled and minified into one. You can see the python script I use to minify <a href="https://raw.github.com/JasonRowe/SimpleHTML5.Charts/master/build.py">here</a>.</p> 

<ol> 
<li><a href="https://github.com/JasonRowe/SimpleHTML5.Charts/blob/master/src/animation.js">animation.js</a></li> 
<li><a href="https://github.com/JasonRowe/SimpleHTML5.Charts/blob/master/src/builder.js">builder.js</a></li> 
<li><a href="https://github.com/JasonRowe/SimpleHTML5.Charts/blob/master/src/core.js">core.js</a></li> 
<li><a href="https://github.com/JasonRowe/SimpleHTML5.Charts/blob/master/src/pie.js">pie.js</a></li> 
<li><a href="https://github.com/JasonRowe/SimpleHTML5.Charts/blob/master/src/rendering.js">rendering.js</a></li> 
<li><a href="https://github.com/JasonRowe/SimpleHTML5.Charts/blob/master/src/styles.js">styles.js</a></li>
</ol> 

<p>I then added a <a href="https://github.com/JasonRowe/SimpleHTML5.Charts/tree/master/test">test folder</a> and setup the same file names but which had test cases for each script. Then an index.html file to display the test groups or “modules” as they are called in QUnit. Here is an example of a test that always passes</p> 

<pre class="brush: js; ">

module(&quot;sample test&quot;);

test(&quot;a sample qunit test&quot;, function () {
    ok(true, &quot;always fine&quot;);
});


</pre>  

<p>The next thing I worked on was getting a namespace around the code. I went with the following which seems to work for my needs.</p> 

<pre class="brush: js; ">

var MYAPP = MYAPP || {};

MYAPP.namespace = function (ns_string) { var parts = ns_string.split(&#039;.&#039;), parent = MYAPP, i; // strip redundant leading global 

if (parts[0] === &quot;MYAPP&quot;) { parts = parts.slice(1); } for (i = 0; i &lt; parts.length; i += 1) { // create a property if it doesn&#039;t exist 

if (typeof parent[parts[i]] === &quot;undefined&quot;) { parent[parts[i]] = {}; 

} parent = parent[parts[i]]; } return parent; }; 


</pre>  

<p>Stefanov, Stoyan (2010). JavaScript Patterns (pp. 89-90). OReilly Media &#8211; A. Kindle Edition. </p>

<p>So after refactoring, I’ve got the pie chart setup code to the following.</p>

<pre class="brush: js; ">

var pieElm = document.getElementById(&#039;pieChart&#039;);
var pieData = $(&#039;#chartData td&#039;);

var pieChart = new SimpleHtml5.Core.Pie(pieElm, pieData);

$(&#039;#pieChart&#039;).click (pieChart, SimpleHtml5.Pie.Animation.HandleChartClick);

</pre>

<p>To customize the style I allow passing in a custom style object to override the defaults.</p>

<pre class="brush: js; ">


var customStyles = {
    chartSizePercent: 49,
    maxPullOutDistance: 10,
    pullOutFrameStep: 4,
    pullOutFrameInterval: 40,
    pullOutLabelPadding: 42
};

var pieElm = document.getElementById(&#039;pieChart&#039;);
var pieData = $(&#039;#chartData td&#039;);
var pieChart = new SimpleHtml5.Core.Pie(pieElm, pieData, customStyles);
$(&#039;#pieChart&#039;).click (pieChart, SimpleHtml5.Pie.Animation.HandleChartClick);

</pre>

<p>
If you are curious about how the other parts of the chart were organized you can see the source code on <a href="https://github.com/JasonRowe/SimpleHTML5.Charts">github</a>.
</p>

<p>

<blockquote>I can also be found on Google+

<a title="Jason Rowe is on Google+" rel="author" href="http://profiles.google.com/jasonrowe?rel=author" alt="Google+" title="Google+">Jason Rowe</a> and twitter <a title="Jason Rowe is on twitter" rel="author" href="http://twitter.com/jsonrow?rel=author" alt="twitter" title="twitter">@jsonrow</a>
</blockquote>


</p>

]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2011/11/02/getting-back-into-javascript/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;]]></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: c#; ">
  
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: c#; ">
  
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: c#; ">
  
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: c#; ">
  
var type = typeof(IMyImageComponent);
            var styles = AppDomain.CurrentDomain.GetAssemblies().ToList()
                .SelectMany(s =&gt; s.GetTypes())
                .Where(type.IsAssignableFrom);

            //find all classes that implement IMyImageComponent and register using name from GetFileName()
            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>

Here is how the factory was initialized:

<pre class="brush: c#; ">
  
            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: c#; ">
  
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: c#; ">
  
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>Changing Chart Color by Previous Close</title>
		<link>http://jasonrowe.com/2011/01/16/changing-chart-color-by-previous-close/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=changing-chart-color-by-previous-close</link>
		<comments>http://jasonrowe.com/2011/01/16/changing-chart-color-by-previous-close/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 01:40:14 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[charting]]></category>
		<category><![CDATA[gRaphaël]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1438</guid>
		<description><![CDATA[&#160; I frequently get asked how to create a chart in JavaScript that shows a different line color above and below the previous close price. Here is a example of what I mean. View this test page if you want&#8230;]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p> 

<p>I frequently get asked how to create a chart in JavaScript that shows a different line color above and below the previous close price. Here is a example of what I mean.</p> 

<p><a href="http://jasonrowe.com/wp-content/uploads/2011/01/final_example.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="final_example" border="0" alt="final_example" src="http://jasonrowe.com/wp-content/uploads/2011/01/final_example_thumb.png" width="244" height="177"></a></p> 

<p>View this <a href="http://jasonrowe.com/misc/chart/prevcloseline.html">test page</a> if you want skip the details and see a working example in JavaScript/SVG</p>

<p>At first glance, I’ve always thought this would be very easy and instructed them to create a new path depending on if the line is above or below the previous close line (the blue line in the image above). Simple enough right?</p> 

<p>It turns out I was missing a crucial step that might go unnoticed if you are using many data points. The problem turns up when using sparse data like the example shown above.</p> <p>Here is what it looks like if you do what I said literally.</p> <p><a href="http://jasonrowe.com/wp-content/uploads/2011/01/simple_start_broken.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="simple_start_broken" border="0" alt="simple_start_broken" src="http://jasonrowe.com/wp-content/uploads/2011/01/simple_start_broken_thumb.png" width="244" height="178"></a>&nbsp; </p> <p>&nbsp;</p> <p>That missing step I mentioned is connecting the new lines. Seems obvious now that I look at an example. So how will this be done? Here is an image showing the paths with labels for easy reference.</p> 

<p><a href="http://jasonrowe.com/wp-content/uploads/2011/01/simple_paths_connections.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="simple_paths_connections" border="0" alt="simple_paths_connections" src="http://jasonrowe.com/wp-content/uploads/2011/01/simple_paths_connections_thumb.png" width="244" height="179"></a></p> 

<p>What I have found works best is to find the intersection point between the paths and the previous close line. So you would create one line using the last point from path 1 and the first points from path2. The second line would just be the previous close line points. Unfortunately, just having the points is not enough to calculate the intersection.</p> 

<p>Below is the needed format and calculation. I created a function to do this in JS which is provided below but I wanted to include the <a href="http://www.topcoder.com/tc?module=Static&#038;d1=tutorials&#038;d2=geometry2">full explanation. </a></p> 
<blockquote>

Say we are given two different points, (x1, y1) and (x2, y2), and want to find A, B and C for the equation above. We can do so by setting

A = y2-y1
B = x1-x2
C = A*x1+B*y1

Regardless of how the lines are specified, you should be able to generate two different points along the line, and then generate A, B and C. Now, lets say that you have lines, given by the equations:

A1x + B1y = C1
A2x + B2y = C2

To find the point at which the two lines intersect, we simply need to solve the two equations for the two unknowns, x and y. 

 double det = A1*B2 &#8211; A2*B1
    if(det == 0){
        //Lines are parallel
    }else{
        double x = (B2*C1 &#8211; B1*C2)/det
        double y = (A1*C2 &#8211; A2*C1)/det
    }
</blockquote>


<p>Here is the full function in JS to create this format and find the intersection.</p> 



<pre class="brush: javascript; ">

  //Line-Line Intersection
        var getXCrossing = function(p1x, p1y, p2x, p2y, marker, markerMaxX) {
               
                var retValX = 0;
                var retValY = 0;
               
                //graph lines
                var a1 = p2y - p1y;
                var b1 = p1x - p2x;
                var c1 = a1 * p1x + b1 * p1y;
                
                //marker line is always horizontal
                var a2 = marker - marker;
                var b2 = 0 - markerMaxX;
                var c2 = a2 * 0 + b2 * marker;
                
                var det = a1 * b2 - a2 * b1;
                
                if(det === 0)
                {
                    //Lines are parallel
                }
                else
                {
                    retValX = (b2 * c1 - b1 * c2) / det;
                    retValY = (a1 * c2 - a2 * c1) / det;
                }   
                
                return {
                        x: retValX,
                        y: retValY
                    };
                };

</pre>

<p>Here is a <a href="http://jasonrowe.com/misc/chart/prevcloseline.html">test page</a> which shows a working example in SVG using <a href="http://g.raphaeljs.com/">gRaphaël</a> JavaScript library.</p>
]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2011/01/16/changing-chart-color-by-previous-close/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Blogging with Google App Engine</title>
		<link>http://jasonrowe.com/2010/10/17/blogging-with-google-app-engine/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=blogging-with-google-app-engine</link>
		<comments>http://jasonrowe.com/2010/10/17/blogging-with-google-app-engine/#comments</comments>
		<pubDate>Sun, 17 Oct 2010 16:33:23 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[General Programming]]></category>
		<category><![CDATA[GAE]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1400</guid>
		<description><![CDATA[&#160; A recent post and talk on twitter about host providers got me interested in building a blog using Google App Engine (GAE). It&#8217;s free to use and would eliminate having to pay for a hosting provider for a small&#8230;]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p> <p>A recent <a href="http://www.murphybytes.com/2010/09/29/gae-is-better-than-ec2/">post</a> and talk on twitter about host providers got me interested in building a blog using Google App Engine (GAE). It&#8217;s free to use and would eliminate having to pay for a hosting provider for a small site. My blog turned out like this <a href="http://jsoncharts.appspot.com/">jsoncharts</a>. I&#8217;m pretty happy with it so far.

<p>I got started with Python and GAE by reading the documentation and using the examples on the <a href="http://code.google.com/appengine/docs/python/gettingstarted/introduction.html">Google App Engine site</a>. Then I used this <a href="http://brizzled.clapper.org/id/77/">article</a> and framework for the base of my blog. The major changes I made were adding commenting and friendly URL’s. I can have URL’s like this (<a title="http://jsoncharts.appspot.com/blog/force-directed-graph-with-raphael" href="http://jsoncharts.appspot.com/blog/force-directed-graph-with-raphael">http://jsoncharts.appspot.com/blog/force-directed-graph-with-raphael</a>) and comments on the articles (<a title="http://jsoncharts.appspot.com/blog/force-directed-graph-with-raphael#respond" href="http://jsoncharts.appspot.com/blog/force-directed-graph-with-raphael#respond">http://jsoncharts.appspot.com/blog/force-directed-graph-with-raphael#respond</a>). </p> <p>Adding friendly URL’s was easy enough. Following <a href="http://bret.appspot.com/entry/experimenting-google-app-engine">Bret Taylor’s example</a> here is what my WSGIApplication instance looks like.</p> 

<pre class="brush: python; ">
 
application = webapp.WSGIApplication(
    [(&#039;/&#039;, FrontPageHandler),
     (&#039;/tag/([^/]+)/*$&#039;, ArticlesByTagHandler),
     (&#039;/date/(\d\d\d\d)-(\d\d)/?$&#039;, ArticlesForMonthHandler),
     (&#039;/&#039;+ defs.ARTICLE_URL_PATH +&#039;/(\d+)/?$&#039;, SingleArticleHandler),
     (&#039;/&#039;+ defs.ARTICLE_URL_PATH +&#039;/([^/]+)&#039;, SingleArticleHandlerBySlug),
     (&#039;/archive/?$&#039;, ArchivePageHandler),
     (&#039;/rss2/?$&#039;, RSSFeedHandler),
     (&#039;/.*$&#039;, NotFoundPageHandler),
     ], 

</pre>

<p>The following line routes incoming request to a class handler named “SingleArticleHandlerBySlug”.</p> 

<pre class="brush: python; ">
 
(&#039;/&#039;+ defs.ARTICLE_URL_PATH +&#039;/([^/]+)&#039;, SingleArticleHandlerBySlug),

</pre>

<p>The handler looks like this:</p> 

<pre class="brush: python; ">
 
class SingleArticleHandlerBySlug(AbstractPageHandler):
    &quot;&quot;&quot;
    Handles requests to display a single article, given its unique ID.
    Handles nonexistent IDs.
    &quot;&quot;&quot;
    def get(self, slug):
        article = Article.get_for_slug(slug)
        comments = None
        if article:
            comments = Comment.get_all_by_articleId(article.id)
            template = &#039;show-single-article.html&#039;
            articles = [article]
            more = None
        else:
            template = &#039;not-found.html&#039;
            articles = [] 

        self.response.out.write(self.render_articles(articles=articles,
                                                     request=self.request,
                                                     recent=self.get_recent(),
                                                     template_name=template,
                                                     comments=comments)) 

</pre>

<p>To add the commenting I had to create a new model class for storage. This was very simple.</p> 

<pre class="brush: python; ">
 
class Comment(db.Model): 

    name = db.TextProperty()
    email = db.TextProperty()
    website = db.TextProperty()
    body = db.TextProperty()
    commented_when = db.DateTimeProperty(auto_now_add=True)
    id = db.IntegerProperty()
    articleId = db.IntegerProperty()
    gravatar_url = db.TextProperty() 

</pre>

<p>Then I added a few functions for finding and deleting and then added them in. I can’t remember ever doing something with storage this fast. I don&#8217;t miss SQL at all. GAE really hides all the storage implementation details for you. Here is an example of the functions used to access the data store.</p> 

<pre class="brush: python; ">
 
@classmethod
def get_all(cls):
    q = db.Query(Comment)
    q.order(&#039;-commented_when&#039;)
    return q.fetch(FETCH_THEM_ALL)
@classmethod
def get_all_by_articleId(cls, articleId):
    q = db.Query(Comment)
    q.filter(&#039;articleId = &#039;, articleId)
    q.order(&#039;-commented_when&#039;)
    return q.fetch(FETCH_THEM_ALL) 

</pre>

<p>That’s all it takes and you are ready to go.</p> <p>Overall I was very impressed with the experience. In the future I&#8217;ll probably look into using Django&#8217;s form validation framework for comments and figure out how backups would work.</p>

Post Related Links:
<ul>
<li><a href="https://github.com/JasonRowe/picoblog">JsonChart Fork on GitHub</a></li>
<li><a href="https://github.com/bmc/picoblog">PicoBlog on GitHub</a></li>
<li><a href="http://brizzled.clapper.org/id/77/">Writing Blogging Software for Google App Engine</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/10/17/blogging-with-google-app-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Force Directed Graph with Raphael</title>
		<link>http://jasonrowe.com/2010/09/25/force-directed-graph-with-raphael/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=force-directed-graph-with-raphael</link>
		<comments>http://jasonrowe.com/2010/09/25/force-directed-graph-with-raphael/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 01:49:11 +0000</pubDate>
		<dc:creator>Jason</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Raphael]]></category>
		<category><![CDATA[SVG]]></category>

		<guid isPermaLink="false">http://jasonrowe.com/?p=1360</guid>
		<description><![CDATA[Trigger Graph &#160; I’ve recently been looking around the Canvas and SVG development space and things have changed. Many amazing drawing and charting libraries are now available. The one in particular that caught my eye was Raphael. As the site&#8230;]]></description>
			<content:encoded><![CDATA[<div style="margin-left:20px">
<div id="canvas"></div><a href="#" onclick="StartGraph();return false">Trigger Graph</a></div>
<script type="text/javascript" src="http://jasonrowe.com/misc/raphael-min.js"></script>

  <script type="text/javascript">

        var paper = null;

        var _nodes = new Array();

        StartGraph();

        var intervalID;

        function Animate() {
            var loop = 0;
            return setInterval(function () {
                ApplyForces(_nodes, 29, 0.35, 1);
                loop++;

                if (loop > 15) {
                    clearInterval(intervalID);
                }
            }, 200);
        }

        function Clear() {
            clearInterval(intervalID);
            paper.clear()
        }

        function StartGraph() {

            clearInterval(intervalID);

            if (paper !== null) {
                paper.clear();
                paper.remove();
            }

            paper = Raphael("canvas", 320, 200);

            // rectangle with rounded corners
            var c = paper.rect(1, 0, 305, 190, 10);

            _nodes = [];

            for (var i = 0; i < 20; i++) {

                var randomnumberX = Math.floor(Math.random() * 30);
                var randomnumberY = Math.floor(Math.random() * 30);

                var circle = paper.circle(120 + randomnumberX, 90 + randomnumberY, 10);

                circle.attr("fill", "#f00");

                circle.attr("stroke", "#fff");

                var element = { "circle": circle, "mass": 20, "line": null };

                element.IsConnectedTo = function (node) {


                    node.circle.attr("cx")
                    var nodeX = this.circle.attr("cx");
                    var nodeY = this.circle.attr("cy");

                    var otherNodeX = node.circle.attr("cx");
                    var otherNodeY = node.circle.attr("cy");

                    var d = Distance(nodeX, nodeY, otherNodeX, otherNodeY);

                    if (d < 30) 
                    {
                        if (d > 15) 
                        {//hack for wordpress formatting doesnt allow and sign in if...

                            if (this.line === null) {
                                this.line = paper.path("M{0},{1}L{2},{3}", nodeX, nodeY, otherNodeX, otherNodeY);
                                this.line.attr({ stroke: "#f00" });
                            }

                            if (node.line === null) {
                                node.line = paper.path("M{0},{1}L{2},{3}", otherNodeX, otherNodeY, nodeX, nodeY);
                                node.line.attr({ stroke: "#f00" });
                            }

                            return true;
                        }
                        // hack for wordpress formatting
                        if (this.line !== null) {
                            this.line.remove();
                            this.line = null;
                        }

                        return false;

                     }
                else {

                        if (this.line !== null) {
                            this.line.remove();
                            this.line = null;
                        }

                        return false;
                    }

                };

                _nodes.push(element)

            }

            intervalID = Animate();
        }

        function Distance(x1, y1, x2, y2) {

            return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));

        }


        function ApplyForces(nodes, spring, charge, damping) {

            for (var i in nodes) {

                var node = nodes[i];

                for (var j in nodes) {
                    var otherNode = nodes[j];

                    if (node != otherNode) {

                        var iniOtherNodePosition = otherNode.circle.getBBox();
                        var iniNodePosition = node.circle.getBBox();

                        var dx = iniOtherNodePosition.x - iniNodePosition.x;

                        var dy = iniOtherNodePosition.y - iniNodePosition.y;

                        var hypotenuse = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

                        var force = 0;

                        if (node.IsConnectedTo(otherNode)) {

                            force = (hypotenuse - spring) / 2.0;
                        }
                        else {

                            force = -((node.mass * otherNode.mass) / Math.pow(hypotenuse, 2)) * charge;

                        }

                        dx /= hypotenuse;

                        dy /= hypotenuse;

                        dx *= force;

                        dy *= force;

                        var nodeCxSum = node.circle.attr("cx") + dx;

                        if (nodeCxSum < 0) {
                            nodeCxSum = 15;
                        }

                        if (nodeCxSum > 310) {
                            nodeCxSum = 290;
                        }


                        node.circle.attr({ cx: nodeCxSum });

                        var nodeCySum = node.circle.attr("cy") + dy;

                        if (nodeCySum < 0) {
                            nodeCySum = 15;
                        }

                        if (nodeCySum > 190) {
                            nodeCySum = 170;
                        }

                        node.circle.attr({ cy: nodeCySum });
                    }
                }


                var cxValue = node.circle.attr("cx");

                var nodePosition = node.circle.getBBox();


                var nodeX = nodePosition.x + cxValue;

                if (nodeX < 0) {
                    nodeX = 15;
                }

                if(nodeX > 310)
                {
                    nodeX = 290;
                }

                node.circle.attr({ x: nodeX });

                var cyValue = node.circle.attr("cy");

                var nodeY = nodePosition.y + cyValue;

                if(nodeY < 0)
                {
                    nodeY = 15;
                }

                if (nodeY > 190) {
                    nodeY = 170;
                }

                node.circle.attr({ y: nodeY });

                if (cxValue < 0) {
                    nodeY = 0;
                }

                if (cxValue > 310) {
                    nodeY = 290;
                }

                if (cyValue < 0) {
                    nodeY = 15;
                }

                if (cyValue > 190) {
                    nodeY = 170;
                }

                node.circle.attr({ cx: cxValue * damping });

                node.circle.attr({ cy: cyValue * damping });
            }

        }
    </script>



<p>&nbsp;</p> <p>I’ve recently been looking around the Canvas and SVG development space and things have changed. Many amazing drawing and charting libraries are now available. The one in particular that caught my eye was <a href="http://raphaeljs.com/">Raphael</a>. As the site says, “Raphael is a small JavaScript library that should simplify your work with vector graphics on the web” and it does.</p> 

<p>I decided to try out the library by building a <a href="http://en.wikipedia.org/wiki/Force-based_algorithms_%28graph_drawing%29">force directed graph</a>. Mine is a pretty simple one and I probably didn’t get all the calculations exactly correct but the point wasn’t really the graph. It was trying out the library and I’m really glad I did. Here is what the graph looks like. Hopefully you saw a working example at the top of this post.</p> 

<a href="http://jasonrowe.com/wp-content/uploads/2010/09/ForceGraphCapture.png"><img src="http://jasonrowe.com/wp-content/uploads/2010/09/ForceGraphCapture.png" alt="" title="ForceGraphCapture" width="325" height="210" class="alignright size-full wp-image-1380" /></a>

<p>As you can see it’s rendered in SVG for supported browsers and VML in IE. I’ve only tested this in the latest versions of Google, Firefox, and IE so sorry if all you see is a broken element or script error.</p> <p>What I really like about the library is it does not focus on one particular thing like charts or plotting. It’s just a drawing library. It has a great focus on providing easy to use shapes and paths. I was able to prototype the graph very quickly. I was shocked at how well it worked across all the browsers.</p>

<p>So I encourage you to go try the Raphael library. You will be building interesting scalable images in no time.</p>]]></content:encoded>
			<wfw:commentRss>http://jasonrowe.com/2010/09/25/force-directed-graph-with-raphael/feed/</wfw:commentRss>
		<slash:comments>2</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;]]></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: c#; ">
 

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&#039;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;]]></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;]]></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>
	</channel>
</rss>

<!-- Dynamic page generated in 0.825 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-09 04:13:37 -->

