<?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>House of Metnetsky &#187; programming</title>
	<atom:link href="http://cowarthill.com/blog/index.php/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://cowarthill.com/blog</link>
	<description>Run Tortoise Run</description>
	<lastBuildDate>Fri, 26 Feb 2010 17:15:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>VSTO Outlook Add-ins &#8211; Reference Leaks</title>
		<link>http://cowarthill.com/blog/index.php/2010/01/01/vsto-outlook-add-ins-reference-leaks/</link>
		<comments>http://cowarthill.com/blog/index.php/2010/01/01/vsto-outlook-add-ins-reference-leaks/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 16:51:20 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[vsto]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=359</guid>
		<description><![CDATA[Not too long ago I came across an annoying issue with my Outlook Add-in which creates a form region at the bottom of the contact and distribution list inspector windows. Apparently, if you edit certain fields (like check-boxes) when a VSTO add-in is loaded the reference count is not properly decremented which leaves the OutlookItem in [...]]]></description>
			<content:encoded><![CDATA[<p>Not too long ago I came across an annoying issue with my Outlook Add-in which creates a form region at the bottom of the contact and distribution list inspector windows. Apparently, if you edit certain fields (like check-boxes) when a <a href="http://blogs.msdn.com/vsto/" target="_blank">VSTO</a> add-in is loaded the reference count is not properly decremented which leaves the <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.contactitem.aspx" target="_blank">OutlookItem</a> in an edited state.</p>
<p>To fix the issue you have to edit some auto-generated <a href="http://blogs.msdn.com/vsto/" target="_blank">VSTO</a> code and release the <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.contactitem.aspx" target="_blank">OutlookItem</a> during a setup event like so:</p>
<pre class="brush: csharp; title: ; notranslate">
private void RegionFactory_FormRegionInitializing(object sender, Outlook.FormRegionInitializingEventArgs e)
{
    Marshal.ReleaseComObject(e.OutlookItem);
}
</pre>
<p>This block of code can be found in the region block labeled: <strong>#region Form Region Factory</strong></p>
<p>Apparently, a Microsoft <a href="http://blogs.msdn.com/pcreehan/default.aspx" target="_blank">support engineer</a> posted about this back in <a href="http://blogs.msdn.com/pcreehan/archive/2008/08/07/form-region-leak-in-visual-studio-tools-for-office-2008-v3-template.aspx" target="_blank">August of 2008</a>, but I never came across it until after working with a different very nice MSDN support engineer.</p>
<p>The other day however, I realized that the trick above does not in fact work for Distribution List (<a href="http://msdn.microsoft.com/en-us/library/bb157886.aspx" target="_blank">IPM.DistList</a>) form regions. Watch the following video for proof!</p>
<div class="aligncenter">
[See post to watch Flash video]
</div>
<p>I contacted the very nice engineer who helped me before to re-open/create a support ticket about the issue. While waiting for a response however, I kept trying to fix the issue and finally did. I&#8217;m quite hopeful that my fix is not the best answer, as it&#8217;s truly a bizarre hack.</p>
<p>Take a look at the Designer code generated for your region. The <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.tools.outlook.iformregionfactory.aspx" target="_blank">IFormRegionFactory</a> which creates an instance of the actual ImportedFormRegion does not need to return anything for the region to load. In fact, if you throw an exception from <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.tools.outlook.iformregionfactory.createformregion.aspx" target="_blank">IFormRegionFactory.CreateFormRegion</a>, the <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.distlistitem.aspx" target="_blank">DistListItem</a> is properly unreferenced when the inspector is closed.</p>
<p>You can watch the following video to see it in action!</p>
<div class="aligncenter">
[See post to watch Flash video]
</div>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2010/01/01/vsto-outlook-add-ins-reference-leaks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://cowarthill.com/blog/wp-content/uploads/2009/12/dist-bad.flv" length="16759864" type="video/x-flv" />
<enclosure url="http://cowarthill.com/blog/wp-content/uploads/2009/12/dist-good.flv" length="67887874" type="video/x-flv" />
<enclosure url="http://cowarthill.com/blog/wp-content/uploads/2009/12/dist-bad.ogg" length="3891624" type="audio/ogg" />
		</item>
		<item>
		<title>VSTO Outlook Add-ins &#8211; Getting Contacts from Distribution Lists</title>
		<link>http://cowarthill.com/blog/index.php/2009/12/29/vsto-outlook-add-ins-distribution-list-recipients/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/12/29/vsto-outlook-add-ins-distribution-list-recipients/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 23:33:06 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[vsto]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=336</guid>
		<description><![CDATA[A while ago I was tasked with creating an Outlook Add-in that enables a user to opt-in their contacts for synchronization with a KMBS product named Page Scope Enterprise Suite (PSES). Part of this add-in is to offer a panel at the bottom of every contact so they can be opt-ed in for synchronization like [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I was tasked with creating an Outlook Add-in that enables a user to opt-in their contacts for synchronization with a <a href="http://kmbs.konicaminolta.us/" target="_blank">KMBS</a> product named <a href="http://kmbs.konicaminolta.us/content/products/models/pagescopeenterprise.html" target="_blank">Page Scope Enterprise Suite (PSES)</a>. Part of this add-in is to offer a panel at the bottom of every contact so they can be opt-ed in for synchronization like so:</p>
<p><a href="http://cowarthill.com/blog/wp-content/uploads/2009/12/contact.png"><img class="aligncenter size-medium wp-image-339" title="Outlook Contact Form Region" src="http://cowarthill.com/blog/wp-content/uploads/2009/12/contact-300x218.png" alt="Outlook Contact Form Region" width="300" height="218" /></a></p>
<p>As you can see this isn&#8217;t very fancy &#8211; two check-boxes to control if you want the email and/or fax addresses sent along to PSES. Naturally, there is also an option to opt-in distribution lists:</p>
<p><a href="http://cowarthill.com/blog/wp-content/uploads/2009/12/group1.png"><img class="aligncenter size-medium wp-image-341" title="Outlook Distribution Form Region" src="http://cowarthill.com/blog/wp-content/uploads/2009/12/group1-300x226.png" alt="Outlook Distribution Form Region" width="300" height="226" /></a></p>
<p>This is of course where the fun began. In my personal opinion distribution lists were not properly implemented, or rather updated from earlier versions of Outlook. For instance, take a close look at the image above. Notice how a &#8220;fax&#8221; address is listed under the &#8220;E-mail&#8221; column? Do you also notice how it has the @ symbol? What in the world is going on here?</p>
<p>Another issue is how the ContactItem relates to the Recipient &#8211; or rather how you can obtain the actual contact from the item in the distribution list. Based on documentation we should be able to use the <strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.addressentry.getcontact.aspx" target="_blank">GetContact()</a></strong> method found a little ways down on the <strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.recipient.aspx" target="_blank">Recipient</a></strong> class.</p>
<pre class="brush: csharp; title: ; notranslate">
Outlook.Recipient.AddressEntry.GetContact()
</pre>
<p>Sadly however, this doesn&#8217;t work (for me at-least) no matter what I did. So after a decent amount of trial and error I was able to determine that a Recipient&#8217;s <strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.recipient.entryid.aspx" target="_blank">EntryID</a></strong> actually contains the the Contact&#8217;s <strong><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._contactitem.entryid.aspx" target="_blank">EntryID</a></strong>.</p>
<p>For example:</p>
<pre class="brush: csharp; title: ; notranslate">
Recipient.EntryID = &quot;abcd-1234&quot;;
Contact.EntryID = &quot;1234&quot;;
</pre>
<p>This is simplified of course as real ID&#8217;s are quite long. So to actually get the contact we should do this:</p>
<pre class="brush: csharp; title: ; notranslate">
Outlook.Recipient r = DistListItem.GetMember(1);
string rid = r.EntryID;
rid = rid.Substring(rid.Length - 48);

Outlook.ContactItem c = Application.Session.GetItemFromID(rid, null) as Outlook.ContactItem;
</pre>
<p>Hopefully someone else will find this mess useful as I couldn&#8217;t find anything a year ago about these oddities and issues.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/12/29/vsto-outlook-add-ins-distribution-list-recipients/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>log4net PatternString</title>
		<link>http://cowarthill.com/blog/index.php/2009/12/23/log4net-patternstring/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/12/23/log4net-patternstring/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 20:30:10 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[mono]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=316</guid>
		<description><![CDATA[I&#8217;ve been using log4net since it was first available for Mono and barely know anything about it. To a certain extent you&#8217;ve got to love it because of that &#8211; it just works! The project is great, but development appears somewhat stagnant. Either way, I&#8217;ve never needed to know much more than basic configuration and [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using <a href="http://logging.apache.org/log4net/" target="_blank">log4net</a> since it was first available for <a href="http://mono-project.com/" target="_blank">Mono</a> and barely know anything about it. To a certain extent you&#8217;ve got to love it because of that &#8211; it just works! The project is great, but development appears somewhat stagnant. Either way, I&#8217;ve never needed to know much more than basic configuration and how to get it monitored even though I&#8217;ve used it for daemons, client applications, Add-ins, etc.</p>
<p>Today however, I learned something! A while ago I needed to have the <em><a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.RollingFileAppender.html" target="_blank">RollingFileAppender</a></em> log to a varying location depending on Windows version (XP vs Vista/7). At the time I found posts showing me how to use variables within the &#8220;file&#8221; option like so:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;file value=&quot;${APPDATA}\Company\Product\logs\data.log&quot; /&gt;
</pre>
<p>Not having looked at the log4net code this is either explicitly converted to a user&#8217;s roaming folder, or it is replaced as an environment variable. This works great for applications that should log per user, but what if I needed the <a href="http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx" target="_blank">&#8220;All Users&#8221; roaming folder on Windows</a>?  Neither <em>${COMMONAPPDATA}</em> or <em>${ALLUSERAPPDATA}</em> worked for me so I needed another option that would cut it.</p>
<p><strong>Enter <a href="http://logging.apache.org/log4net/release/sdk/log4net.Util.PatternConverter.html" target="_blank">log4net.Util.PatternConverter</a></strong></p>
<p>By extending this very simple class and implementing one method we can now do variable substitution. The syntax leaves a lot to be desired, but hey &#8211; it works!</p>
<pre class="brush: xml; title: ; notranslate">
&lt;file type=&quot;log4net.Util.PatternString&quot;&gt;
  &lt;converter&gt;
    &lt;name value=&quot;sub&quot; /&gt;
    &lt;type value=&quot;SpecialFolderPathConverter, Assembly&quot; /&gt;
  &lt;/converter&gt;
  &lt;conversionPattern value=&quot;%sub{ApplicationData}\Company\Product\logs\addin.log&quot; /&gt;
&lt;/file&gt;
</pre>
<p>With this setup now all I have to do is create the <em><strong>Assembly.SpecialFolderPathConverter</strong></em> class:</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.IO;

namespace Assembly
{
    public class SpecialFolderPathConverter : log4net.Util.PatternConverter
    {
        protected override void Convert(TextWriter writer, object state)
        {
            // Option gets set to contents of {}
            if (String.IsNullOrEmpty(this.Option))
                return;

            try {
                Environment.SpecialFolder sf = (Environment.SpecialFolder)
                    Enum.Parse(typeof(Environment.SpecialFolder), this.Option, true);

                writer.Write(Environment.GetFolderPath(sf));
            } catch (Exception) {
            }
        }
    }
}
</pre>
<p>As you can probably see this class takes any string within the <strong>{}</strong> brackets following <strong>%sub</strong> and replaces it using <strong><a href="http://msdn.microsoft.com/en-us/library/14tx8hby.aspx" target="_blank">Environment.GetFolderPath</a></strong> which is quite simple, and helpful.</p>
<p>Thank you <a href="http://logging.apache.org/log4net/" target="_blank">log4net</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/12/23/log4net-patternstring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Mighty &#8220;Success Exception&#8221;</title>
		<link>http://cowarthill.com/blog/index.php/2009/10/02/the-mighty-success-exception/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/10/02/the-mighty-success-exception/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 12:54:40 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[humor]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=295</guid>
		<description><![CDATA[For all those Java programmers who feel lonely in the land of .NET &#8211; here&#8217;s a class just for you!]]></description>
			<content:encoded><![CDATA[<p>For all those Java programmers who feel lonely in the land of .NET &#8211; here&#8217;s a class just for you!</p>
<pre class="brush: csharp; title: ; notranslate">
using System;

namespace Biz.Your.Company.Goes.Here.Util
{
	public sealed class SuccessException : Exception
	{
		public SuccessException() : base()
		{
			System.Environment.Exit(1);
		}

		public SuccessException(string msg) : base(msg)
		{
			System.Environment.Exit(1);
		}

		public SuccessException(string msg, Exception exception) : base(msg, exception)
		{
			System.Environment.Exit(1);
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/10/02/the-mighty-success-exception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mono Embedded &#8211; Your Own .NET Plugin</title>
		<link>http://cowarthill.com/blog/index.php/2009/08/27/mono-embedded-one/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/08/27/mono-embedded-one/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 19:25:38 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[embed]]></category>
		<category><![CDATA[mono]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=284</guid>
		<description><![CDATA[I&#8217;ve embedded either for fun or work a number of languages to see what hosting them in C is like &#8211; both for performance and ease of marshalling. So far I&#8217;m impressed with the internals of Mono, but feel like there&#8217;s a lack of proper GOTCHA&#8217;s documented anywhere. Some are spread out around the web, [...]]]></description>
			<content:encoded><![CDATA[<div>I&#8217;ve embedded either for fun or work a number of languages to see what hosting them in C is like &#8211; both for performance and ease of marshalling. So far I&#8217;m impressed with the internals of Mono, but feel like there&#8217;s a lack of proper GOTCHA&#8217;s documented anywhere. Some are spread out around the web, but most don&#8217;t directly state key points. As such, I&#8217;m going to be posted a few as I come across them.</p>
<p>WARNING: Some of this may not make complete sense without reading <a href="http://www.mono-project.com/Embedding_Mono" target="_blank">http://www.mono-project.com/Embedding_Mono</a> first.</p>
<p><strong>Creating Objects</strong><br />
Like the above docs day, all you really need to do is:</p>
<pre class="brush: cpp; title: ; notranslate">
/* get handle for class from assembly */
MonoImage *image = mono_assembly_get_image(MonoAssembly*);
MonoClass *klass = mono_class_from_name(image, &quot;Namespace&quot;, &quot;Class&quot;);

/* instantiate class and call .ctor (as they're nothing more than methods) */
MonoObject *obj = mono_object_new(MonoDomain*, klass);
mono_runtime_init(obj); /* call .ctor w/out args */
</pre>
<p><strong>Reusing Objects</strong><br />
If you need to reuse this new MonoObject instance EVER I would highly suggest calling <strong>mono_gchandle_new(MonoObject*, pinned)</strong> otherwise the GC will get to it before you want it again &#8211; I GUARANTEE THIS. The reason this happens is because objects created from your C code have no real &#8220;SCOPE&#8221;, so they&#8217;re collected quickly just like they were local variables in a method. Read the following link, it&#8217;s helpful:</p>
<p><a href="http://www.go-mono.org/docs/index.aspx?link=xhtml%3Adeploy%2Fmono-api-gchandle.html" target="_blank">http://www.go-mono.org/docs/index.aspx?link=xhtml%3Adeploy%2Fmono-api-gchandle.html</a></p>
<p>As a side note, you can actually call methods on objects that have been collected as long as the methods usage of `this` is only limited to `this.GetType()` (or nearly static). Try it, you&#8217;ll get some really funny results!</p>
<p><strong>Finding Methods</strong><br />
The MonoClass* struct contains (or points to) lots of lists of data. The methods of a class are essentially one big long list and each method (every single variation) is a different instance of MonoMethod*. Take a look at the following C# class:</p>
<pre class="brush: csharp; title: ; notranslate">
namespace Test
{
	public class Foo
	{
		public Foo()
		{
		}

		public void Log(int num)
		{
		}

		public void Log(string msg)
		{
		}
	}
}
</pre>
<p>NOTICE: The Log method is overloaded!</p>
<p>One way to call Foo.Log(?) is like so:</p>
<pre class="brush: cpp; title: ; notranslate">
/* get handle for class from assembly */
MonoImage *image = mono_assembly_get_image(MonoAssembly*);
MonoClass *klass = mono_class_from_name(image, &quot;Namespace&quot;, &quot;Class&quot;);

/* instantiate class and call .ctor (as they're nothing more than methods) */
MonoObject *obj = mono_object_new(MonoDomain*, klass);
mono_runtime_init(obj); /* call .ctor w/out args */

/* Get Log method from MonoClass that takes 1 argument
MonoMethod *m = mono_class_get_method_from_name(klass, &quot;Log&quot;, 1);

/* create single argument */
void *args[1] = { mono_string_new(MonoDomain*, &quot;Hello World&quot;); };

/* last argument is to capture exceptions */
mono_runtime_invoke(m, obj, args, NULL);
</pre>
<p>Any guess what might have just happened? Well, we just passed a string to the Log(int) method because <strong>mono_class_get_method_from_name</strong> returns the first one it finds, and not the one based on the type. To fix this you could write your own method which loops through MonoMethod*&#8217;s and find the correct signature or use the helper methods:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;mono/metadata/debug-helpers.h&gt;

MonoMethodDesc *d = mono_method_desc_new(&quot;:Log(int)&quot;, FALSE);
MonoMethod *m = mono_method_desc_search_in_class(d, klass);
mono_method_desc_free(d);
</pre>
<p>The <strong>mono_method_desc_*</strong> functions are extremely helpful and remove some of the crazy and changing internals &#8211; so I&#8217;d suggest using them for much of your calls.</p>
<p>Here are some further examples of the string descriptor for mono_method_desc_new:</p>
<ul>
<li>Namespace.Test:Log(string) -&gt; find Log method in Test class (requires second argument to be TRUE)</li>
<li>:Log(string) -&gt; find Log method which takes a string</li>
<li>:Log(XmlReader) -&gt; find Log method which takes an XmlReader</li>
<li>:Log(My.Namespace.XmlReader) -&gt; find the method which takes YOUR funky XmlReader</li>
</ul>
<p>As you can see it covers the gamut &#8211; so thank you to whomever created that extremely useful class/struct/function-set.</p>
</div>
<div>~ Till next time!</div>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/08/27/mono-embedded-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mono + SCGI</title>
		<link>http://cowarthill.com/blog/index.php/2009/06/10/mono-scgi/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/06/10/mono-scgi/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 21:46:13 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[scgi]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=267</guid>
		<description><![CDATA[Over a year ago I started a SCGI daemon for Mono (scgi-mono-server). For those who don&#8217;t know, the &#8220;SCGI protocol is a replacement for the Common Gateway Interface (CGI) protocol. It is a standard for applications to interface with HTTP servers. It is similar to FastCGI but is designed to be easier to implement&#8221;.I stopped [...]]]></description>
			<content:encoded><![CDATA[<div>Over a year ago I started a <a title="http://python.ca/scgi/protocol.txt" href="http://" target="_blank">SCGI</a> daemon for <a title="http://www.mono-project.com/" href="http://" target="_blank">Mono</a> (scgi-mono-server). For those who don&#8217;t know, the <a href="http://www.mems-exchange.org/software/scgi" target="_blank">&#8220;SCGI protocol is a replacement for the Common Gateway Interface (CGI) protocol. It is a standard for applications to interface with HTTP servers. It is similar to FastCGI but is designed to be easier to implement&#8221;</a>.I stopped all development shortly after I started because <a href="http://www.lighttpd.net/" target="_blank">lighttpd</a> (the web server I cared about) required a very small patch to be useful. Having supplied the <a href="http://redmine.lighttpd.net/projects/lighttpd/repository/revisions/2223/diff/branches/lighttpd-1.4.x/src/mod_scgi.c" target="_blank">patch</a> I waited around for it to be rolled into a release (<a href="http://www.lighttpd.net/2008/9/30/1-4-20-Otherwise-the-terrorists-win" target="_blank">1.4.20</a>) and then waited for it to be picked up by <a href="http://packages.ubuntu.com/search?keywords=lighttpd&amp;searchon=names&amp;suite=jaunty&amp;section=all" target="_blank">Ubuntu</a>, but it still hasn&#8217;t. So what brought it back to life? A silly bug: <a href="https://bugs.launchpad.net/ubuntu/+source/mod-mono/+bug/227781" target="_blank">https://bugs.launchpad.net/ubuntu/+source/mod-mono/+bug/227781</a>.</div>
<p>Some of our servers need both PHP5 &amp; Mono to run side-by-side so one of our guys listed the options:</p>
<div>
<ul>
<li dir="ltr">Pull mono &amp; <a href="http://www.mono-project.com/Mod_mono" target="_blank">mod-mono</a> 1.9.1 back-ports from a <a href="https://launchpad.net/ubuntu/+ppas" target="_blank">PPA</a> (<a href="http://ppa.launchpad.net/directhex/ppa/ubuntu">http://ppa.launchpad.net/directhex/ppa/ubuntu</a>)</li>
<li dir="ltr">Patch and rebuild <a href="http://www.mono-project.com/Mod_mono" target="_blank">mod-mono</a> 1.2.5 ourselves</li>
<li dir="ltr">Switch to <a href="http://en.wikipedia.org/wiki/FastCGI" target="_blank">FastCGI</a> for PHP5, so we can use apache2-mpm-worker for mod-mono-server</li>
<li dir="ltr">Switch from Apache to lighttpd (and rebuild with our patch)</li>
<li dir="ltr">Switch from Apache + mod-mono to Apache + FastCGI or SCGI (requires patching lighttpd)</li>
<li dir="ltr">Switch from Apache + mod-mono to Apache + mod_proxy for <a href="http://www.mono-project.com/ASP.NET#ASP.NET_hosting_with_XSP" target="_blank">XSP</a></li>
</ul>
<p>Given our growing dislike for Apache &amp; appreciation for lighttpd we decided on a phased approach:</p>
<ul>
<li dir="ltr">Switch PHP5 to Apache + <a href="http://en.wikipedia.org/wiki/FastCGI" target="_blank">FastCGI</a></li>
<li dir="ltr">Switch Mono to Apache + SCGI</li>
<li dir="ltr">Run for a while (make sure everything works well)</li>
<li dir="ltr">Switch from Apache to lighttpd</li>
</ul>
<p>We choose SCGI for Mono over <a href="http://en.wikipedia.org/wiki/FastCGI" target="_blank">FastCGI</a> because:</p>
<ul>
<li dir="ltr">FastCGI requires a lot of chatter between the client &amp; server</li>
<li dir="ltr">Great incentive to finally give the server to Mono</li>
</ul>
<p>With our approach in mind I started working on scgi-mono-server again, but with a new target &#8211; Apache. This shouldn&#8217;t have been very hard given that mod_scgi is provided by <strong>Quixote</strong>, but there were a few stumbling blocks. Apache, for whatever reason, has decided to break the SCGI specification (in my eyes).  As stated in the <strong>Protocol</strong>: &#8220;[t]he format of the response is not specified&#8221; &#8211; meaning whatever the SCGI server sends back to the client (Apache, lighttpd, etc) should go back to the originator (web browser). Apache however, does not honor this. </p>
<p>The first line of any HTTP response (AFAIK) should be it&#8217;s <em>Status Line</em>:</p>
<p><strong>HTTP/1.1 200 OK</strong>.</p>
<p>Apache&#8217;s mod_scgi requires that all lines until the body have a colon so that is can parse the header and update it&#8217;s internal data model. Therefore, our first line now has to be replaced by:</p>
<p><strong>Status: 200 OK</strong></p>
<p>Thankfully the <strong>Example</strong> section of the protocol showed me how to <strong><em>fix the issue</em></strong>. I&#8217;m tempted to patch Apache/mod_scgi but I&#8217;m a bit worried about how many SCGI servers require this broken code. So for now I&#8217;ve added a configuration option that can be put inside ASP.NET&#8217;s web.config to control the <strong><em>hack</em></strong>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;appSettings&gt;
	&lt;add key=&quot;MonoServerApacheStatus&quot; value=&quot;true&quot; /&gt;
&lt;/appSettings&gt;
</pre>
<p>I&#8217;ll be submitting the server back to Mono with some documentation after it goes through some solid developer testing on our side &#8211; so I hope someone enjoys!</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/06/10/mono-scgi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming Tutorial: Comments</title>
		<link>http://cowarthill.com/blog/index.php/2009/03/27/programming-tutorial-comments/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/03/27/programming-tutorial-comments/#comments</comments>
		<pubDate>Fri, 27 Mar 2009 23:38:30 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[humor]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[mono]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=260</guid>
		<description><![CDATA[Comments are only effective if they threaten abuse. Discovered by Noah Massey.]]></description>
			<content:encoded><![CDATA[<p>Comments are only effective if they threaten abuse.</p>
<pre class="brush: csharp; title: ; notranslate">
/**
 * Note: The following array MUST be sorted in order for BinarySearch to work. I have taken the liberty of
 * creating it sorted to avoid this operation. If you really feel the need to break the manual sorting,
 * uncomment the array.sort below this, and then go out and stand in front of traffic. thank you.
 */

string[] allowed_items  = {&quot;activate&quot;, &quot;restore&quot;, &quot;save&quot;, &quot;update-relay&quot;, &quot;verify-mount&quot;, &quot;verify-restore&quot;}; 

//Array.Sort(allowed_items);

if (Array.BinarySearch(allowed_items, list) &gt;= 0) {
	/* -.v.- */
}
</pre>
<p>Discovered by Noah Massey.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/03/27/programming-tutorial-comments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming Tutorial: Unreachable Code</title>
		<link>http://cowarthill.com/blog/index.php/2009/03/24/programming-tutorial-unreachable-code/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/03/24/programming-tutorial-unreachable-code/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 22:30:47 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[humor]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[shell]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=240</guid>
		<description><![CDATA[Always run non-existent commands after unreachable code. Discovered by Noah Massey.]]></description>
			<content:encoded><![CDATA[<p>Always run non-existent commands after unreachable code.</p>
<pre class="brush: bash; title: ; notranslate">
if [ `id -u` != 0 ]; then
	sudo $0
	exit $?
fi

if [ `dpkg -l | grep sun-java5 | wc -l` -eq 0 ]; then
	sh /media/cdrom0/application/appupgrade; # causes reboot
else
	sh /media/cdrom0/application/sysupgrade; # causes reboot
fi

sudo updat-java-alternatives -s java-6-sun;

exit 0;
</pre>
<p>Discovered by Noah Massey.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/03/24/programming-tutorial-unreachable-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming Tutorial: Readability</title>
		<link>http://cowarthill.com/blog/index.php/2009/03/18/programming-tutorial-readability/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/03/18/programming-tutorial-readability/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 17:01:32 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[humor]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=213</guid>
		<description><![CDATA[Readability is always more important than simple one-liners: Discovered by @zewillow.]]></description>
			<content:encoded><![CDATA[<p>Readability is always more important than simple one-liners:</p>
<pre class="brush: php; title: ; notranslate">
if ($form-&gt;minute == 0) {
	$minute = &quot;00&quot;;
} else if ($form-&gt;minute &lt; 10) {
	$minute = &quot;0&quot; . $form-&gt;minute;
} else {
	$minute = $form-&gt;minute;
}
</pre>
<p>Discovered by <a href="http://twitter.com/zewillow" target="_blank">@zewillow</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/03/18/programming-tutorial-readability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming Tutorial: Variable Initialization</title>
		<link>http://cowarthill.com/blog/index.php/2009/03/17/programming-tutorial-variable-initialization/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/03/17/programming-tutorial-variable-initialization/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 19:25:19 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[humor]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=207</guid>
		<description><![CDATA[Always make sure your variables are properly initialized: Discovered by @zewillow]]></description>
			<content:encoded><![CDATA[<p>Always make sure your variables are properly initialized:</p>
<pre class="brush: php; title: ; notranslate">
$list = $_SESSION['list'];

if ($list == null || $list == &quot;&quot;) {
	$list = $_SESSION['list'];
}
</pre>
<p>Discovered by <a href="http://twitter.com/zewillow" target="_blank">@zewillow</a></p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/03/17/programming-tutorial-variable-initialization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Web Services in .NET (Part 2)</title>
		<link>http://cowarthill.com/blog/index.php/2009/03/16/restful-web-services-in-net-part-2/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/03/16/restful-web-services-in-net-part-2/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 01:05:10 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=193</guid>
		<description><![CDATA[Now that I&#8217;ve finally got a bit of time I figured I should explain how we updated our old RESTful framework to be nice and slick. Instead of one method per class which handles all sub method variations we now have something much prettier and easier to maintain. The UserService found in the previous post [...]]]></description>
			<content:encoded><![CDATA[<p>Now that I&#8217;ve finally got a bit of time I figured I should explain how we updated our old RESTful framework to be nice and slick. Instead of one method per class which handles all sub method variations we now have something much prettier and easier to maintain. The UserService found in the previous post can now look like:</p>
<pre class="brush: csharp; title: ; notranslate">
public class UserService : RestService
{
	[RestMethod(&quot;GET&quot;, &quot;^$&quot;)]
	public IList RetrieveAll()
	{
	}

	[RestMethod(&quot;GET&quot;, @&quot;^(?&lt;id&gt;[0-9]+)$&quot;)]
	public User Retrieve(int id)
	{
	}

	[RestMethod(&quot;HEAD&quot;, @&quot;^(?&lt;name&gt;\w+)$&quot;)]
	public User Exists(string name)
	{
	}

	[RestMethod(&quot;PUT&quot;, &quot;^$&quot;, typeof(User))]
	public User Create(User user)
	{
	}

	[RestMethod(&quot;POST&quot;, &quot;^$&quot;, typeof(User))]
	public bool Update(User user)
	{
	}

	[RestMethod(&quot;DELETE&quot;, @&quot;^(?&lt;id&gt;[0-9]*)$&quot;)]
	public bool Delete(int id)
	{
	}
}
</pre>
<p>As you can see there are a lot of differences:</p>
<ul>
<li>Heavy influence from newer APIs</li>
<li>Methods can return any Type</li>
<li>Methods can take 0 or more arguments of any Type</li>
<li>RestMethodAttribute has been added to match URLs against methods</li>
</ul>
<p>Most of the code above should be self-explanatory, but in case it&#8217;s not here&#8217;s some help.</p>
<p>The method decorator <b>[RestMethod("GET", "^$")]</b> tells the framework that any HTTP GET requests against the <b>UserService</b> class without any trailing arguments (<b>http://localhost/user.r</b>) should be handled by <b>RetrieveAll()</b>.</p>
<p>The method decorator <b>[RestMethod("GET", @"^(?&lt;id&gt;[0-9]+)$&#8221;)]</b> tells the framework that any HTTP GET request against the <b>UserService</b> class which ends with a number only (<b>http://localhost/user.r/1</b>, <b>http://localhost/user.r/5000</b>, etc) should be handled by <b>Retrieve(int id)</b>. The cool thing here is that the regex group <id> will provide a match to the argument name so our function will be called with whatever number the URL ends with. So calling <b>http://localhost/user.r/25</b> where the following is the executed method will result in?</p>
<pre class="brush: csharp; title: ; notranslate">
[RestMethod(&quot;GET&quot;, @&quot;^(?&lt;id&gt;[0-9]+)$&quot;)]
public bool Retrieve(int id)
{
	return id == 25;
}
</pre>
<p><b>TRUE</b>!! Pretty simple, and very cool. Another nice feature is when the HTTP request contains a body like a POST or PUT would. So POSTing to <b>http://localhost/user.r</b> with a body of:</p>
<pre class="brush: jscript; title: ; notranslate">
{'user': {
	'first_name': 'Matthew',
	'last_name': 'Metnetsky'
}}
</pre>
<p>would call the method decorated with <b>[RestMethod("POST", "^$", typeof(User))]</b> and it&#8217;s <b>user</b> argument would actually be set assuming the class implemented a JSON serializer. All of the URL/body mappers are definable by implementing <a href="http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx" target="_blank">Binder</a> and listing them in the web.config against a Content-Type. By default there are Binders for form variables, JSON, XML, raw streams, and a few more.</p>
<p>So why might I be discussing the external API of a closed library? To PUSH innovation in the current public ones. By taking these ideas and creating an &#8220;open&#8221; version I&#8217;m sure I&#8217;d be breaking my contract so I&#8217;ve got two options:</p>
<ol>
<li>Expose our public API to entice and PUSH others to innovate</li>
<li>Get a lot of feedback which might enable me to get our library opened</li>
</ol>
<p>So&#8230;. let me know&#8230;. <img src='http://cowarthill.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/03/16/restful-web-services-in-net-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Web Services in .NET (Part 1)</title>
		<link>http://cowarthill.com/blog/index.php/2009/02/26/restful-web-services-in-net-part-1/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/02/26/restful-web-services-in-net-part-1/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 22:51:22 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=178</guid>
		<description><![CDATA[A couple of years ago I tossed together a RESTful IHttpHandlerFactory for .NET. It wasn&#8217;t amazing, but it was being used long before Microsoft et all decided to create there own. Instead of extending Page you extended RestService and implemented whatever methods you wanted. As you can probably guess the request&#8217;s HTTP Method was transformed [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of years ago I tossed together a <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" target="_blank">RESTful</a> <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttphandlerfactory.aspx" target="_blank">IHttpHandlerFactory</a> for <a href="http://msdn.microsoft.com/en-us/netframework/default.aspx" target="_blank">.NET</a>. It wasn&#8217;t amazing, but it was being used long before Microsoft et all decided to create there own. Instead of extending <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.aspx" target="_blank">Page</a> you extended RestService and implemented whatever methods you wanted.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IRestService
{
	void Head(RestEventArgs args);
	object Get(RestEventArgs args);
	object Put(RestEventArgs args);
	object Post(RestEventArgs args);
}
</pre>
<p>As you can probably guess the request&#8217;s <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" target="_blank">HTTP Method</a> was transformed into the function name and executed accordingly. If the method wasn&#8217;t &#8220;known&#8221; we would then use reflection to find the method for execution. Not to fansy as you can see, but it worked.</p>
<p>If a request was made for <b>http://localhost/app/users.r</b> the <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx" target="_blank">IHttpHandler</a> <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" target="_blank">factory</a> would load users.r and it would tell us what <a href="http://msdn.microsoft.com/en-us/library/0b0thckt.aspx" target="_blank">class</a> you assigned to it (much like <a href="http://msdn.microsoft.com/en-us/library/ydy4x04a.aspx" target="_blank">@Page</a> CodeBehind/Inherits in .aspx). From there we would instantiate the <a href="http://msdn.microsoft.com/en-us/library/0b0thckt.aspx" target="_blank">class</a> and call the appropriate <a href="http://msdn.microsoft.com/en-us/library/ms173114.aspx" target="_blank">method</a>. Whatever you returned would be marshalled for wire transfer based on it&#8217;s type.</p>
<pre class="brush: csharp; title: ; notranslate">
	class User : IXmlSerializable
	{
		/* ... */
	}

	public class UserService : RestService
	{
		public object Get(RestEventArgs args);
		{
			return new User(5, &quot;Matthew&quot;, &quot;Metnetsky&quot;);
		}
	}
}
</pre>
<p>Calling <b>http://localhost/app/users.r</b> would execute UserService::Get(..) which would return a User instance. The results are then inspected for a few different interfaces like <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" target="_blank">IXmlSerializable</a>, IJsonSerializable (one of ours), etc. Based on what is supported by the <a href="http://msdn.microsoft.com/en-us/library/ms173104.aspx" target="_blank">Type</a>, we then check if the requester supports it by interogating their <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" target="_blank">&#8220;Accepts&#8221; header</a>. This way each requester can receive what they understand how to handle (for instance &#8211; don&#8217;t send <a href="http://www.json.org/" target="_blank">JSON</a> to <a href="http://www.adobe.com/devnet/actionscript/articles/actionscript3_overview.html" target="_blank">AS3</a>). The system really worked well, and it&#8217;s simplicity made it damn fast.</p>
<p>Like all frameworks however, once it was actually in use we were able to see the pitfalls and issues. Take a look at the following URLs:</p>
<ul>
<li><b>http://localhost/app/users.r</b></li>
<li><b>http://localhost/app/users.r/1</b></li>
<li><b>http://localhost/app/users.r/matthew</b></li>
</ul>
<p>In order to handle all of the urls above the Get(RestEventArgs) method turned into one big switch/if/else conditional. Some people made it prettier than others, but the result was the same. So about 14 months ago we upgraded our framework &#8211; check back soon to see how we did it, and why I&#8217;m bringing it up now.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/02/26/restful-web-services-in-net-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PMS2 &#8211; Coming Soon to an Interweb Near You</title>
		<link>http://cowarthill.com/blog/index.php/2009/02/19/pms2-coming-soon/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/02/19/pms2-coming-soon/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 23:39:28 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[mono]]></category>
		<category><![CDATA[pms]]></category>
		<category><![CDATA[printgroove]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=158</guid>
		<description><![CDATA[A long, long time myself and two friends were working on a college project where the entire goal as I saw it was to &#8220;create&#8221; stuff. Mono was a wee lad back in 2003, but I still preferred it to Java any day of the week. So myself, Phil Tricca, and Joseph Scaduto created a [...]]]></description>
			<content:encoded><![CDATA[<p>A long, long time myself and two friends were working on a college project  where the entire goal as I saw it was to &#8220;create&#8221; stuff. <a href="http://www.mono-project.com/Main_Page" target="_blank">Mono</a> was a wee lad back in 2003, but I still preferred it to Java any day of the week. So myself, <a href="http://media.www.dailyorange.com/media/storage/paper522/news/2003/11/19/Feature/Traditional.Remedies.Come.Up.Short.In.The.Quest.For.The.Perfect.Hangover.Cure-561669.shtml" target="_blank">Phil Tricca</a>, and Joseph Scaduto created a whole framework for creating what are now called &#8220;learning communities&#8221; in <a href="http://www.mono-project.com/Main_Page" target="_blank">Mono</a>/<a href="http://www.mono-project.com/GtkSharp" target="_blank">Gtk#</a>/<a href="http://www.mono-project.com/Mod_mono" target="_blank">mod_mono</a>.</p>
<p>One of the pieces we needed was a databases abstraction layer (we had grand ideas) so we first sought to flush out the <a href="http://msdn.microsoft.com/en-us/library/ms971512.aspx" target="_blank">ObjectSpaces</a> API for Mono. Sadly, Microsoft couldn&#8217;t get their act together so we built our own. So in honor of Microsoft we called it Phil-And-Matt Spaces, shortened to PMS. After it&#8217;s original debut it sat on the selves for quite some time until I started working for <a href="http://kmbs.konicaminolta.us/" target="_blank">Konica Minolta Business Solutions</a> and was tasked with creating <a href="http://kmbs.konicaminolta.us/content/products/models/printgroove.html" target="_blank">Printgroove</a>. PMS hit the spot (man that sounds funny) &#8211; it was far from bad, but it certainly wasn&#8217;t awesome. At the point of its resurrection it needed a face lift, but never got one.</p>
<p>It&#8217;s now been years since <a href="http://kmbs.konicaminolta.us/content/products/models/printgroove.html" target="_blank">Printgroove</a> got started and PMS has continued to work well for it and numerous other projects &#8211; but I&#8217;ve got an itch that must be scratched. So while working on a small web service only project I&#8217;ve been adding in a couple dozen extra hours to mature PMS &#8211; or basically throw away it&#8217;s entire user facing API.</p>
<p>Here&#8217;s a sneak peak of whats to come:</p>
<pre class="brush: csharp; title: ; notranslate">
// - Pull IDbConnection from pool based on unique name (from config file)
// - This is useful if you have multiple databases to chat with
// - Not specifying a name will load the one marked default or the first one found
using (DbBroker cxt = new DbBroker(&quot;name-mapping-to-config-connection-string&quot;)) {

    // SELECT member.* FROM member WHERE username LIKE '%a%' ORDER BY id
	// Enumerate through results without storing Member objects in container
	foreach (Member m in cxt.Query&lt;Member&gt;().Like(&quot;username&quot;, &quot;%a%&quot;).OrderBy(&quot;id&quot;).Exec())
		Console.WriteLine(&quot; : &quot; + m);

	// Use raw SQL and ignore chainable methods for generation
	// Store results in List&lt;Member&gt; and then iterate through it
	string sql = &quot;SELECT member.* FROM member where username LIKE '%a%' ORDER BY id&quot;;
	foreach (Member m in cxt.Exec&lt;Member&gt;().Objects&lt;List&lt;Member&gt;&gt;(sql))
		Console.WriteLine(&quot; : &quot; + m);

	// get first member
	Console.WriteLine(&quot;first: &quot; + cxt.Query&lt;Member&gt;().Exec().First());

	// a short-cut to get the first member since we aren't filtering etc
	Console.WriteLine(&quot;first: &quot; + cxt.Exec&lt;Member&gt;().First());

	// SELECT COUNT(member.*) FROM member WHERE id &gt; 50000
	// Use generics to cast the output of ExecuteScalar to an Int32
	Console.WriteLine(&quot;count: &quot; + cxt.Query&lt;Member&gt;().Filter(&quot;id &gt; 50000&quot;).Exec().Count&lt;int&gt;());

	// Directly call ExecuteScalar but use generics to cast the output
    sql = &quot;SELECT id FROM member WHERE username='mimetnet'&quot;;
	Console.WriteLine(&quot;scalar: &quot; + cxt.Exec&lt;Member&gt;().Scalar&lt;int&gt;(sql));

	// Directly call ExecuteReader() with our generated SQL
	// SELECT id,username FROM member WHERE id &gt; 68665
	using (IDataReader reader = cxt.Query&lt;Member&gt;()
									.GreaterThan(&quot;id&quot;, 68665)
									.SetColumns(&quot;id,username&quot;)
									.Exec()
									.Reader()) {
		while (reader.Read()) {
			Console.WriteLine(&quot;Member(id={0}, name='{1}')&quot;, reader[0], reader[1]);
		}
	}
}
</pre>
<p>Please send me your thoughts/concerns/nightmares.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/02/19/pms2-coming-soon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Annoyances: header()</title>
		<link>http://cowarthill.com/blog/index.php/2009/02/10/php-annoyances-header/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/02/10/php-annoyances-header/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 04:04:23 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=138</guid>
		<description><![CDATA[Earlier today, and yesterday in fact, I was successfully downloading generated PDF&#8217;s from a FLEX application from an Apache2 server via mod_php5. Tonight however, it kept failing with an IOErrorEvent #2038. There&#8217;s lots of fun references to this issue like this one. Sadly downloading via FileReference doesn&#8217;t trigger the HTTPStatusEvent event, so I can&#8217;t lie [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier today, and yesterday in fact, I was successfully downloading generated PDF&#8217;s from a FLEX application from an Apache2 server via mod_php5. Tonight however, it kept failing with an IOErrorEvent #2038. There&#8217;s lots of fun references to this issue like this <a target="_blank">one</a>. Sadly downloading via FileReference doesn&#8217;t trigger the HTTPStatusEvent event, so I can&#8217;t lie to FLEX.</p>
<p>I eventually stopped brute forcing an attempt and intelligently looked at Apache2&#8242;s logs and found this wonderful line:</p>
<p><em style="font-size:6">10.10.220.130 &#8211; - [10/Feb/2009:20:24:16 -0500] &#8220;GET /vrm/Create_Report.php?download=vrm_report_17_10-10-220-130.pdf HTTP/1.1&#8243; 1 68856 &#8220;-&#8221; &#8220;Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; &#8230;)&#8221;</em></p>
<p>Do you notice whats wrong? No? Look for the 1 after &#8220;HTTP/1.1&#8243; and before the &#8220;68856&#8243; &#8211; this is where the HTTP Status Code should be. Eh? What happened? Where&#8217;d my status go? The server-side looked like this:</p>
<pre class="brush: php; title: ; notranslate">
if (file_exists($file)) {
	header('Content-Type', 'application/octet-stream', true);
	header('Content-Disposition', 'attachment/filename=' . $filename, true);
	header('Content-Length', filesize($file), true);
	header('Content-Description', 'File Transfer');
	readfile($file);
}
</pre>
<p>Any one notice the issue &#8211; header is being use inappropriately. The first argument should be the entire response header, the second argument is the option to override a matching header, and the third is the status code. &#8220;true&#8221; evaluates &#8220;1&#8243; and thus the status of 1. You might ask as I am right now: Why is he divulging that he&#8217;s an idiot? Well folks it goes like this:</p>
<p>It&#8217;s 10:55PM and I&#8217;ve been programming since 8:30AM to meet a deadline. Things get missed and stupid mistakes happen. The above code worked on (IIS 6 + PHP5) but failed on (Apache2 + PHP5) &#8211; and this is one of the many reasons I hate PHP. The second argument should be a boolean and should SCREAM to the error log if you don&#8217;t match the type expected. Instead it says nothing, and leaves you to your madness.</p>
<p>Anyways, lets fix the code and go home!</p>
<pre class="brush: php; title: ; notranslate">
	header('Content-Type: application/octet-stream', true, 200);
	header('Content-Disposition: attachment/filename=' . $filename, true);
	header('Content-Length: ' . filesize($file), true);
	header('Content-Description: File Transfer');
</pre>
<p><em style="font-size:8">10.10.220.130 &#8211; - [10/Feb/2009:22:14:15 -0500] &#8220;GET /vrm/Create_Report.php?download=vrm_report_1_10-10-220-130.pdf HTTP/1.1&#8243; 200 68856 &#8220;-&#8221; &#8220;Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; &#8230;)&#8221;</em></p>
<p>Gah ;-0</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/02/10/php-annoyances-header/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Replacing Flex&#8217;s Timer with Event.ENTER_FRAME</title>
		<link>http://cowarthill.com/blog/index.php/2009/02/05/replacing-flexs-timer-with-event-enter-frame/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/02/05/replacing-flexs-timer-with-event-enter-frame/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 03:54:23 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[flex]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=125</guid>
		<description><![CDATA[One of the projects I&#8217;m working on, as you might have guessed, utilizes Adobe&#8217;s AIR. After reading a few dozen optimization tips it sounded like I needed to replace four internal Timer&#8216;s because they aren&#8217;t very efficient. As I couldn&#8217;t find anything off-hand that suited my needs I rolled my own (with some optimizations by [...]]]></description>
			<content:encoded><![CDATA[<p>One of the projects I&#8217;m working on, as you might have guessed, utilizes Adobe&#8217;s <a href="http://www.adobe.com/products/air/" target="_blank">AIR</a>. After reading a <a href="http://www.craftymind.com/2008/11/20/max-2008-session-material/" target="_blank">few</a> dozen <a href="http://spreadingfunkyness.com/garbage-collection-with-flex-and-adobe-air/" target="_blank">optimization</a> tips it sounded like I needed to replace four internal <a href="http://livedocs.adobe.com/flex/3/langref/flash/utils/Timer.html" target="_blank">Timer</a>&#8216;s because they aren&#8217;t very efficient. As I couldn&#8217;t find anything off-hand that suited my needs I rolled my own (with some optimizations by Noah Massey).</p>
<p>The original code looked similar to:</p>
<pre class="brush: jscript; title: ; notranslate">
private var timer:Timer = new Timer(15000); // run every 15 seconds

private function onCreation(event:Event):void {
	this.timer.addEventListener(TimerEvent.TIMER, this.onTimer, false, 0, true);
	this.timer.start();
}

private function onTimer(event:TimerEvent):void {
	/* do something */
}
</pre>
<p>I didn&#8217;t want to totally refactor all of my code because that would have been an amazing waste of time. So I ran through my usage of &#8220;timer&#8221; and realized what I needed to be able to do:</p>
<ul>
<li>start</li>
<li>stop</li>
<li>change interval</li>
<li>create run-once functions like setTimeout, but tied to frames</li>
</ul>
<p>With this in mind I typed up what I wanted and after a bit of tweaking my usage now looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
private function onCreation(event:Event):void {
	FrameActivity.assign('someName', 15, this.onTimer);

	this.addEventListener(Event.ENTER_FRAME, FrameActivity.handleFrame, false, 0, true);
}

private function onTimer(event:Event):void {
	/* do something */
}
</pre>
<p>If you like what you see, send me a comment and I&#8217;ll happily provide the code.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/02/05/replacing-flexs-timer-with-event-enter-frame/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AS3 Reflection</title>
		<link>http://cowarthill.com/blog/index.php/2009/01/28/as-reflection/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/01/28/as-reflection/#comments</comments>
		<pubDate>Wed, 28 Jan 2009 22:48:57 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=117</guid>
		<description><![CDATA[Type discovery, better known as reflection, is rather odd in Flex. There is no type system to describe the types like sooo many languages offer (even PHP5 finally got it right). The closest that I know of is flash.utils.describeType which is quite weird as it returns XML. The DTD for the XML is ugly to [...]]]></description>
			<content:encoded><![CDATA[<p>Type discovery, better known as reflection, is rather odd in Flex. There is no type system to describe the types like sooo many languages offer (even <a href="http://us.php.net/oop5.reflection" target="_blank">PHP5</a> finally got it right). The closest that I know of is <a  target="_blank"  href="http://livedocs.adobe.com/flex/3/langref/flash/utils/package.html#describeType()">flash.utils.describeType</a> which is quite weird as it returns <a href="http://livedocs.adobe.com/flex/3/langref/XML.html"  target="_blank">XML</a>. The DTD for the XML is ugly to me, but everyone has their opinions. A simple class like..</p>
<pre class="brush: jscript; title: ; notranslate">
public final class EmployeeTitle extends BaseModel
{
	public var id:Number = NaN;
	public var title:String = '';

	public function EmployeeTitle()
	{
		super();
	}

	public static function fromXML(xml:XML):EmployeeTitle
	{
		return null; /* we should do something important here */
	}
}
</pre>
<p>turns into the following XML&#8230;</p>
<pre class="brush: xml; title: ; notranslate">
&lt;type name=&quot;kmbs.model::EmployeeTitle&quot; base=&quot;kmbs.model::BaseModel&quot; isDynamic=&quot;false&quot; isFinal=&quot;true&quot; isStatic=&quot;false&quot;&gt;
  &lt;extendsClass type=&quot;kmbs.model::BaseModel&quot;/&gt;
  &lt;extendsClass type=&quot;Object&quot;/&gt;
  &lt;variable name=&quot;id&quot; type=&quot;Number&quot;/&gt;
  &lt;variable name=&quot;title&quot; type=&quot;String&quot;/&gt;
  &lt;method name=&quot;assignXML&quot; declaredBy=&quot;kmbs.model::BaseModel&quot; returnType=&quot;void&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;XML&quot; optional=&quot;false&quot;/&gt;
  &lt;/method&gt;
  &lt;method name=&quot;toString&quot; declaredBy=&quot;kmbs.model::BaseModel&quot; returnType=&quot;String&quot;/&gt;
  &lt;method name=&quot;toXML&quot; declaredBy=&quot;kmbs.model::BaseModel&quot; returnType=&quot;XML&quot;/&gt;
&lt;/type&gt;
</pre>
<p>As I was looking for a way to marshal the type to XML for pushing to the server it seems like this was the closest I was going to get. So I wrote some code and got the basics working no problem. A few days ago I realized that most of my models would be a bit more useful if they were [Bindable] and thus dispatched events about their changes (lets keep those interfaces up to date eh?). So I added what .NET calls attributes and Flex calls metadata tags.. [Bindable] to my class.</p>
<pre class="brush: jscript; title: ; notranslate">
[Bindable]
public final class EmployeeTitle extends BaseModel
{
	/* .... */
}
</pre>
<p>Once I did this however, none of my XML marshaling was working because apparently the type descriptor is now <strong>totally</strong> different.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;type name=&quot;kmbs.model::EmployeeTitle&quot; base=&quot;kmbs.model::BaseModel&quot; isDynamic=&quot;false&quot; isFinal=&quot;true&quot; isStatic=&quot;false&quot;&gt;
  &lt;extendsClass type=&quot;kmbs.model::BaseModel&quot;/&gt;
  &lt;extendsClass type=&quot;Object&quot;/&gt;
  &lt;implementsInterface type=&quot;flash.events::IEventDispatcher&quot;/&gt;
  &lt;method name=&quot;addEventListener&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot; returnType=&quot;void&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;String&quot; optional=&quot;false&quot;/&gt;
    &lt;parameter index=&quot;2&quot; type=&quot;Function&quot; optional=&quot;false&quot;/&gt;
    &lt;parameter index=&quot;3&quot; type=&quot;Boolean&quot; optional=&quot;true&quot;/&gt;
    &lt;parameter index=&quot;4&quot; type=&quot;int&quot; optional=&quot;true&quot;/&gt;
    &lt;parameter index=&quot;5&quot; type=&quot;Boolean&quot; optional=&quot;true&quot;/&gt;
  &lt;/method&gt;
  &lt;accessor name=&quot;id&quot; access=&quot;readwrite&quot; type=&quot;Number&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot;&gt;
    &lt;metadata name=&quot;Bindable&quot;&gt;
      &lt;arg key=&quot;event&quot; value=&quot;propertyChange&quot;/&gt;
    &lt;/metadata&gt;
  &lt;/accessor&gt;
  &lt;method name=&quot;hasEventListener&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot; returnType=&quot;Boolean&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;String&quot; optional=&quot;false&quot;/&gt;
  &lt;/method&gt;
  &lt;method name=&quot;dispatchEvent&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot; returnType=&quot;Boolean&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;flash.events::Event&quot; optional=&quot;false&quot;/&gt;
  &lt;/method&gt;
  &lt;method name=&quot;willTrigger&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot; returnType=&quot;Boolean&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;String&quot; optional=&quot;false&quot;/&gt;
  &lt;/method&gt;
  &lt;method name=&quot;removeEventListener&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot; returnType=&quot;void&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;String&quot; optional=&quot;false&quot;/&gt;
    &lt;parameter index=&quot;2&quot; type=&quot;Function&quot; optional=&quot;false&quot;/&gt;
    &lt;parameter index=&quot;3&quot; type=&quot;Boolean&quot; optional=&quot;true&quot;/&gt;
  &lt;/method&gt;
  &lt;accessor name=&quot;title&quot; access=&quot;readwrite&quot; type=&quot;String&quot; declaredBy=&quot;kmbs.model::EmployeeTitle&quot;&gt;
    &lt;metadata name=&quot;Bindable&quot;&gt;
      &lt;arg key=&quot;event&quot; value=&quot;propertyChange&quot;/&gt;
    &lt;/metadata&gt;
  &lt;/accessor&gt;
  &lt;method name=&quot;assignXML&quot; declaredBy=&quot;kmbs.model::BaseModel&quot; returnType=&quot;void&quot;&gt;
    &lt;parameter index=&quot;1&quot; type=&quot;XML&quot; optional=&quot;false&quot;/&gt;
  &lt;/method&gt;
  &lt;method name=&quot;toString&quot; declaredBy=&quot;kmbs.model::BaseModel&quot; returnType=&quot;String&quot;/&gt;
  &lt;method name=&quot;toXML&quot; declaredBy=&quot;kmbs.model::BaseModel&quot; returnType=&quot;XML&quot;/&gt;
&lt;/type&gt;
</pre>
<p>As you can see all of the variable tags have been replaced by accessor tags. And methods have been added in order to perform the Event handling/dispatching, but apparently the class doesn&#8217;t extend something special. Instead the compiler seemingly injects raw methods, which bothers me for some reason.</p>
<p>As you can see I find Flex&#8217;s internals rather <strong>weird</strong> instead of <strong>smart</strong>, but as I said, everyone has their opinions.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/01/28/as-reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Monthly Calendars in PHP for Flex</title>
		<link>http://cowarthill.com/blog/index.php/2009/01/21/php-flex-xml-calendar/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/01/21/php-flex-xml-calendar/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 01:00:05 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=96</guid>
		<description><![CDATA[At work I recently had a need to create a monthly calendar within Flex and populated with data from a web-service (created in PHP). I hate reinventing the wheel, but I also hate wasting time searching for a solution to a simple enough problem. So below you can find a quick answer to the problem [...]]]></description>
			<content:encoded><![CDATA[<p>At work I recently had a need to create a monthly calendar within Flex and populated with data from a web-service (created in PHP). I hate reinventing the wheel, but I also hate wasting time searching for a solution to a simple enough problem. So below you can find a quick answer to the problem as I couldn&#8217;t find one myself.</p>
<p><strong>PHP</strong>: The following code creates a simple XML feed.</p>
<hr />
<pre class="brush: php; title: ; notranslate">
&lt;?php
	/**
	 * Create a XML calendar for a given year &amp;amp; month
	 *
	 * Noah Massey &amp;amp; Matthew Metnetsky
	 */
	function calendar_xml($doc, $year, $month)
	{
		if (!$doc) throw new Exception('doc is bad');
		if (!$month) throw new Exception('month  is bad');
		if (!$year) throw new Exception('year is bad');

		$numDays = date('t', mktime(0, 0, 0, $month, 1, $year));

		$monthNode = $doc-&gt;appendChild($doc-&gt;createElement('month'));

		$day = 1 - date('w', mktime(0, 0, 0, $month, 1, $year));

		do {
			$weekNode = $monthNode-&gt;appendChild($doc-&gt;createElement('week'));

			for ($y=0;$y&lt;7 and $day &lt;= $numDays; $day++,$y++) {
				//$sunday = ($day == $y);
				//$sunday = ($day == ($y + 6));
				$dayNode = $weekNode-&gt;appendChild($doc-&gt;createElement('day'));
				$numAttr = $doc-&gt;createAttribute('num');
				$numAttr-&gt;appendChild($doc-&gt;createTextNode($day));
				$dayNode-&gt;appendChild($numAttr);

				/*
				 * we could loop through database records here for holidays etc
				 * the _real_ version uses mktime(0, 0, 0, $month, $day, $year)
				 * to check for a stamp within an array of holiday records
				 * and then tack on some more nodes to $dayNode
				 */
			}
		} while ($day &lt;= $numDays);
	}

	$doc = new DOMDocument('1.0', 'UTF-8');
	$doc-&gt;formatOutput = true;

	$date = getdate();
	$year = (int) (array_key_exists('year', $_GET))? $_GET['year'] : $date['year'];
	$month = (int) (array_key_exists('month', $_GET))? $_GET['month'] : $date['mon'];

	calendar_xml($doc, $year, $month);
	header('Content-Type: application/xml', true);
	echo($doc-&gt;saveXML());
?&gt;
</pre>
<p>If you look at the rather large comment block above you can see where the value comes in. It&#8217;s pretty simple to use a unix timestamp to find records which you actually would want in the XML like holidays, events, etc.</p>
<p>The basic output looks like the following, and can be see in full at <a target="_blank" href="http://cowarthill.com/blog/wp-content/uploads/2009/01/calendar-xml.php">http://cowarthill.com/blog/wp-content/uploads/2009/01/calendar-xml.php</a></p>
<pre class="brush: xml; title: ; notranslate">
	&lt;month&gt;
		&lt;week&gt;
			&lt;day num=&quot;{day of month}&quot; /&gt;
		&lt;/week&gt;
	&lt;/month&gt;
</pre>
<hr />
Once you have all of this in place you need to pull it into Flex. I found using a DataGrid very easy once you have the XML from the web service. And to customize the display I created a custom itemRenderer for the DataGridColumns. Here&#8217;s a few snippets&#8230;.</p>
<p><strong>MXML:</strong> Lets define our DataGrid and our HTTPService which will retrieve our data.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:DataGrid id=&quot;dg&quot;
	sortableColumns=&quot;false&quot;
	draggableColumns=&quot;false&quot;
	selectable=&quot;false&quot;
	showScrollTips=&quot;true&quot;
	horizontalScrollPolicy=&quot;off&quot;
	verticalScrollPolicy=&quot;off&quot;&gt;
	&lt;mx:columns&gt;
		&lt;mx:DataGridColumn headerText=&quot;Sunday&quot; itemRenderer=&quot;calendar.MonthCell&quot; /&gt;
		&lt;mx:DataGridColumn headerText=&quot;Monday&quot; itemRenderer=&quot;calendar.MonthCell&quot; /&gt;
		&lt;mx:DataGridColumn headerText=&quot;Tuesday&quot; itemRenderer=&quot;calendar.MonthCell&quot; /&gt;
		&lt;mx:DataGridColumn headerText=&quot;Wednesday&quot; itemRenderer=&quot;calendar.MonthCell&quot; /&gt;
		&lt;mx:DataGridColumn headerText=&quot;Thursday&quot; itemRenderer=&quot;calendar.MonthCell&quot;  /&gt;
		&lt;mx:DataGridColumn headerText=&quot;Friday&quot; itemRenderer=&quot;calendar.MonthCell&quot; /&gt;
		&lt;mx:DataGridColumn headerText=&quot;Saturday&quot; itemRenderer=&quot;calendar.MonthCell&quot; /&gt;
	&lt;/mx:columns&gt;
&lt;/mx:DataGrid&gt;

&lt;mx:HTTPService id=&quot;calHS&quot;
	url=&quot;http://localhost/project/calendar-xml.php&quot;
	method=&quot;GET&quot;
	result=&quot;handleCalXML(event);&quot;
	fault=&quot;Alert.show('Failed to retrieve XML from server');&quot;
	resultFormat=&quot;e4x&quot;
	contentType=&quot;application/xml&quot;/&gt;
</pre>
<p><strong>AS3:</strong> Now we need at least two functions: 1 to call the service and retrieve the XML; and a second take the response and assign it to the DataGrid.</p>
<pre class="brush: jscript; title: ; notranslate">
/* month should be 1-based (January) */
public function retrieveCalendar():void
{
	calHS.url = 'http://localhost/project/calendar-xml.php?year=' + year + '&amp;amp;month=' + month;
	calHS.send();
}

/* handle the results from from calendar-xml.php */
private function handleCalXML(event:ResultEvent):void
{
	var weeks:XMLList = event.result.week as XMLList;

	/* dg is defined above in the MXML */
	this.dg.dataProvider = dayInfo;
	this.dg.rowCount = weeks.length(); // grid show be no bigger than necessary
}
</pre>
<p>Now we&#8217;re going to create a reusable itemRenderer which is instantiated for each cell in the DataGrid. You can do this in MXML directly, but I like AS3. The most important function to focus on is the setter for data because it assigns the values based on the XML we received.</p>
<pre class="brush: jscript; title: ; notranslate">
package calendar
{
	import mx.collections.XMLListCollection;
	import mx.controls.TextArea;
	import mx.controls.listClasses.BaseListData;
	import mx.controls.listClasses.IDropInListItemRenderer;
	import mx.controls.listClasses.IListItemRenderer;
	import mx.core.IDataRenderer;
	import mx.events.FlexEvent;

	public class MonthCell  extends TextArea
							implements IDataRenderer, IDropInListItemRenderer, IListItemRenderer
	{
		private var _week:XMLListCollection = null;
		private var _day:XML = null;
		private var _listData:BaseListData;

		public function MonthCell()
		{
			super();

			this.editable = false;
			this.wordWrap = true;
			this.selectable = false;
		}

		[Bindable(FlexEvent.DATA_CHANGE)]
		public override function get listData():BaseListData
		{
			return this._listData;
		}

		public override function set listData(ldata:BaseListData):void
		{
			if (this._listData != ldata) {
			this._listData = ldata;
			this.dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
			}
		}

		[Bindable(FlexEvent.DATA_CHANGE)]
		public override function get data():Object
		{
			return this._week;
		}

		public override function set data(value:Object):void
		{
			var xml:XML = value as XML;

			if (xml) {
				// convert XML to a list for extra methods
				this._week = new XMLListCollection(xml.children());

				// make sure we've got enough records in week
				// to be able to get the current day
				if (this._week.length &gt; this.listData.columnIndex) {
					this._day = this._week.getItemAt(this.listData.columnIndex) as XML;
				} else {
					this._day = null; // clear in-case we're reused
				}
			}

			// do we have a valid day XML object
			if (this._week == null || this._day == null || int(this._day.@num) &lt; 1) {
				this.htmlText = &quot;&quot;;
			} else {
				/* lets display the day of the month in the cell */
				this.htmlText = &quot;&lt;p&gt;&lt;b&gt;&quot; + this._day.@num + &quot;&lt;/b&gt;&lt;/p&gt;&quot;;
			}

			this.invalidateProperties();
			this.dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/01/21/php-flex-xml-calendar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Filtering File Selectors</title>
		<link>http://cowarthill.com/blog/index.php/2009/01/17/filtering-file-selectors/</link>
		<comments>http://cowarthill.com/blog/index.php/2009/01/17/filtering-file-selectors/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 17:54:27 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[gtk]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=16</guid>
		<description><![CDATA[Why is it that almost every language/framework offers totally different, and yet similar, solutions for filtering in/out files from selection menus? .NET In the example there are two types of selectors: text files (.txt); all files (*.*). Labels (Text files) are separated from their filter values (*.txt) by the pipe character and each filter type [...]]]></description>
			<content:encoded><![CDATA[<p>Why is it that almost every language/framework offers totally different, and yet similar, solutions for filtering in/out files from selection menus?</p>
<hr />
<h3>.NET</h3>
<pre class="brush: csharp; title: ; notranslate">OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = &quot;Text files (*.txt)|*.txt|All files (*.*)|*.*&quot;</pre>
<p>In the example there are two types of selectors: text files (.txt); all files (*.*). Labels (Text files) are separated from their filter values (*.txt) by the pipe character and each filter type is separated by&#8230; a pipe too! It looks weird, but considering it&#8217;s based off old-school Windows API I can understand and sort of respect their desire to not change. MFC sucks and using weird DSLs instead of creating more objects can have it&#8217;s <em>benefits</em>.</p>
<hr />
<h3>Flash</h3>
<pre class="brush: jscript; title: ; notranslate">var filters:Array = new Array();
filters.push(new FileFilter('Text Files', '*.txt'));
filters.push(new FileFilter('Rich Text', '*.rtf'));

var file:flash.net.FileReference = new FileReference();
file.browse(filters);</pre>
<p>FileFilter is constructed with the rules like so: FileFilter(&#8216;Text Files&#8217;, &#8216;*.txt&#8217;). You can either specify multiple FileFilters or append multiple rulsets to the same label like so: FileFilter(&#8216;Text files&#8217;, &#8216;*.txt;*.txt2&#8242;). Truly a cleaner interface than .NET&#8217;s, but many could argue it&#8217;s Object over kill (AWT/SWING is probably worse).</p>
<hr />
<h3>Gtk+</h3>
<pre class="brush: cpp; title: ; notranslate">GtkFileFilter *file_filter = gtk_file_filter_new();
gtk_file_filter_set_name(file_filter, &quot;Log Files (*.bab)&quot;);
gtk_file_filter_add_pattern(file_filter, &quot;*.bab&quot;);</pre>
<p>Even though Gtk+ is in C, it has a nice interface (which many languages like Flash could be accused of robbing). The name is different than the pattern, and there aren&#8217;t ugly crazy separators like in .NET/MFC.</p>
<hr />
<h3>Swing</h3>
<pre class="brush: java; title: ; notranslate">ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension(&quot;jpg&quot;);
filter.addExtension(&quot;gif&quot;);
filter.setDescription(&quot;JPG &amp;amp;amp;amp; GIF Images&quot;);

JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(filter);</pre>
<p>This isn&#8217;t too bad until you realize that <a title="ExampleFileFilter" href="http://kickjava.com/src/demo/swingset/ExampleFileFilter.java.htm" target="_blank">ExampleFileFilter</a> is a custom class which extends abstract <a title="FileFilter" href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/filechooser/FileFilter.html" target="_blank">FileFilter</a>. Yes there are other ways, but boy is this annoying!</p>
<hr />
<h3>Python (Gtk+)</h3>
<pre class="brush: python; title: ; notranslate">
        dialog = gtk.FileChooserDialog(title=&quot;Select the World&quot;
                            , action=gtk.FILE_CHOOSER_ACTION_OPEN
                            , buttons=(gtk.STOCK_CANCEL
                                                    , gtk.RESPONSE_CANCEL
                                                    , gtk.STOCK_OPEN
                                                    , gtk.RESPONSE_OK))
        filter = gtk.FileFilter()
        filter.set_name(&quot;All files&quot;)
        filter.add_pattern(&quot;*&quot;)
        dialog.add_filter(filter)
</pre>
<p>Just like Gtk+ but with the Python-esk feel.</p>
<hr />
<h3>Conclusion</h3>
<p>I must be stating the obvious: Framework developers hate programmers.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2009/01/17/filtering-file-selectors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Array.length anybody?</title>
		<link>http://cowarthill.com/blog/index.php/2008/12/03/js-array-length/</link>
		<comments>http://cowarthill.com/blog/index.php/2008/12/03/js-array-length/#comments</comments>
		<pubDate>Wed, 03 Dec 2008 23:12:44 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[ie7]]></category>
		<category><![CDATA[ie8]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=76</guid>
		<description><![CDATA[I came across a fun little issue today that I think should have been more obvious to me. Apparently, and I can&#8217;t believe I&#8217;m saying this: IE and Firefox parse Javascript differently. Take the following code: What should the length be? In Firefox 2 &#38; 3 the length is 2, but in IE7/IE8 the length [...]]]></description>
			<content:encoded><![CDATA[<p>I came across a fun little issue today that I think should have been more obvious to me. Apparently, and I can&#8217;t believe I&#8217;m saying this: IE and Firefox parse Javascript differently. Take the following code:</p>
<pre class="brush: jscript; title: ; notranslate">
var foo = [
{'one': 1},
{'two': 2},
];
</pre>
<p>What should the length be? In Firefox 2 &amp; 3 the length is 2, but in IE7/IE8 the length is 3. I can&#8217;t confirm this, but considering I figured this out due to a *NEW* bug in one of our products, I think this is <strong>somewhat</strong> new in IE.</p>
<p>On a side note, it&#8217;s interesting that IE even parses the above considering the following code will break:</p>
<pre class="brush: jscript; title: ; notranslate">
var foo = {
'one': 1,
'two': 2,
}
</pre>
<p>The difference here is of course that <strong>foo</strong> in the second example is an <strong>object</strong>, whereas the first example it&#8217;s an <strong>array</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2008/12/03/js-array-length/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Internet Explorer Quirks: 204</title>
		<link>http://cowarthill.com/blog/index.php/2008/12/02/internet-explorer-quirks-204/</link>
		<comments>http://cowarthill.com/blog/index.php/2008/12/02/internet-explorer-quirks-204/#comments</comments>
		<pubDate>Wed, 03 Dec 2008 00:50:11 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[ie7]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[printgroove]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=52</guid>
		<description><![CDATA[A long time ago when I first started doing a lot of REST + Ajax developement I hit a really strange issue. Apparently, if your server returns a HTTP Status code of 204 in response to a POST method IE partially blows up. Part of this has to do with IE requiring try/catch blocks around [...]]]></description>
			<content:encoded><![CDATA[<p>A long time ago when I first started doing a lot of REST + Ajax developement I hit a really strange issue. Apparently, if your server returns a HTTP Status code of 204 in response to a POST method IE partially blows up. Part of this has to do with IE requiring try/catch blocks around code that could be devastating &#8211; like XMLHttpRequest.send()? And part of it has to do with IE not parsing a 204 response.</p>
<p>Upon receipt of 204 IE appears to halt parsing as the XMLHttpRequest instance becomes corrupt and is no longer usable. Checking true/false against the instance works (and is false), but querying a method or variable from the instance produces an error.</p>
<pre class="brush: jscript; title: ; notranslate">
var xhr = null;

try {
    // without try/catch IE throws error for no good reason
    xhr = new Ajax.Request(url, options);
} catch (exe) {
    /* will never fail on IE for 204 */
    console.error(exe);
}

// xhr is invalid for IE + POST + 204
if (xhr) {
    resp = xhr.transport;
} else if (/^post$/i.test(method) &amp;&amp; this.isInternetExplorer()) {
    resp = this.FAKE_204_RESPONSE();
}
</pre>
<p>I vaguely remember reading on some site that IE fails on POST + 204 because it helps the browser short circuit and keep from redrawing the interface from a &lt;form/&gt; submission. This <strong><em>sort of</em></strong> makes sense because you can then upload/POST form data without having to redraw the page and still know if everything succeeded.</p>
<p>Either way, it is truly annoying. And the only reason I&#8217;m evening posting about this, other than education and helping myself remember, is that my original comments around the code above was vulgar. It happened to have been 3AM or so and my polite-o-meter wasn&#8217;t working well. It is now almost three years later and I believe some people have seen the original comments and didn&#8217;t find it appropriate &#8211; to which they are correct.</p>
<p>With that said &#8211; Internet Explorer has some weird quirks.</p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2008/12/02/internet-explorer-quirks-204/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IE7, IE8 Beta2&#8230; meet &lt;object/&gt;</title>
		<link>http://cowarthill.com/blog/index.php/2008/11/25/ie7-ie8-beta2-meet-object/</link>
		<comments>http://cowarthill.com/blog/index.php/2008/11/25/ie7-ie8-beta2-meet-object/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 01:26:57 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[ie7]]></category>
		<category><![CDATA[ie8]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=27</guid>
		<description><![CDATA[Why is it that IE7 and IE8 Beta 2 still can&#8217;t quit get the &#60;object/&#62; tag correct? When using Javascript to &#8220;dynamically&#8221; add object tags to the interface my experience, bad luck, and bouts of pain teach me that using the DOM API just doesn&#8217;t cut it. Well, to be fair the following functions don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Why is it that IE7 and IE8 Beta 2 still can&#8217;t quit get the &lt;object/&gt; tag correct? When using Javascript to &#8220;dynamically&#8221; add object tags to the interface my experience, bad luck, and bouts of pain teach me that using the DOM API just doesn&#8217;t cut it. Well, to be fair the following functions don&#8217;t cut it:</p>
<ul>
<li>document.createElement</li>
<li>document.createAttribute</li>
<li>[DOMElement].setAttribute(key, value)</li>
<li>[DOMElement].setAttributeNode([DOMAttribute])</li>
</ul>
<p>For any and all other &#8220;dynamic&#8221; HTML modifications the above functions work great! But if I use them to embed Flash or Silverlight movies it just tanks. Instead you have to construct ugly strings that represent the HTML you want and use [DOMElement].innerHTML. When you do this, suddenly the .swf/.xap loads and all is well.</p>
<p>Why oh why?</p>
<p>And for anyone who cares, following file does a decent job of HTML generation within Javascript&#8230; except for IE and the &lt;object/&gt; tag&#8230;. and input of type radio (WTF!).</p>
<p><a href="http://cowarthill.com/blog/wp-content/uploads/2008/11/html_obj.js">http://cowarthill.com/blog/wp-content/uploads/2008/11/html_obj.js</a></p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2008/11/25/ie7-ie8-beta2-meet-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Silverlight vs. Flash</title>
		<link>http://cowarthill.com/blog/index.php/2008/11/24/silverlight-vs-flash/</link>
		<comments>http://cowarthill.com/blog/index.php/2008/11/24/silverlight-vs-flash/#comments</comments>
		<pubDate>Tue, 25 Nov 2008 00:03:15 +0000</pubDate>
		<dc:creator>MET</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[kmbs]]></category>
		<category><![CDATA[printgroove]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://cowarthill.com/blog/?p=3</guid>
		<description><![CDATA[I&#8217;ve been a long time hater of Flash as a web-service consumer because of its inability to use any HTTP method other than GET or POST. People revert to stupid URL argument tricks like ?_method=DELETE and actually use a GET or POST, neither of which work if your service layer is actually &#8230; truly &#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been a long time hater of Flash as a web-service consumer because of its inability to use any HTTP method other than GET or POST. People revert to stupid URL argument tricks like ?_method=DELETE and actually use a GET or POST, neither of which work if your service layer is actually &#8230; truly &#8230; RESTful.</p>
<p>Silverlight has the same damn issue. Apparently none of the blog posts I read a WHILE back (2+ yrs) mentioned the fact that Flash, and now Silverlight, use the lowest common denominator for their web request classes&#8230;. NPAPI (Gecko/Mozilla Plugin SDK). I&#8217;m sure there are good reasons for using the embedded ones, security, re-usability, performance too &#8211; but it&#8217;s rather annoying!</p>
<p>Why the NPAPI developers don&#8217;t augment the API, I have no idea. But at least Silverlight allows for a HTML event to trigger the OpenFileDialog.ShowDialog() without having to do fun invisible overlays.</p>
<p>Silverlight:<br />
<a class="moz-txt-link-freeext" href="http://wilcob.com/Wilco/Silverlight/http-requests-in-silverlight.aspx">http://wilcob.com/Wilco/Silverlight/http-requests-in-silverlight.aspx</a></p>
<p>Flash:<a class="moz-txt-link-freetext" href="http://www.adobe.com/devnet/flashplayer/articles/fplayer10_security_changes_02.html#head34"></p>
<p>http://www.adobe.com/devnet/flashplayer/articles/fplayer10_security_changes_02.html#head34</p>
<p></a><a class="moz-txt-link-freetext" href="http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html">http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html<br />
</a><a class="moz-txt-link-freetext" href="http://theflashblog.com/?p=423">http://theflashblog.com/?p=423</a></p>
]]></content:encoded>
			<wfw:commentRss>http://cowarthill.com/blog/index.php/2008/11/24/silverlight-vs-flash/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

