<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Flying Pies</title>
	<atom:link href="http://flyingpies.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://flyingpies.wordpress.com</link>
	<description>A pie in the sky, with a barndoor for wings and strapped to a stronger engine. Modest forays into coding land.</description>
	<lastBuildDate>Fri, 23 Dec 2011 21:06:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='flyingpies.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Flying Pies</title>
		<link>http://flyingpies.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://flyingpies.wordpress.com/osd.xml" title="Flying Pies" />
	<atom:link rel='hub' href='http://flyingpies.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Creating several Microsoft Tags at once</title>
		<link>http://flyingpies.wordpress.com/2011/05/25/creating-several-microsoft-tags/</link>
		<comments>http://flyingpies.wordpress.com/2011/05/25/creating-several-microsoft-tags/#comments</comments>
		<pubDate>Thu, 26 May 2011 06:16:53 +0000</pubDate>
		<dc:creator>Oren Trutner</dc:creator>
				<category><![CDATA[Microsoft-Tag]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://flyingpies.wordpress.com/?p=153</guid>
		<description><![CDATA[Microsoft tags are a type of barcode you can scan with your mobile phone. They connect physical objects and printed material to text, images and media on the web. You may have seen them printed in magazine ads, billboards, or product packaging. Anyone can create and print tags. Microsoft&#8217;s tag manager lets you sign up [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=153&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Microsoft tags are a type of barcode you can scan with your mobile phone. They connect physical objects and printed material to text, images and media on the web. You may have seen them printed in magazine ads, billboards, or product packaging. Anyone can create and print tags. Microsoft&#8217;s <a href="http://tag.microsoft.com">tag manager</a> lets you sign up and create tags for free. You can point your tags at your website pages, and import their images to any graphic software that you use to create printed material.</p>
<div id="attachment_211" class="wp-caption alignnone" style="width: 360px"><a href="http://flyingpies.files.wordpress.com/2011/05/some-sample-tags.png"><img class="size-full wp-image-211" title="Some sample tags" src="http://flyingpies.files.wordpress.com/2011/05/some-sample-tags.png?w=630" alt="Some sample tags"   /></a><p class="wp-caption-text">Some sample tags</p></div>
<p>The Tag manager website is great for creating a handful of tags. If you have to create more of them, however, Tag manager can become tiring, and fast. To that end, Microsoft provides the Tag API. The Tag API lets developers create and update several tags at once. The Tag API is available as a SOAP web service that can be invoked from numerous software environments. In this article, we will put together a small .NET Framework applet that lets you create a any number of tags.</p>
<h3>Getting started with the Tag API</h3>
<p>Visit <a href="http://tag.microsoft.com/developer/index.aspx">http://tag.microsoft.com/developer/index.aspx</a> to get acquainted with the Tag API. To get started, you will need to set up your free Tag Manager account, and then obtain an API key. If you haven&#8217;t already, go to the tag manager website and click the TAG MANAGER link at the top right to get started. The signup process is straightforward. Once inside the Tag manager, you can see your (empty) list of tags. At this point, you should be able to <a href="http://tag.microsoft.com/ws/accessrequest.aspx">request an API key</a>. The API key looks like a string of 30 or so hex digits, not unlike a GUID.</p>
<h3>Your first TagAPI program</h3>
<p>With the API key in hand, we can get started. Fire up Visual Studio, and create a new console application. In the <em>Solution Explorer</em> view, right click <em>References</em> and select <em>Add Service Reference&#8230;</em> In the <em>Add Service Reference</em> dialog window that pops up, type in the address of the Tag API: <em>https://ws.tag.microsoft.com/MIBPService.wsdl</em> and click Go. The <em>MIBPService</em> will show up in the <em>Services</em> list. If you expand it and select the <em>IMIBPContract</em> underneath, the list of supported operations will show. Modify the namespace  to &#8220;Tag&#8221; and click OK to proceed. A service reference to the Tag API will be added to your project.</p>
<div style="height:150pt;">
<div id="attachment_168" class="wp-caption alignleft" style="width: 160px"><a href="http://flyingpies.files.wordpress.com/2011/05/add-service-reference1.png"><img class="size-thumbnail wp-image-168 " title="Adding a service reference" src="http://flyingpies.files.wordpress.com/2011/05/add-service-reference1.png?w=150&#038;h=119" alt="Adding a service reference" width="150" height="119" /></a><p class="wp-caption-text">Adding a service reference</p></div>
<div id="attachment_165" class="wp-caption alignleft" style="width: 160px"><a href="http://flyingpies.files.wordpress.com/2011/05/adding-the-tag-api-service-reference1.png"><img class="size-thumbnail wp-image-165" title="Adding the Tag API service reference" src="http://flyingpies.files.wordpress.com/2011/05/adding-the-tag-api-service-reference1.png?w=150&#038;h=119" alt="Adding the Tag API service reference" width="150" height="119" /></a><p class="wp-caption-text">Adding the Tag API service reference</p></div>
</div>
<p>To use the Tag API in your program, first add a <em>using</em> statement with its namespace. I named my application &#8220;MakeTags&#8221; &#8212; use your application&#8217;s namespace as the prefix there. The second part of the namespace, &#8220;Tag&#8221;, is the value entered in the Namespace box of the <em>Add Service Reference</em> window.</p>
<p><pre class="brush: csharp;">
using namespace MakeTags.Tag;
</pre></p>
<p>To invoke Tag API services, we will need to create two objects. One represents the Tag API service, and the other represents our API key. Make sure to insert the API key you applied for into <em>creds.AccessToken</em>. In your program&#8217;s Main function, add:</p>
<p><pre class="brush: csharp;">
static void Main(string[] args)
{
    MIBPContractClient tagService = new MIBPContractClient();
    UserCredential creds = new UserCredential();
    creds.AccessToken = &quot;your-access-token-here&quot;;
}
</pre></p>
<p>To create a single Tag, we could add the following code to invoke the <a href="http://tag.microsoft.com/howto.aspx#CreateTag">CreateTag</a> method. Make sure to use a new tag title. Trying to create a tag with a title of a tag you created before will fail. Also note that the tag category has to exist before you call CreateTag. I used the &#8220;Main&#8221; category, that is supposed to be created for you on your new Tag account. But it has been a long time since I created my account, and I may be wrong. If needed, you can create a category from Tag Manager, or invoke the <a href="http://tag.microsoft.com/howto.aspx#CreateCategory">CreateCategory</a> method to create a new one.</p>
<p><pre class="brush: csharp;">
string tagTitle = &quot;Tag title here&quot;;
string category = &quot;Main&quot;;

URITag tag = new URITag();
tag.Title = tagTitle;
tag.MedFiUrl = &quot;http://flyingpies.wordpress.com/2011/05/24/creating-several-microsoft-tags&quot;;
tag.UTCStartDate = DateTime.UtcNow;
tagService.CreateTag(creds, category, tag);
</pre></p>
<p>At this point, if all is well, the program can run and create a new tag. Try it out, and look for your new tag inside Tag Manager. Running the unmodified program again will fail &#8212; because we already have a tag with this name. Modify the tag name before you run the program one more time. Here&#8217;s the complete program:</p>
<p><pre class="brush: csharp;">
using System;
using MakeTags.Tag;

namespace MakeTags {
    class Program {
        static void Main(string[] args) {
            MIBPContractClient tagService = new MIBPContractClient();
            UserCredential creds = new UserCredential();
            creds.AccessToken = &quot;your-access-token-here&quot;;

            string tagTitle = &quot;Tag title here&quot;;
            string category = &quot;Main&quot;;

            URITag tag = new URITag();
            tag.Title = tagTitle;
            tag.MedFiUrl = &quot;http://flyingpies.wordpress.com/2011/05/24/creating-several-microsoft-tags&quot;;
            tag.UTCStartDate = DateTime.UtcNow;
            tagService.CreateTag(creds, category, tag);
        }
    }
}
</pre></p>
<h3>Rendering the tags</h3>
<p>To print the tags, we will need to render them as images. The <a href="http://tag.microsoft.com/howto.aspx#CreateBarcode">GetBardcode</a> method asks the Tag API service to render the tag for us in one of several image formats. In addition to several bitmap formats (png, jpeg, gif, tiff), <em>GetBarcode</em> can also return a PDF rendering of the tag. You can also specify whether you want the rendered tag to include instructions for the user to download the tag mobile phone app.</p>
<p>Adding the following at the bottom of the program almost does what you would expect:</p>
<p><pre class="brush: csharp;">
string tagImageFilePath = &quot;mytag.png&quot;;
byte[] tagImageBytes = tagService.GetBarcode(
    creds,
    category,
    tagTitle,
    ImageTypes.png,
    1f,
    DecorationType.HCCBRP_DECORATION_DOWNLOAD,
    false);
System.IO.File.WriteAllBytes(tagImageFilePath, tagImageBytes);
</pre></p>
<p>If you run the program at this state (make sure to use a new title, or delete the old tags), it will fail in <em>GetBarcode</em>. The exception complains: &#8220;&#8230;The maximum array length quota (16384) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the&#8230;&#8221;. The service reference that we added in the beginning limited itself to 16K of data, but our tag image apparently needs a few more bytes (at our chosen image format and size, about 45K are needed.) This is easy to fix. In the application&#8217;s <em>app.config</em> file, find the line that contains <em>maxArrayLength=&#8221;16384&#8243;</em> and replace it with a higher value. I used maxArrayLength=&#8221;100000&#8243;:</p>
<p><pre class="brush: xml;">
&lt;readerQuotas maxDepth=&quot;32&quot; maxStringContentLength=&quot;8192&quot; maxArrayLength=&quot;100000&quot;
    maxBytesPerRead=&quot;4096&quot; maxNameTableCharCount=&quot;16384&quot; /&gt;
</pre></p>
<p>Now our program runs to completion, and leaves an image file of the rendered tag in its startup folder. Here&#8217;s the image created from the snippet above. Go ahead, scan it with the tag reader on your mobile phone!</p>
<div id="attachment_189" class="wp-caption alignnone" style="width: 160px"><a href="http://flyingpies.files.wordpress.com/2011/05/mytag.png"><img class="size-thumbnail wp-image-189" title="A sample rendered tag" src="http://flyingpies.files.wordpress.com/2011/05/mytag.png?w=150&#038;h=138" alt="A sample rendered tag" width="150" height="138" /></a><p class="wp-caption-text">A sample rendered tag</p></div>
<h3></h3>
<h3>Several at once</h3>
<p>Now that we know how to create and render tags, we can do so in a loop. Here&#8217;s the complete program:</p>
<p><pre class="brush: csharp;">
using System;
using System.IO;
using MakeTags.Tag;

namespace MakeTags {
    class Program {
        static void Main(string[] args) {
            MIBPContractClient tagService = new MIBPContractClient();
            UserCredential creds = new UserCredential();
            creds.AccessToken = &quot;your-access-token-here&quot;;

            int tagsToCreate = 10;
            string category = &quot;Main&quot;;
            string tagTitlePrefix = &quot;My Sample Tag &quot;;
            string tagImageFilePathFormat = &quot;mytag{0}.png&quot;;

            for (int i = 0; i &lt; tagsToCreate; ++i) {
                Console.WriteLine(&quot;Creating tag &quot; + i);

                string tagTitle = tagTitlePrefix + i;

                URITag tag = new URITag();
                tag.Title = tagTitle;
                tag.MedFiUrl = &quot;http://flyingpies.wordpress.com/2011/05/24/creating-several-microsoft-tags&quot;;
                tag.UTCStartDate = DateTime.UtcNow;
                tagService.CreateTag(creds, category, tag);

                string tagImageFilePath = string.Format(tagImageFilePathFormat, i);
                byte[] tagImageBytes = tagService.GetBarcode(
                    creds,
                    category,
                    tagTitle,
                    ImageTypes.png,
                    1f,
                    DecorationType.HCCBRP_DECORATION_DOWNLOAD,
                    false);
                File.WriteAllBytes(tagImageFilePath, tagImageBytes);
            }
        }
    }
}
</pre></p>
<div id="attachment_208" class="wp-caption alignnone" style="width: 310px"><a href="http://flyingpies.files.wordpress.com/2011/05/the-rendered-tags.png"><img class="size-medium wp-image-208" title="The rendered tags" src="http://flyingpies.files.wordpress.com/2011/05/the-rendered-tags.png?w=300&#038;h=259" alt="The rendered tags" width="300" height="259" /></a><p class="wp-caption-text">The rendered tags</p></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flyingpies.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flyingpies.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flyingpies.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flyingpies.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flyingpies.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flyingpies.wordpress.com/153/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flyingpies.wordpress.com/153/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flyingpies.wordpress.com/153/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=153&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flyingpies.wordpress.com/2011/05/25/creating-several-microsoft-tags/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86846ba709fb232a1454d7adeb6c983e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">orentrutner</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/05/some-sample-tags.png" medium="image">
			<media:title type="html">Some sample tags</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/05/add-service-reference1.png?w=150" medium="image">
			<media:title type="html">Adding a service reference</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/05/adding-the-tag-api-service-reference1.png?w=150" medium="image">
			<media:title type="html">Adding the Tag API service reference</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/05/mytag.png?w=150" medium="image">
			<media:title type="html">A sample rendered tag</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/05/the-rendered-tags.png?w=300" medium="image">
			<media:title type="html">The rendered tags</media:title>
		</media:content>
	</item>
		<item>
		<title>Performance counters types with the .NET Framework</title>
		<link>http://flyingpies.wordpress.com/2011/04/07/performance-counters-types-with-the-net-framework/</link>
		<comments>http://flyingpies.wordpress.com/2011/04/07/performance-counters-types-with-the-net-framework/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 22:52:05 +0000</pubDate>
		<dc:creator>Oren Trutner</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://flyingpies.wordpress.com/?p=92</guid>
		<description><![CDATA[NumberOfItems32 Measures a raw value: &#8220;shows the most recently observed value.&#8221; AverageCount64 Measures ITEMS per OPERATION: &#8221;how many items are processed, on average, during an operation.&#8221; AverageTimer32 Measures TIME, in seconds: &#8221;the time it takes, on average, to complete a process or operation.&#8221; This chart shows average operation time, in milliseconds. The counter actually measures the time [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=92&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>NumberOfItems32</h2>
<p>Measures a raw value: &#8220;shows the most recently observed value.&#8221;</p>
<p><a href="http://flyingpies.files.wordpress.com/2011/04/numberofitems321.png"><img class="alignnone size-medium wp-image-103" title="NumberOfItems32" src="http://flyingpies.files.wordpress.com/2011/04/numberofitems321.png?w=300&#038;h=205" alt="" width="300" height="205" /></a></p>
<p><pre class="brush: csharp;">
using System.Diagnostics;
using System.Threading;

namespace PerformanceCounterExperiments
{
    class Program
    {
        static void Main(string[] args)
        {
            string categoryName = &quot;Experimental&quot;;
            string counterName = &quot;number of items&quot;;

            // delete the category if it already exists
            if (PerformanceCounterCategory.Exists(categoryName))
            {
                PerformanceCounterCategory.Delete(categoryName);
            }

            // create the performance category and counter
            PerformanceCounterCategory.Create(
                categoryName,
                &quot;&quot;,
                PerformanceCounterCategoryType.SingleInstance,
                new CounterCreationDataCollection(new[]
                {
                    new CounterCreationData(
                        counterName,
                        &quot;&quot;,
                        PerformanceCounterType.NumberOfItems32)
                }));

            // obtain the writable counter object
            PerformanceCounter counter = new PerformanceCounter(
                categoryName,
                counterName,
                false);

            // increment the counter every 100 milliseconds
            Console.WriteLine(&quot;Starting&quot;);
            while (true)
            {
                counter.Increment();
                Thread.Sleep(100);
            }
        }
    }
}
</pre></p>
<h2>AverageCount64</h2>
<p>Measures ITEMS per OPERATION: &#8221;how many items are processed, on average, during an operation.&#8221;</p>
<p><a href="http://flyingpies.files.wordpress.com/2011/04/averagecount641.png"><img class="alignnone size-medium wp-image-115" title="AverageCount64" src="http://flyingpies.files.wordpress.com/2011/04/averagecount641.png?w=300&#038;h=206" alt="" width="300" height="206" /></a></p>
<p><pre class="brush: csharp;">
// create the performance category and counters
PerformanceCounterCategory.Create(
    categoryName,
    &quot;&quot;,
    PerformanceCounterCategoryType.SingleInstance,
    new CounterCreationDataCollection(new[]
    {
        new CounterCreationData(
            counterName,
            &quot;&quot;,
            PerformanceCounterType.AverageCount64),
        new CounterCreationData(
            counterName + &quot; base&quot;,
            &quot;&quot;,
            PerformanceCounterType.AverageBase)
    }));

// obtain the writable counter objects
PerformanceCounter counter = new PerformanceCounter(
    categoryName,
    counterName,
    false);
PerformanceCounter baseCounter = new PerformanceCounter(
    categoryName,
    counterName + &quot; base&quot;,
    false);

// increment the counter every 100 milliseconds
Console.WriteLine(&quot;Starting&quot;);
Random random = new Random();

while (true)
{
    counter.IncrementBy(50 + random.Next(-10, 10));
    baseCounter.Increment();
    Thread.Sleep(100);
}
</pre></p>
<h2>AverageTimer32</h2>
<p>Measures TIME, in seconds: &#8221;the time it takes, on average, to complete a process or operation.&#8221;</p>
<p><a href="http://flyingpies.files.wordpress.com/2011/04/averagetimer32.png"><img class="size-medium wp-image-127" title="AverageTimer32" src="http://flyingpies.files.wordpress.com/2011/04/averagetimer32.png?w=300&#038;h=210" alt="" width="300" height="210" /></a></p>
<p>This chart shows <em>average operation time</em>, in milliseconds. The counter actually measures the time in seconds. We multiplied it by x1000 in Performance Monitor, so that the 50 milliseconds value would show as 50.</p>
<p><pre class="brush: csharp;">
// create the performance category and counters
PerformanceCounterCategory.Create(
    categoryName,
    &quot;&quot;,
    PerformanceCounterCategoryType.SingleInstance,
    new CounterCreationDataCollection(new[]
    {
        new CounterCreationData(
            counterName,
            &quot;&quot;,
            PerformanceCounterType.AverageTimer32),
        new CounterCreationData(
            counterName + &quot; base&quot;,
            &quot;&quot;,
            PerformanceCounterType.AverageBase)
    }));

// obtain the writable counter objects
PerformanceCounter counter = new PerformanceCounter(
    categoryName,
    counterName,
    false);
PerformanceCounter baseCounter = new PerformanceCounter(
    categoryName,
    counterName + &quot; base&quot;,
    false);

// do a 50 msec operation every 100 msec, and measure the time
Console.WriteLine(&quot;Starting&quot;);
Random random = new Random();

while (true)
{
    // simulate an operation taking ~50 msec
    Stopwatch stopwatch = Stopwatch.StartNew();
    Thread.Sleep(50 + random.Next(-10, 10));
    stopwatch.Stop();

    // update the counter and base with the number of ticks
    // the operation took
    counter.IncrementBy(stopwatch.ElapsedTicks);
    baseCounter.Increment();

    Thread.Sleep(100);
}
</pre></p>
<h2>CountPerTimeInterval32</h2>
<p>Measures the TIME PERCENTAGE an operation takes out of a larger INTERVAL. The MSDN documentation appears to be somewhat misleading as to this counter type.</p>
<p><a href="http://flyingpies.files.wordpress.com/2011/04/countpertimeinterval32.png"><img class="alignnone size-medium wp-image-146" title="CountPerTimeInterval32" src="http://flyingpies.files.wordpress.com/2011/04/countpertimeinterval32.png?w=300&#038;h=209" alt="" width="300" height="209" /></a></p>
<p><pre class="brush: csharp;">
// create the performance category and counters
PerformanceCounterCategory.Create(
    categoryName,
    &quot;&quot;,
    PerformanceCounterCategoryType.SingleInstance,
    new CounterCreationDataCollection(new[]
    {
        new CounterCreationData(
            counterName,
            &quot;&quot;,
            PerformanceCounterType.CountPerTimeInterval32)
    }));

// obtain the writable counter objects
PerformanceCounter counter = new PerformanceCounter(
    categoryName,
    counterName,
    false);

// do a 100 msec operation every 250 msec, and measure the time
Console.WriteLine(&quot;Starting&quot;);
Random random = new Random();

while (true)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    Thread.Sleep(100);
    stopwatch.Stop();

    counter.IncrementBy(stopwatch.ElapsedTicks);

    Thread.Sleep(150);
}
</pre></p>
<h2>RateOfCountsPerSecond32</h2>
<p>Measures OPERATIONS per SECOND: &#8220;shows the average number of operations completed during each second.&#8221;</p>
<p><a href="http://flyingpies.files.wordpress.com/2011/04/rateofcountspersecond32.png"><img class="alignnone size-medium wp-image-139" title="RateOfCountsPerSecond32" src="http://flyingpies.files.wordpress.com/2011/04/rateofcountspersecond32.png?w=300&#038;h=208" alt="" width="300" height="208" /></a></p>
<p><pre class="brush: csharp;">
// create the performance category and counters
PerformanceCounterCategory.Create(
    categoryName,
    &quot;&quot;,
    PerformanceCounterCategoryType.SingleInstance,
    new CounterCreationDataCollection(new[]
    {
        new CounterCreationData(
            counterName,
            &quot;&quot;,
            PerformanceCounterType.RateOfCountsPerSecond32)
    }));

// obtain the writable counter objects
PerformanceCounter counter = new PerformanceCounter(
    categoryName,
    counterName,
    false);

// increment the counter every 100 milliseconds
Console.WriteLine(&quot;Starting&quot;);
Random random = new Random();

while (true)
{
    counter.IncrementBy(5);

    Thread.Sleep(100);
}
</pre></p>
<h2>Reference</h2>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx">http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flyingpies.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flyingpies.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flyingpies.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flyingpies.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flyingpies.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flyingpies.wordpress.com/92/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flyingpies.wordpress.com/92/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flyingpies.wordpress.com/92/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=92&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flyingpies.wordpress.com/2011/04/07/performance-counters-types-with-the-net-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86846ba709fb232a1454d7adeb6c983e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">orentrutner</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/04/numberofitems321.png?w=300" medium="image">
			<media:title type="html">NumberOfItems32</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/04/averagecount641.png?w=300" medium="image">
			<media:title type="html">AverageCount64</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/04/averagetimer32.png?w=300" medium="image">
			<media:title type="html">AverageTimer32</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/04/countpertimeinterval32.png?w=300" medium="image">
			<media:title type="html">CountPerTimeInterval32</media:title>
		</media:content>

		<media:content url="http://flyingpies.files.wordpress.com/2011/04/rateofcountspersecond32.png?w=300" medium="image">
			<media:title type="html">RateOfCountsPerSecond32</media:title>
		</media:content>
	</item>
		<item>
		<title>Signing Amazon Product Advertising API &#8211; C#/WCF &#8211; Part 2</title>
		<link>http://flyingpies.wordpress.com/2009/08/13/signing-amazon-product-advertising-api-cwcf-part-2/</link>
		<comments>http://flyingpies.wordpress.com/2009/08/13/signing-amazon-product-advertising-api-cwcf-part-2/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 22:34:53 +0000</pubDate>
		<dc:creator>Oren Trutner</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Amazon]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ECS]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://flyingpies.wordpress.com/?p=64</guid>
		<description><![CDATA[Just the sample code Download the sample project from: AmazonProductAdvtApiWcfSample.zip, 324KB, 8/1/2009 The sample is self-contained, and does not require you to read this post to use. If trying to replicate the sample&#8217;s behavior in a different program, take a look at step 2 below regarding adding the Amazon ECS service reference. Part 2 In [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=64&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Just the sample code</h2>
<p style="padding-left:30px;">Download the sample project from:</p>
<p style="padding-left:30px;"><a href="http://flyingpies.s3.amazonaws.com/AmazonProductAdvtApiWcfSample.zip">AmazonProductAdvtApiWcfSample.zip, 324KB, 8/1/2009</a></p>
<p style="padding-left:30px;">The sample is self-contained, and does not require you to read this post to use. If trying to replicate the sample&#8217;s behavior in a different program, take a look at step 2 below regarding adding the Amazon ECS service reference.</p>
<h2>Part 2</h2>
<p>In <a href="http://flyingpies.wordpress.com/2009/08/01/17/">part 1</a>, we built a simple C# console application that used WCF to send an authenticated ItemSearch request to the Amazon Product Advertising API (formerly the Amazon Associates Web Service &#8212; AWS). If you are just starting out with authenticated requests to that service, you might want to read that post first.</p>
<p>While the sample worked well for some of you, others reported difficulties with more complicated usage patterns. I will try to tackle these issues in this post. I am also updating the sample solution to include additional sample programs.</p>
<h2>Asynchronous requests</h2>
<p>The sample program in part 1 showed how to send a synchronous request to the product advertising web service. The program prepared a request object, and then called an ItemSearch method. This method sent the request, and then waited for the reply to come back. In many situations, we do not want the program to wait. Instead, we want to accomplish other tasks until the response arrives.</p>
<p>If we could send an ItemSearch request asynchronously instead, the method would return immediately, allowing the program to continue doing other things. We would then expect a callback method to be invoked when the request completes, allowing us to make use of the results. Luckily, WCF supports asynchronous methods. Here&#8217;s what you could do:</p>
<h3>Step 1 &#8211; Create a sample console application</h3>
<ol>
<li>In Visual Studio 2008, select <em>New/Project&#8230;</em> from the File menu.</li>
<li>Select <em>Console Application</em> from <em>Visual C#/Windows</em>, and enter the application&#8217;s name.</li>
<li>Click <em>OK</em></li>
</ol>
<p>Visual Studio creates a new console application. So far, this isn&#8217;t different than any other console app.</p>
<h3>Step 2 &#8211; Add a web service reference</h3>
<ol>
<li>In the <em>Solution Explorer</em> view, right click <em>References</em>, then select <em>Add Service Reference&#8230;</em></li>
<li>The <em>Add Service Reference</em> dialog appears. Type in the Amazon Product Advertising API WSDL URL in the Address box:<a href="http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl">http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl</a></li>
<li>Click <em>Go</em>. Visual Studio takes a moment to download the service description, and then populates the Services box. You should see <em>AWSECommerceService</em> in there.</li>
<li>Type in the namespace for the code that Visual Studio will generate. I used Amazon.ECS.</li>
<li>Click <em>Advanced&#8230;</em> Check the<em> Generate asynchronous operations</em> box. This will create the asynchronous versions of the methods.</li>
<li>Click OK.</li>
</ol>
<p>Visual Studio now creates a service reference and adds it to your project. You can see it under the Service References folder in Solution Explorer. Your application will now also have an app.config file added, listing WCF binding and endpoint information for the added service.</p>
<h3>Step 3 &#8211; Add the helper classes that aid in signing the requests.</h3>
<p>You can just copy and paste the Amazon.ECS.Addons folder from the sample project, with its three classes: AmazonHeader, AmazonSigningEndpointBehavior and AmazonSigningMessageInspector.</p>
<h3>Step 4 &#8211; Add code to access the product advertising API asynchronously.</h3>
<p>This code is modeled after the sample in part 1:</p>
<p><pre class="brush: csharp;">
using System;
using System.ServiceModel;
using Async.Amazon.ECS;

namespace Async {
    class Program {
        // your Amazon ID's
        private const string accessKeyId = &quot;XXXXXXXXXXXXXXXXXXXX&quot;;
        private const string secretKey   = &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;;

        // the program starts here
        static void Main(string[] args) {

            // create a WCF Amazon ECS client
            BasicHttpBinding binding       = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            binding.MaxReceivedMessageSize = int.MaxValue;
            AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
                binding,
                new EndpointAddress(&quot;https://webservices.amazon.com/onca/soap?Service=AWSECommerceService&quot;));

            // add authentication to the ECS client
            client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));

            // prepare an ItemSearch request
            ItemSearchRequest request = new ItemSearchRequest();
            request.SearchIndex       = &quot;Books&quot;;
            request.Title             = &quot;WCF&quot;;
            request.ResponseGroup     = new string[] { &quot;Small&quot; };

            ItemSearch itemSearch     = new ItemSearch();
            itemSearch.Request        = new ItemSearchRequest[] { request };
            itemSearch.AWSAccessKeyId = accessKeyId;

            // prepare to handle the results, once the async request is completed
            client.ItemSearchCompleted += (source, e) =&gt; {
                // write out the results
                foreach (var item in e.Result.Items[0].Item) {
                    Console.WriteLine(item.ItemAttributes.Title);
                }
            };

            // issue the ItemSearch request
            client.ItemSearchAsync(itemSearch);
            Console.WriteLine(&quot;Waiting for results...&quot;);

            // wait for results
            Console.ReadKey();
        }
    }
}

</pre></p>
<p>Like in part 1, this program creates a client object, associates it with an endpoint behavior that ensures requests will be authenticated, and creates an ItemSearch request object. This is where things change, however. While in part 1 our program just used the client to send the request and wait for the response. Our version is different.</p>
<p>First, we attach an event handler to the client&#8217;s <em>ItemSearchCompleted</em> event. The event handler will get called when the response to our request comes back. Our event handler here just prints out the item titles to the console. If you find the <em>(source, e) =&gt; { &#8230; }</em> syntax a bit strange &#8212; this is just a C# shorthand notation for defining a named event handler, perhaps something like <em>void RequestCompleted(object sender, ItemSearchCompletedEventArgs e) { &#8230; }</em>.</p>
<p>Only then does the program invoke the ItemSearch operation, by calling ItemSearchAsync. ItemSearchAsync sends the request to the web service, and returns immediately. At this point our program continues processing, by printing out that it&#8217;s waiting for results, and then waiting for a key press. This gives the asynchronous operation time to complete and invoke our event handler. A real application could use the opportunity to carry out real work here.</p>
<p>Note that the request is signed exactly the same way it was in part 1. There is no difference in how synchronous and asynchronous requests are authenticated. In fact, the SOAP messages look identical. The distinction is only in how these operations are used in your application.</p>
<h2>Batch requests</h2>
<p>The product advertising API allows you to combine two requests of the same type in one SOAP message. This practice is named <a href="http://docs.amazonwebservices.com/AWSECommerceService/2009-07-01/DG/index.html?BatchRequests.html">batch requests</a>. Batch requests are authenticated exactly the same way that single requests are. To try this out, follow step 1-3 above, then try out this main program:</p>
<p><pre class="brush: csharp;">
using System;
using System.ServiceModel;
using Batch.Amazon.ECS;

namespace Batch {
    class Program {
        // your Amazon ID's
        private const string accessKeyId = &quot;XXXXXXXXXXXXXXXXXXXX&quot;;
        private const string secretKey   = &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;;

        // the program starts here
        static void Main(string[] args) {

            // create a WCF Amazon ECS client
            BasicHttpBinding binding       = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            binding.MaxReceivedMessageSize = int.MaxValue;
            AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
                binding,
                new EndpointAddress(&quot;https://webservices.amazon.com/onca/soap?Service=AWSECommerceService&quot;));

            // add authentication to the ECS client
            client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));

            // prepare the first ItemSearchRequest
            ItemSearchRequest request1 = new ItemSearchRequest();
            request1.SearchIndex       = &quot;Books&quot;;
            request1.Keywords          = &quot;WCF&quot;;
            request1.ItemPage          = &quot;1&quot;;
            request1.ResponseGroup     = new string[] { &quot;Small&quot; };

            // prepare a second ItemSearchRequest
            ItemSearchRequest request2  = new ItemSearchRequest();
            request2.SearchIndex        = &quot;Books&quot;;
            request2.Keywords           = &quot;WCF&quot;;
            request2.ItemPage           = &quot;2&quot;;
            request2.ResponseGroup      = new string[] { &quot;Small&quot; };

            // batch the two requests together
            ItemSearch itemSearch       = new ItemSearch();
            itemSearch.Request          = new ItemSearchRequest[] { request1, request2 };
            itemSearch.AWSAccessKeyId   = accessKeyId;

            // issue the ItemSearch request
            ItemSearchResponse response = client.ItemSearch(itemSearch);

            // write out the results
            foreach (var item in response.Items[0].Item) {
                Console.WriteLine(item.ItemAttributes.Title);
            }
            foreach (var item in response.Items[1].Item) {
                Console.WriteLine(item.ItemAttributes.Title);
            }
        }
    }
}

</pre></p>
<p>This variation of the sample program creates two <em>ItemSearchRequest </em>objects instead of just one, and adds them as an array to an <em>ItemSearch</em> object before invoking the web service request, with:</p>
<p><pre class="brush: csharp;">
itemSearch.Request = new ItemSearchRequest[] { request1, request2 };
</pre></p>
<p>When the response is returned, the program prints out the results from both requests separately.</p>
<p>Note how the requests obtain results for the first two pages of the same query in one go. Those could have been completely different queries too.</p>
<h2>A simpler constructor for AmazonSigningEndpointBehavior</h2>
<p>A recurring stumbling block for readers of part 1 was the constructor of the AmazonSigningEndpointBehavior class. The first constructor argument was the operation name &#8212; the string that is embedded in the SOAP request as the Action header. The constructor needed to track the operation name, in order to include it as part of the request signature. For an ItemSearch operation, this value was supposed to be &#8220;ItemSearch&#8221;. For an asynchronous ItemSearchAsync operation, this value was supposed to be &#8220;ItemSearch&#8221; too.</p>
<p><pre class="brush: xml;">
&lt;s:Envelope xmlns:s=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;
  &lt;s:Header xmlns:aws=&quot;http://security.amazonaws.com/doc/2007-01-01/&quot; xmlns:a=&quot;http://schemas.microsoft.com/ws/2005/05/addressing/none&quot;&gt;
    &lt;a:Action s:mustUnderstand=&quot;1&quot;&gt;
        http://soap.amazon.com/ItemSearch
    &lt;/a:Action&gt;
    &lt;aws:AWSAccessKeyId&gt;1Y0XKFB8S7MD7GG73PR2&lt;/aws:AWSAccessKeyId&gt;
    &lt;aws:Timestamp&gt;2009-08-13T00:27:59Z&lt;/aws:Timestamp&gt;
    &lt;aws:Signature&gt;bm9FTq7HWnVgYusDaCbMyRrGTQXwA3Ji8FcdLEXAMPLE&lt;/aws:Signature&gt;
  &lt;/s:Header&gt;
</pre></p>
<p><pre class="brush: csharp;">
// add authentication to the ECS client
client.ChannelFactory.Endpoint.Behaviors.Add(
    new AmazonSigningEndpointBehavior(
        &quot;ItemSearch&quot;, accessKeyId, secretKey));
</pre></p>
<p>There was an opportunity for confusion here. Some folks placed <em>ItemSearchAsync </em>here, or <em>BeginItemSearch, </em>which wouldn&#8217;t work. To avoid the problem, the endpoint behavior constructor no longer requires an operation name. Instead, the operation is extracted from the Action header, just before the request is signed. If you are using the helper classes in the updated sample, you don&#8217;t need to do anything to take advantage of that.</p>
<p><pre class="brush: csharp;">
// extract the operation from the url in the Action header,
// past the last '/' character.
string operation = Regex.Match(
    request.Headers.Action,
    &quot;[^/]+$&quot;).ToString();
</pre></p>
<h2>MaxReceivedMessageSize</h2>
<p>Product advertising API responses can grow quite long, especially once you go beyond the puny &#8220;Small&#8221; response group. This quickly overwhelms the 16KB default limit in our WCF client code, causing an exception in <em>client.ItemSearch(&#8230;)</em>. To avoid the exception, set the MaxReceivedMessageSize property of the binding object to some larger value. The sample program does this:</p>
<p><pre class="brush: csharp;">
BasicHttpBinding binding = new BasicHttpBinding(
    BasicHttpSecurityMode.Transport);
binding.MaxReceivedMessageSize = int.MaxValue;
</pre></p>
<h2>What&#8217;s in the sample code?</h2>
<p>The <a href="http://flyingpies.s3.amazonaws.com/AmazonProductAdvtApiWcfSample.zip">sample solution</a> has three console applications:</p>
<ol>
<li>Simple &#8212; just the bare-bones sample, issuing a synchronous ItemSearch request</li>
<li>Batch &#8212; a modified version of Simple, sending two batched requests in one SOAP message</li>
<li>Async &#8212; a modified version of Simple, sending an asynchronous request and waiting for the response</li>
</ol>
<p>All three samples authenticate their requests, using the exact same three helper classes.</p>
<p>To run the samples, don&#8217;t forget to substitute your own Amazon access key and secret key, at the constants at the top of Program.cs. The samples do not include valid keys, and will not return any results from the Amazon web service without your valid keys.</p>
<p><strong>More information</strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms730059.aspx">How to: Call WCF Service Operations Asynchronously</a> (MSDN)</p>
<p>My thanks to Erica Sanders, Jason Foglia and Andrew for helping figure all this out.</p>
<br /> Tagged: .NET, Amazon, C#, ECS, WCF <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flyingpies.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flyingpies.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flyingpies.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flyingpies.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flyingpies.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flyingpies.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flyingpies.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flyingpies.wordpress.com/64/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=64&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flyingpies.wordpress.com/2009/08/13/signing-amazon-product-advertising-api-cwcf-part-2/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86846ba709fb232a1454d7adeb6c983e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">orentrutner</media:title>
		</media:content>
	</item>
		<item>
		<title>The shortest ever S3 C#/SOAP/WCF client</title>
		<link>http://flyingpies.wordpress.com/2009/08/04/the-shortest-ever-s3-csoapwcf-client/</link>
		<comments>http://flyingpies.wordpress.com/2009/08/04/the-shortest-ever-s3-csoapwcf-client/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 07:21:51 +0000</pubDate>
		<dc:creator>Oren Trutner</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Amazon]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[S3]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://flyingpies.wordpress.com/?p=53</guid>
		<description><![CDATA[Just the code Download the sample project from: AmazonS3SoapWcfSample.zip, 30KB, 8/4/2009 The sample is self-contained. You don’t need to follow any of the text in this post to build and use it. If trying to replicate the sample’s behavior in a different program, take a look at step 2 below regarding adding the Amazon S3 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=53&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Just the code</h2>
<p style="padding-left:30px;">Download the sample project from:</p>
<p style="padding-left:30px;"><a href="http://flyingpies.s3.amazonaws.com/AmazonS3SoapWcfSample.zip">AmazonS3SoapWcfSample.zip, 30KB, 8/4/2009</a></p>
<p style="padding-left:30px;">The sample is self-contained. You don’t need to follow any of the text in this post to build and use it. If trying to replicate the sample’s behavior in a different program, take a look at step 2 below regarding adding the Amazon S3 service reference</p>
<h2>The shortest ever S3 C#/SOAP/WCF client</h2>
<p>I put this together as an answer to <a href="http://stackoverflow.com/questions/1229659/amazon-s3-client-based-on-soap">a question on stackoverflow</a>. What&#8217;s the simplest, most straight-forward way to access the Amazon S3 service from a C# program? To me, the obstacle has always been with authenticating the requests. You have to dig it out of <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=129&amp;categoryID=47">Amazon&#8217;s sample code</a> set up in the days before WCF. So here&#8217;s the shortest I could get it to:</p>
<ol style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;list-style-type:decimal;list-style-position:initial;list-style-image:initial;background-position:initial initial;border:0 initial initial;margin:0 0 1em 30px;padding:0;">
<li style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;background-position:initial initial;border:0 initial initial;margin:0;padding:0;">
<p style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;clear:both;background-position:initial initial;border:0 initial initial;margin:0 0 1em;padding:0;"><strong>Step 1:</strong> Start Visual Studio 2008, create a new C# Windows console application.</p>
</li>
<li style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;background-position:initial initial;border:0 initial initial;margin:0;padding:0;">
<p style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;clear:both;background-position:initial initial;border:0 initial initial;margin:0 0 1em;padding:0;"><strong>Step 2:</strong> Add the S3 WSDL as a service reference. In Solution Explorer, right click References, select Add Service Reference. Type in the S3 WSDL address in the Address box: <a style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;color:#0077cc;text-decoration:none;cursor:pointer;background-position:initial initial;border:0 initial initial;margin:0;padding:0;" rel="nofollow" href="http://s3.amazonaws.com/doc/2006-03-01/AmazonS3.wsdl">http://s3.amazonaws.com/doc/2006-03-01/AmazonS3.wsdl</a>. Click Go. &#8220;AmazonS3&#8243; should show in the Services box. Enter a namespace. I entered Amazon.S3. Click OK.</p>
</li>
<li style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;background-position:initial initial;border:0 initial initial;margin:0;padding:0;">
<p style="font-size:14px;vertical-align:baseline;background-image:initial;background-repeat:initial;background-attachment:initial;background-color:transparent;clear:both;background-position:initial initial;border:0 initial initial;margin:0 0 1em;padding:0;"><strong>Step 3:</strong> Modify Program.cs to look something like the following:</p>
</li>
</ol>
<p><pre class="brush: csharp;">
using System;
using System.Globalization;
using System.Text;
using System.Security.Cryptography;
using AmazonS3SoapWcfSample.Amazon.S3;

namespace AmazonS3SoapWcfSample {
	class Program {
		private const string accessKeyId     = &quot;YOURACCESSKEYIDHERE0&quot;;
		private const string secretAccessKey = &quot;YOURSECRETACCESSKEYHEREANDYESITSTHATLONG&quot;;

		public static DateTime LocalNow() {
			DateTime now = DateTime.Now;
			return new DateTime(
				now.Year, now.Month, now.Day,
				now.Hour, now.Minute, now.Second,
				now.Millisecond, DateTimeKind.Local);
		}

		public static string SignRequest(string secret, string operation, DateTime timestamp) {
			HMACSHA1 hmac         = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
			string   isoTimeStamp = timestamp.ToUniversalTime().ToString(
				&quot;yyyy-MM-ddTHH:mm:ss.fffZ&quot;,
				CultureInfo.InvariantCulture);
			string   signMe       = &quot;AmazonS3&quot; + operation + isoTimeStamp;
			string   signature    = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(signMe)));
			return signature;
		}

		static void Main(string[] args) {
			DateTime       now    = LocalNow();
			AmazonS3Client client = new AmazonS3Client();

			var result = client.ListAllMyBuckets(
				accessKeyId,
				now,
				SignRequest(secretAccessKey, &quot;ListAllMyBuckets&quot;, now));

			foreach (var bucket in result.Buckets) {
				Console.WriteLine(bucket.Name);
			}
		}
	}
}

</pre></p>
<p>If you now insert your access key ID and secret access key in the appropriate spots and run the program, you should get a listing of your S3 buckets. The <em>AmazonS3Client</em> class has all the SOAP operations available as instance methods on it.</p>
<p>Works for you? Have an idea how to make it even shorter? &#8211;leave a comment.</p>
<br /> Tagged: .NET, Amazon, C#, S3, WCF <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flyingpies.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flyingpies.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flyingpies.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flyingpies.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flyingpies.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flyingpies.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flyingpies.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flyingpies.wordpress.com/53/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=53&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flyingpies.wordpress.com/2009/08/04/the-shortest-ever-s3-csoapwcf-client/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86846ba709fb232a1454d7adeb6c983e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">orentrutner</media:title>
		</media:content>
	</item>
		<item>
		<title>Signing Amazon Product Advertising API requests &#8212; the missing C# WCF sample</title>
		<link>http://flyingpies.wordpress.com/2009/08/01/17/</link>
		<comments>http://flyingpies.wordpress.com/2009/08/01/17/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 05:57:39 +0000</pubDate>
		<dc:creator>Oren Trutner</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Amazon]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ECS]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://flyingpies.wordpress.com/?p=17</guid>
		<description><![CDATA[(See also part 2 of this post) Just the sample code Download the sample project from: AmazonProductAdvtApiWcfSample.zip, 324KB, 8/1/2009 The sample is self-contained. You don&#8217;t need to follow any of the text in this post to build and use it. If trying to replicate the sample&#8217;s behavior in a different program, take a look at [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=17&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>(See also <a href="http://flyingpies.wordpress.com/2009/08/13/signing-amazon-product-advertising-api-cwcf-part-2/">part 2</a> of this post)</p>
<h2>Just the sample code</h2>
<p>Download the sample project from:</p>
<p><a href="http://flyingpies.s3.amazonaws.com/AmazonProductAdvtApiWcfSample.zip">AmazonProductAdvtApiWcfSample.zip, 324KB, 8/1/2009</a></p>
<p>The sample is self-contained. You don&#8217;t need to follow any of the text in this post to build and use it. If trying to replicate the sample&#8217;s behavior in a different program, take a look at step 2 below regarding adding the Amazon ECS service reference.</p>
<h2>Authentication of Product Advertising API requests</h2>
<p>If you develop for the Amazon Product Advertising API (formerly known as the Amazon Associates Web Service &#8212; AWS), you would have noticed by now the repeating emails from Amazon about a <a title="change in the rules" href="http://developer.amazonwebservices.com/connect/ann.jspa?annID=444">change in the rules</a>. Starting August 15, 2009, all API requests must be authenticated using cryptographic signatures. The Amazon API documentation explains <a title="how to authenticate requests" href="http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?RequestAuthenticationArticle.html">how to authenticate requests</a>. The API team also provides <a title="sample code" href="http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=14">sample code</a> in C#, Java and Perl.  Two C# samples are provided, one for applications using the SOAP interface, and another for applications using REST.</p>
<p>My application uses SOAP, and so I started with that sample. The SOAP sample, it turned out, uses the <a href="http://msdn.microsoft.com/en-us/library/microsoft.web.services3.aspx">Microsoft.Web.Services3</a> namespace, which belongs to the Web Services Enhancements (<a href="http://msdn.microsoft.com/en-us/library/aa139619.aspx">WSE</a>) class library. WSE appears to be a .NET 2.0, Visual Studio 2005 thing, and is <a href="http://msdn.microsoft.com/en-us/library/aa528780.aspx">superceded by WCF</a>. If I have to touch my application, I would much rather update it to use WCF, .NET 3.5, and Visual Studio 2008 than to WSE.</p>
<p>Thankfully, a number of folks <a href="http://developer.amazonwebservices.com/connect/thread.jspa?threadID=33012&amp;tstart=0">tackled the</a> <a href="http://stackoverflow.com/questions/1204191/how-to-sign-an-amazon-web-service-request-in-net-with-soap-and-without-wse/1204671#1204671">problem already</a>. The WCF solution implements the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iclientmessageinspector.aspx">IClientMessageInspector</a> interface to gain an opportunity to sign SOAP requests just before they are sent. The signing logic isn&#8217;t particularly complex. It must, however, implement the letter of the specification,or requests are dropped. The remainder of this post outlines a short sample program illustrating how to generate authenticated WCF requests to the Amazon product advertising API. You can download the complete sample from the link at the top of this post.</p>
<h2>Step 1 &#8211; Create a sample console application</h2>
<ol>
<li>In Visual Studio 2008, select New/Project&#8230; from the File menu.</li>
<li>Select Console Application from Visual C#/Windows, and enter the application&#8217;s name.</li>
<li>Click OK</li>
</ol>
<p>Visual Studio creates a new console application. So far, this isn&#8217;t different than any other console app.</p>
<h2>Step 2 &#8211; Add a web service reference</h2>
<ol>
<li>In the Solution Explorer view, right click References, then select Add Service Reference&#8230;</li>
<li>The Add Service Reference dialog appears. Type in the Amazon Product Advertising API WSDL URL in the Address box: <a href="http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl">http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl</a>.</li>
<li>Click Go. Visual Studio takes a moment to download the service description, and then populates the Services box. You should see AWSECommerceService in there.</li>
<li>Type in the namespace for the code that Visual Studio will generate. I used Amazon.ECS. Click OK.</li>
</ol>
<p>Visual Studio now creates a service reference and adds it to your project. You can see it under the Service References folder in Solution Explorer. Your application will now also have an app.config file added, listing WCF binding and endpoint information for the added service.</p>
<h2>Step 3 &#8211; Add code to access the Product Advertising API.</h2>
<p>You could update your program as follows to have it connect to the product advertising API and search for books with &#8220;WCF&#8221; in their title. Make sure to add a using statement to reference the namespace you chose for the service in step 2.</p>
<p><pre class="brush: csharp;">
    using System.ServiceModel;
    using AmazonProductAdvtApiWcfSample.Amazon.ECS;

    class Program {
        // your Amazon ID's
        private const string accessKeyId    = &quot;YOURACCESSKEYIDHEREX&quot;;
        private const string secretKey      = &quot;YOURAMAZONSECRETKEYHERE/YESITSTHISLONGXX&quot;;

        // the program starts here
        static void Main(string[] args) {

            // create a WCF Amazon ECS client
            AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
                new BasicHttpBinding(),
                new EndpointAddress(&quot;http://webservices.amazon.com/onca/soap?Service=AWSECommerceService&quot;));

            // prepare an ItemSearch request
            ItemSearchRequest request   = new ItemSearchRequest();
            request.SearchIndex         = &quot;Books&quot;;
            request.Title               = &quot;WCF&quot;;
            request.ResponseGroup       = new string[] { &quot;Small&quot; };

            ItemSearch itemSearch       = new ItemSearch();
            itemSearch.Request          = new ItemSearchRequest[] { request };
            itemSearch.AWSAccessKeyId   = accessKeyId;

            // issue the ItemSearch request
            ItemSearchResponse response = client.ItemSearch(itemSearch);

            // write out the results
            foreach (var item in response.Items[0].Item) {
                Console.WriteLine(item.ItemAttributes.Title);
            }
        }
    }
</pre></p>
<p>If you enter your Amazon access key ID into accessKeyId and run this program before the August 15 deadline, you might just obtain results. Your console should list the top 10 results for the &#8220;WCF&#8221; query against Amazon&#8217;s US book catalog. If you read this after the deadline has expired, you must complete the remaining steps before you can see the results.</p>
<h2>Step 4 &#8212; Add the authentication code</h2>
<p>That&#8217;s why we&#8217;re here. This sample adds the authentication SOAP headers using three classes:</p>
<ul>
<li>AmazonSigningMessageInspector implements the IClientMessageInspector interface. The implementation of the BeforeSendRequest method in this class generates the request signature and adds the appropriate headers to the request.</li>
<li>AmazonSigningEndpointBehavior implements the IEndpointBehavior. The implementation of the ApplyClientBehavior in this class adds our message inspector to the ECS client at the right moment.</li>
<li>AmazonHeader is a small helper class implementing MessageHeader. Our message inspector uses instances of this class to add the authentication headers into the SOAP request.</li>
</ul>
<p>Rather than include the full listing of these classes, let&#8217;s focus on the portion that actually signs the request.</p>
<p><pre class="brush: csharp;">
public object BeforeSendRequest(ref Message request, IClientChannel channel) {
    // prepare the data to sign
    DateTime    now             = DateTime.UtcNow;
    string      timestamp       = now.ToString(&quot;yyyy-MM-ddTHH:mm:ssZ&quot;);
    string      signMe          = operation + timestamp;
    byte[]      bytesToSign     = Encoding.UTF8.GetBytes(signMe);

    // sign the data
    byte[]      secretKeyBytes  = Encoding.UTF8.GetBytes(secretKey);
    HMAC        hmacSha256      = new HMACSHA256(secretKeyBytes);
    byte[]      hashBytes       = hmacSha256.ComputeHash(bytesToSign);
    string      signature       = Convert.ToBase64String(hashBytes);

    // add the signature information to the request headers
    request.Headers.Add(new AmazonHeader(&quot;AWSAccessKeyId&quot;, accessKeyId));
    request.Headers.Add(new AmazonHeader(&quot;Timestamp&quot;, timestamp));
    request.Headers.Add(new AmazonHeader(&quot;Signature&quot;, signature));

    return null;
}
</pre></p>
<p>BeforeSendRequest gets called just before the SOAP request is put out on the network. Our implementation of this method comutes a hash-based message authentication code (HMAC) of the operation and current time using the SHA256 hash function. It also puts the access key ID, timestamp and signature in the SOAP request headers. This embeds tags like the following in the SOAP request:</p>
<p><pre class="brush: xml;">
&lt;soap:Header
   xmlns:aws=&quot;http://security.amazonaws.com/doc/2007-01-01/&quot;&gt;
   &lt;aws:AWSAccessKeyId&gt;YOURACCESSKEYIDHEREX&lt;/aws:AWSAccessKeyId&gt;
   &lt;aws:Timestamp&gt;2009-08-15T23:59:59Z&lt;/aws:Timestamp&gt;
   &lt;aws:Signature&gt;SZf1CHmQnrZbsrC13hCZS061ywsEXAMPLE&lt;/aws:Signature&gt;
&lt;/soap:Header&gt;
</pre></p>
<h2>Step 5 &#8211; Make the Amazon ECS client authenticate</h2>
<p>Finally, to make our Amazon ECS client actually authenticate its requests, modify the main() method as follows:</p>
<p><pre class="brush: csharp;">
// create a WCF Amazon ECS client
AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
    new BasicHttpBinding(BasicHttpSecurityMode.Transport),
    new EndpointAddress(&quot;https://webservices.amazon.com/onca/soap?Service=AWSECommerceService&quot;));

// add authentication to the ECS client
client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(&quot;ItemSearch&quot;, accessKeyId, secretKey));
</pre></p>
<p>There are three changes from our original console program:</p>
<ol>
<li>The binding constructor now takes a BasicHttpSecurityMode.Transport argument. This forces an HTTPS connection. The Amazon web service refuses to accept authenticated requests over plain HTTP.</li>
<li>The endpoint address starts with &#8220;https:&#8221; instead of &#8220;http:&#8221;. The remainder of the URL did not change.</li>
<li> An instance of our endpoint behavior class is added to the client&#8217;s channel factory. This ensures that our message inspector will get plugged in when the client creates new connections, and will get to sign outgoing SOAP messages.</li>
</ol>
<h2>That&#8217;s it.</h2>
<p>This is all that&#8217;s required to get your WCF based Amazon Product Advertising API application to send authenticated requests. If you build and run the application now, your console should list 10 book titles returned from the service.</p>
<p>Worked for you? Didn&#8217;t work? Let us know in the comments!</p>
<p>Read <a href="http://flyingpies.wordpress.com/2009/08/13/signing-amazon-product-advertising-api-cwcf-part-2/">part 2</a>.</p>
<br /> Tagged: .NET, Amazon, C#, ECS, WCF <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flyingpies.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flyingpies.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flyingpies.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flyingpies.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flyingpies.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flyingpies.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flyingpies.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flyingpies.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=17&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flyingpies.wordpress.com/2009/08/01/17/feed/</wfw:commentRss>
		<slash:comments>88</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86846ba709fb232a1454d7adeb6c983e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">orentrutner</media:title>
		</media:content>
	</item>
		<item>
		<title>A sorted dictionary for Cocoa</title>
		<link>http://flyingpies.wordpress.com/2009/07/24/a-sorted-dictionary-for-cocoa/</link>
		<comments>http://flyingpies.wordpress.com/2009/07/24/a-sorted-dictionary-for-cocoa/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 00:08:14 +0000</pubDate>
		<dc:creator>Oren Trutner</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OS/X]]></category>
		<category><![CDATA[SortedDictionary]]></category>

		<guid isPermaLink="false">http://flyingpies.wordpress.com/?p=3</guid>
		<description><![CDATA[Writing for OS/X or the iPhone? Using NSDictionary to store and access key-value pairs? Ever tried to enumerate them all only to find they come back in some random order? That&#8217;s where I was several precious weeks ago. Of course you could get all the keys and all the values and then sort them all. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=3&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">Writing for OS/X or the iPhone? Using NSDictionary to store and access key-value pairs? Ever tried to enumerate them all only to find they come back in some random order?</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">That&#8217;s where I was several precious weeks ago. Of course you could get all the keys and all the values and then sort them all. But that takes CPU cycles, and is wasteful, especially if you have to re-sort after adding just a handful of items.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">There are two popular classes of data structures used for implementing dictionaries. Hash tables are optimized for extremely fast gets, inserts and deletions, as long as you&#8217;re not changing the number of entries in the dictionary too dramatically. If you do, performance starts dropping, and the hash table has to be resized, the memory reallocated, and the content copied &#8212; a costly operation. As for sort order &#8212; there isn&#8217;t any. The order of elements in the hash table isn&#8217;t related to the elements themselves, and may change when the table is resized.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">The other popular group of data structures are trees. In particular, self-balancing binary search trees specialize in reasonably fast gets, inserts and deletions. They don&#8217;t need to reallocate when some growth threshold is reached. Most importantly, they maintain a clear order between their elements. When used for building a dictionary, a binary search tree uses the sort order of the keys. You could quite efficiently enumerate all or part of the elements in the tree in their increasing or decreasing sort order.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">Outside the Cocoa universe, both hash-based and tree based dictionaries are frequently available. Java has HasMap and TreeMap. The .NET Framework has the Dictioanry and SortedDictionary classes. C++ has the tree-based std::map and the hash-based boost::unordered_map. Cocoa&#8217;s NSDictionary and NSMutableDictionary are hash-based. If there is a sorted dictionary avaiable in Cocoa, it managed to hide quite well.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">So after a prolonged bout of yak shaving, I am posting self-balancing binary search tree implementations of Objective-C SortedDictionary and MutableSortedDictionary classes. They implement the interface of NSDictionary and NSMutableDictioanry, and can be used as drop-in replacements. The new classes are unit-tested, and you can plug in their documentation directly into XCode. And, their sort order is always well defined. When you enumerate a SortedDictionary, you always get entries sorted by key. You can enumerate from the back too. If you query them for their keys and values, they come back sorted. And so on.</div>
<div id="_mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;">You can find the full source code, documentation and unit tests for SortedDictionary and MutableSortedDictionary at http://code.google.com/p/cocoa-sorted-dictionary/. They are available under the rather permissive MIT license, so feel free to hack away.</div>
<p>Writing for OS/X or the iPhone? Using NSDictionary to store and access key-value pairs? Ever tried to enumerate them all only to find they come back in some random order?</p>
<p>That&#8217;s where I was several precious weeks ago. Of course you could get all the keys and all the values and then sort them all. But that takes CPU cycles, and is wasteful, especially if you have to re-sort after adding just a handful of items.</p>
<p>There are two popular classes of data structures used for implementing dictionaries. <a title="Hash tables" href="http://en.wikipedia.org/wiki/Hash_table">Hash tables</a> are optimized for extremely fast gets, inserts and deletions, as long as you&#8217;re not changing the number of entries in the dictionary too dramatically. If you do, performance starts dropping, and the hash table has to be resized, the memory reallocated, and the content copied &#8212; a costly operation. As for sort order &#8212; there isn&#8217;t any. The order of elements in the hash table isn&#8217;t related to the elements themselves, and may change when the table is resized.</p>
<p>The other popular group of data structures are trees. In particular, <a title="Self-balancing binary search trees" href="http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree">self-balancing binary search trees</a> specialize in reasonably fast gets, inserts and deletions. They don&#8217;t need to reallocate when some growth threshold is reached. Most importantly, they maintain a clear order between their elements. When used for building a dictionary, a binary search tree uses the sort order of the keys. You could quite efficiently enumerate all or part of the elements in the tree in their increasing or decreasing sort order.</p>
<p>Outside the Cocoa universe, both hash-based and tree based dictionaries are frequently available. Java has HashMap and TreeMap. The .NET Framework has the Dictioanry and SortedDictionary classes. C++ has the tree-based std::map and the hash-based boost::unordered_map. Cocoa&#8217;s NSDictionary and NSMutableDictionary are hash-based. If there is a sorted dictionary avaiable in Cocoa, it managed to hide quite well.</p>
<p>So after a prolonged bout of yak shaving, I am posting self-balancing binary search tree implementations of Objective-C SortedDictionary and MutableSortedDictionary classes. They implement the interface of NSDictionary and NSMutableDictioanry, and can be used as drop-in replacements. The new classes are unit-tested, and you can plug in their documentation directly into XCode. And, their sort order is always well defined. When you enumerate a SortedDictionary, you always get entries sorted by key. You can enumerate from the back too. If you query them for their keys and values, they come back sorted. And so on.</p>
<p>You can find the full source code, <a href="http://cocoa-sorted-dictionary.s3.amazonaws.com/doc/index.html">documentation</a> and unit tests for SortedDictionary and MutableSortedDictionary at <a title="http://code.google.com/p/cocoa-sorted-dictionary/" href="http://code.google.com/p/cocoa-sorted-dictionary/">http://code.google.com/p/cocoa-sorted-dictionary/</a>. They are available under the rather permissive MIT license, so feel free to hack away.</p>
<p>Oren Trutner</p>
<br /> Tagged: Cocoa, iPhone, Objective-C, OS/X, SortedDictionary <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/flyingpies.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/flyingpies.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/flyingpies.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/flyingpies.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/flyingpies.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/flyingpies.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/flyingpies.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/flyingpies.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=flyingpies.wordpress.com&amp;blog=8694185&amp;post=3&amp;subd=flyingpies&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://flyingpies.wordpress.com/2009/07/24/a-sorted-dictionary-for-cocoa/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86846ba709fb232a1454d7adeb6c983e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">orentrutner</media:title>
		</media:content>
	</item>
	</channel>
</rss>
