<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9 - Entries tagged with UtilRunner</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Tags/utilrunner/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9 - Entries tagged with UtilRunner</title>
      <link>http://channel9.msdn.com/Tags/utilrunner</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Tags/utilrunner</link>
    <language>en</language>
    <pubDate>Mon, 20 May 2013 14:55:00 GMT</pubDate>
    <lastBuildDate>Mon, 20 May 2013 14:55:00 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>2</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Feeling the Earth Move</title>
      <description><![CDATA[
<p>Want to know if the earth is shaking?&nbsp; How about if someone is moving your laptop?&nbsp; Create a utility to detect movement so you'll know right away when something is happening!</p>
<p>The Windows 7 sensors platform exposes a standard way of communicating with hardware for determining location, light, magnetic north (compass), distance, movement, and much more.&nbsp; Through the accelerometer, movement is measured as force (G's) in up to three
 dimensions.&nbsp; The Freescale Badge board that I use for sensor development includes ambient light, touch, and a 3D accelerometer.</p>
<p>Working with the three axes of accelerometer data is incredibly easy.&nbsp; Each sensor data report indicates the number of G's felt along each axis.&nbsp; You can watch the values of movement in order to know more about the environment.</p>
<p>My first thought with this application was to create a seismometer to measure ground tremors, but I'm not so sure the one that I have would be nearly sensitive for that.&nbsp; Then it occurred to me that the accelerometer would work great to detect a laptop being
 moved.&nbsp; I see people leaving their laptop on a table and going up for a refill at a coffee shop.&nbsp; When I do that I always feel pretty nervous.&nbsp; Knowing that it could sound an alarm if someone moved it would make me feel more secure.&nbsp;
</p>
<p>For this application, you'll need a Windows 7 system, with a built-in or hardware add-on accelerometer.&nbsp; Some hard drives have them, some Lenovo laptops have them, but you need to be able to access the sensor using standard Windows 7 Devices and Sensors
 drivers.</p>
<p>With hardware in place, download Visual Studio 2010 Express, the Windows API Code Pack, and the Sensors and Location API, then you're ready to get started!</p>
<h3>Good Vibrations</h3>
<p>The accelerometer is an interesting sensor.&nbsp; You wiggle something physical around and get numbers that change.&nbsp; The numbers represent how many G's are being experienced in up to three dimensions.&nbsp; This makes it trivial to see when there is movement.&nbsp; With
 some additional work you can figure out more fine-grained movement information, but we just need to know how much things are moving around.</p>
<p>Using the Windows 7 managed sensors API, we can instantiate the accelerometer and start reading values with only a small amount of work.&nbsp; Even better, due to the design of the sensors API we can access it without locking it.&nbsp; In other words, unlike reading
 data from a serial port or other hardware connection, applications can share devices.</p>
<p>In this application, I wanted a UI with a lots of the raw and calculated values showing.&nbsp; This includes the G's for the individual axes, the net magnitude, and even a chart of data.&nbsp; In a WPF application, you need public properties in order to participate
 in databinding.&nbsp; You also need to be able to alert listeners when your values change.&nbsp; Unfortunately, the X, Y, and Z values from the sensor report are not easily bindable due to their indexed nature.&nbsp; They also have no way of alerting listeners (like the
 UI) that they have been updated.</p>
<p>The key to creating the right properties is using the <a href="http://msdn.microsoft.com/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank">
INotifyPropertyChanged</a> interface.&nbsp; This interface has only a single member – the
<em>PropertyChanged<strong> </strong></em>event.&nbsp; Whenever a property value changes, raise this event and any interested listeners will know to grab the new value.</p>
<p><strong>Visual Basic</strong></p>
<pre class="csharpcode"><span class="preproc">#Region</span> <span class="str">&quot;Magnitude Property&quot;</span>
    <span class="kwrd">Private</span> _magnitude <span class="kwrd">As</span> <span class="kwrd">Double</span>
    <span class="kwrd">Public</span> <span class="kwrd">Property</span> Magnitude() <span class="kwrd">As</span> <span class="kwrd">Double</span>
        <span class="kwrd">Get</span>
            <span class="kwrd">Return</span> _magnitude
        <span class="kwrd">End</span> <span class="kwrd">Get</span>
        <span class="kwrd">Set</span>(<span class="kwrd">ByVal</span> value <span class="kwrd">As</span> <span class="kwrd">Double</span>)
            _magnitude = value
            OnPropertyChanged(<span class="str">&quot;Magnitude&quot;</span>)
        <span class="kwrd">End</span> <span class="kwrd">Set</span>
    <span class="kwrd">End</span> <span class="kwrd">Property</span>
<span class="preproc">#End Region</span></pre>
<pre class="csharpcode"><span class="preproc">#Region</span> <span class="str">&quot;INotifyPropertyChanged Members&quot;</span>

    <span class="kwrd">Public</span> <span class="kwrd">Event</span> PropertyChanged <span class="kwrd">As</span> PropertyChangedEventHandler <span class="kwrd">Implements</span> INotifyPropertyChanged.PropertyChanged

    <span class="kwrd">Private</span> <span class="kwrd">Sub</span> OnPropertyChanged(<span class="kwrd">ByVal</span> prop <span class="kwrd">As</span> <span class="kwrd">String</span>)
        <span class="kwrd">RaiseEvent</span> PropertyChanged(<span class="kwrd">Me</span>, <span class="kwrd">New</span> PropertyChangedEventArgs(prop))
    <span class="kwrd">End</span> <span class="kwrd">Sub</span>
<span class="preproc">#End Region</span></pre>
<p><strong>Visual C#</strong></p>
<pre class="csharpcode"><span class="preproc">#region</span> Magnitude Property
<span class="kwrd">private</span> <span class="kwrd">double</span> _magnitude;
<span class="kwrd">public</span> <span class="kwrd">double</span> Magnitude
{
    get { <span class="kwrd">return</span> _magnitude; }
    set
    {
        _magnitude = <span class="kwrd">value</span>;
        OnPropertyChanged(<span class="str">&quot;Magnitude&quot;</span>);
    }
}
<span class="preproc">#endregion<pre class="csharpcode"><span class="preproc">#region</span> INotifyPropertyChanged Members

<span class="kwrd">public</span> <span class="kwrd">event</span> PropertyChangedEventHandler PropertyChanged;

<span class="kwrd">private</span> <span class="kwrd">void</span> OnPropertyChanged(<span class="kwrd">string</span> prop)
{
    <span class="kwrd">if</span> (PropertyChanged != <span class="kwrd">null</span>)
        PropertyChanged(<span class="kwrd">this</span>, <span class="kwrd">new</span> PropertyChangedEventArgs(prop));
}

<span class="preproc">#endregion</span>
</pre></span></pre>
<p>This pattern is found in every public property that you want to enable for databinding.&nbsp; It's great because you can do it on a class for WPF or Silverlight, yet it's not creating a dependency on them.&nbsp; You can subscribe to this event in some apps, and simply
 ignore the event in other applications.&nbsp; Being able to reuse business objects this way is a big deal to me.</p>
<p>Now the UI can display new values as they change without the old Windows forms-style code (tbValue.Text = “value”).&nbsp; The other part was to actually sound an alarm if the acceleration was more than a preset value.&nbsp; This is a simple comparison.&nbsp; This threshold
 value is called “sensitivity” and accepts a value from 0-3.&nbsp; This is value is also a property in the view model.&nbsp; If the measured magnitude value is higher than the threshold, then an alert displays and the system
<em>Exclamation </em>sound plays:</p>
<p><strong>Visual Basic</strong></p>
<p></p>
<pre class="csharpcode"><span class="kwrd">If</span> <span class="kwrd">Me</span>.Magnitude &gt; <span class="kwrd">Me</span>.Sensitivity <span class="kwrd">Then</span>
    Status = <span class="kwrd">String</span>.Format(<span class="str">&quot;Big movement! ({0} G's)&quot;</span>, Magnitude)
    System.Media.SystemSounds.Exclamation.Play()
<span class="kwrd">End</span> If</pre>
<strong>Visual C#</strong>
<pre class="csharpcode"><span class="kwrd">if</span> (<span class="kwrd">this</span>.Magnitude &gt; <span class="kwrd">this</span>.Sensitivity)
{ 
    Status = <span class="kwrd">string</span>.Format(<span class="str">&quot;Big movement! ({0} G's)&quot;</span>, Magnitude);
    System.Media.SystemSounds.Exclamation.Play();
}</pre>
<p>&nbsp;</p>
<p>In XAML, a <em>Slider</em> control is bound to the <strong>Sensitivity </strong>
property in <strong>TwoWay </strong>mode. The slider is set with minimum and maximum values. Since sliders typically display their current value, you need to add a
<em>Label</em> too.&nbsp; It's not automatic.&nbsp; The <em>Label</em>'s content is actually bound to the
<em>Value</em> property of the <em>Slider</em> control.&nbsp; So, although it sounds complicated to require an extra field for the slider's label, the element databinding makes it simple.</p>
<pre class="csharpcode">&nbsp;</pre>
<pre class="csharpcode"><strong>XAML</strong></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
 {font-size:small;
 color:black;
 font-family:consolas,"Courier New",courier,monospace;
 background-color:#ffffff}
.csharpcode 
 {margin:0em}
.csharpcode .rem
 {color:#008000}
.csharpcode .kwrd
 {color:#0000ff}
.csharpcode .str
 {color:#006080}
.csharpcode .op
 {color:#0000c0}
.csharpcode .preproc
 {color:#cc6633}
.csharpcode .asp
 {background-color:#ffff00}
.csharpcode .html
 {color:#800000}
.csharpcode .attr
 {color:#ff0000}
.csharpcode .alt
 {background-color:#f4f4f4;
 width:100%;
 margin:0em}
.csharpcode .lnum
 {color:#606060}
-->
</style>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Label</span> <span class="attr">Content</span><span class="kwrd">=&quot;Sensitivity (1-3):&quot;</span> <span class="attr">FontWeight</span><span class="kwrd">=&quot;bold&quot;</span><span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">Grid</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Grid.ColumnDefinitions</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">ColumnDefinition</span> <span class="attr">Width</span><span class="kwrd">=&quot;.75*&quot;</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">ColumnDefinition</span> <span class="attr">Width</span><span class="kwrd">=&quot;.25*&quot;</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Grid.ColumnDefinitions</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Slider</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;slider&quot;</span> <span class="attr">Margin</span><span class="kwrd">=&quot;10,0,10,0&quot;</span> <span class="attr">Value</span><span class="kwrd">=&quot;{Binding Sensitivity, Mode=TwoWay}&quot;</span> <span class="attr">Minimum</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Maximum</span><span class="kwrd">=&quot;3&quot;</span>  <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Label</span> <span class="attr">Content</span><span class="kwrd">=&quot;{Binding Value, ElementName=slider}&quot;</span> <span class="attr">FontWeight</span><span class="kwrd">=&quot;bold&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span><span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Grid</span><span class="kwrd">&gt;</span></pre>
<h3>Getting the Data</h3>
<p>Most sensors support the concept of auto-updating their data on a minimum interval.&nbsp; I decided to do it on my own using a background thread.&nbsp; This guaranteed a constant interval making it nicer for charting.&nbsp; It wasn't really necessary, but what I found
 was no readings during no movement, and a flood of readings when things changed.</p>
<p>As long as the sensor is enabled, you can subscribe to the <em>DataReportChanged</em> event.&nbsp; Then you can access the
<em>CurrentAcceleration</em> property.&nbsp; Individual axes are indexed rather than exposed as direct properties.&nbsp; I suppose this is more flexible for far-future 11-dimensional accelerometers…</p>
<p><strong>Visual Basic</strong></p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> UpdateData()
    _optionsControl.Dispatcher.BeginInvoke(<span class="kwrd">Sub</span>() UpdateDataInvoked())
<span class="kwrd">End</span> <span class="kwrd">Sub</span>

<span class="kwrd">Private</span> <span class="kwrd">Sub</span> UpdateDataInvoked()
    <span class="kwrd">If</span> (_accelSensor <span class="kwrd">Is</span> <span class="kwrd">Nothing</span>) <span class="kwrd">OrElse</span> (_accelSensor.TryUpdateData() = <span class="kwrd">False</span>) <span class="kwrd">Then</span>
        <span class="kwrd">Return</span>
    <span class="kwrd">End</span> <span class="kwrd">If</span>

    <span class="kwrd">Dim</span> currentAccel = _accelSensor.CurrentAcceleration
    <span class="kwrd">Dim</span> sampleTime <span class="kwrd">As</span> DateTime = DateTime.Now

    <span class="kwrd">Me</span>.LastDataReportX = currentAccel(AccelerationAxis.X)
    <span class="kwrd">Me</span>.LastDataReportY = currentAccel(AccelerationAxis.Y)
    <span class="kwrd">Me</span>.LastDataReportZ = currentAccel(AccelerationAxis.Z)

    <span class="kwrd">Me</span>.Magnitude = Math.Sqrt(Math.Pow(<span class="kwrd">Me</span>.LastDataReportX, 2) &#43; Math.Pow(<span class="kwrd">Me</span>.LastDataReportY, 2) &#43; Math.Pow(<span class="kwrd">Me</span>.LastDataReportZ, 2))

    <span class="kwrd">If</span> _perfCounter IsNot <span class="kwrd">Nothing</span> <span class="kwrd">Then</span>
        _perfCounter.RawValue = Convert.ToInt64(<span class="kwrd">Me</span>.Magnitude * 10)
    <span class="kwrd">End</span> <span class="kwrd">If</span>

    ReadingsX.Add(<span class="kwrd">New</span> SensorReading() <span class="kwrd">With</span> { _
        .Reading = <span class="kwrd">Me</span>.LastDataReportX, _
        .Timestamp = sampleTime _
    })
    ReadingsY.Add(<span class="kwrd">New</span> SensorReading() <span class="kwrd">With</span> { _
        .Reading = <span class="kwrd">Me</span>.LastDataReportY, _
        .Timestamp = sampleTime _
    })
    ReadingsZ.Add(<span class="kwrd">New</span> SensorReading() <span class="kwrd">With</span> { _
        .Reading = <span class="kwrd">Me</span>.LastDataReportZ, _
        .Timestamp = sampleTime _
    })

    <span class="kwrd">If</span> ReadingsX.Count &gt; 20 <span class="kwrd">Then</span>
        ReadingsX.RemoveAt(0)
    <span class="kwrd">End</span> <span class="kwrd">If</span>
    <span class="kwrd">If</span> ReadingsY.Count &gt; 20 <span class="kwrd">Then</span>
        ReadingsY.RemoveAt(0)
    <span class="kwrd">End</span> <span class="kwrd">If</span>
    <span class="kwrd">If</span> ReadingsZ.Count &gt; 20 <span class="kwrd">Then</span>
        ReadingsZ.RemoveAt(0)
    <span class="kwrd">End</span> <span class="kwrd">If</span>

    <span class="kwrd">If</span> <span class="kwrd">Me</span>.Magnitude &gt; <span class="kwrd">Me</span>.Sensitivity <span class="kwrd">Then</span>
        Status = <span class="kwrd">String</span>.Format(<span class="str">&quot;Big movement! ({0} G's)&quot;</span>, Magnitude)
        System.Media.SystemSounds.Exclamation.Play()
    <span class="kwrd">End</span> <span class="kwrd">If</span>
<span class="kwrd">End</span> Sub</pre>
<p><strong>Visual C#</strong></p>
<pre class="csharpcode"><span class="kwrd">void</span> UpdateData()
{
    _optionsUI.Dispatcher.Invoke(<span class="kwrd">new</span> Action(
        <span class="kwrd">delegate</span>()
        {
            <span class="kwrd">if</span> ((_accelSensor == <span class="kwrd">null</span>) || (_accelSensor.TryUpdateData() == <span class="kwrd">false</span>)) <span class="kwrd">return</span>;
                    
            var currentAccel = _accelSensor.CurrentAcceleration;
            DateTime sampleTime = DateTime.Now;

            <span class="kwrd">this</span>.LastDataReportX = currentAccel[AccelerationAxis.X];
            <span class="kwrd">this</span>.LastDataReportY = currentAccel[AccelerationAxis.Y];
            <span class="kwrd">this</span>.LastDataReportZ = currentAccel[AccelerationAxis.Z];

            <span class="kwrd">this</span>.Magnitude =
                Math.Sqrt(Math.Pow(<span class="kwrd">this</span>.LastDataReportX, 2) &#43; Math.Pow(<span class="kwrd">this</span>.LastDataReportY, 2) &#43;
                            Math.Pow(<span class="kwrd">this</span>.LastDataReportZ, 2));

            <span class="kwrd">if</span> (_perfCounter != <span class="kwrd">null</span>) _perfCounter.RawValue = Convert.ToInt64(<span class="kwrd">this</span>.Magnitude * 10);

            ReadingsX.Add(<span class="kwrd">new</span> SensorReading { Reading = <span class="kwrd">this</span>.LastDataReportX, Timestamp = sampleTime });
            ReadingsY.Add(<span class="kwrd">new</span> SensorReading { Reading = <span class="kwrd">this</span>.LastDataReportY, Timestamp = sampleTime });
            ReadingsZ.Add(<span class="kwrd">new</span> SensorReading { Reading = <span class="kwrd">this</span>.LastDataReportZ, Timestamp = sampleTime });

            <span class="kwrd">if</span> (ReadingsX.Count &gt; 20) ReadingsX.RemoveAt(0);
            <span class="kwrd">if</span> (ReadingsY.Count &gt; 20) ReadingsY.RemoveAt(0);
            <span class="kwrd">if</span> (ReadingsZ.Count &gt; 20) ReadingsZ.RemoveAt(0);

            <span class="kwrd">if</span> (<span class="kwrd">this</span>.Magnitude &gt; <span class="kwrd">this</span>.Sensitivity)
            { 
                Status = <span class="kwrd">string</span>.Format(<span class="str">&quot;Big movement! ({0} G's)&quot;</span>, Magnitude);
                System.Media.SystemSounds.Exclamation.Play();
            }
    }));
}</pre>
<p>These ReadingsX/Y/Z collections contain the last 20 readings and are used in the next section…</p>
<h3>Flooded with Data</h3>
<p>With so much data flowing in, it can be hard to really visualize it.&nbsp; This is why I decided that it made sense to chart it.&nbsp; There are a few charting options out there that are free and a few that are commercial.&nbsp; Some free options include Visifire, and
 Dynamic Data Display (D3).&nbsp; I chose to use Visifire with a line graph and have a data series for each axis.&nbsp; I'm not sure how useful this information is, but it looks nice!</p>
<p>Behind the scenes, I have three instances of <strong>ObservableCollection </strong>
of type <strong>SensorReading</strong>.&nbsp; <strong>SensorReading </strong>simply holds a data point and a point in time.&nbsp; In XAML, I'm able to perform full data-binding from these collections to datasets in the graph.&nbsp; Each time I add a value I check to see if
 I have over twenty items, and if so I remove the oldest one (element zero).&nbsp; I'm sure I could graph more than that, but it seemed sufficient.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10053939/2425.SS_2D00_2010_2D00_08_2D00_20_5F00_00.04.16_5F00_2.png"><img title="SS-2010-08-20_00.04.16" border="0" alt="SS-2010-08-20_00.04.16" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10053939/7120.SS_2D00_2010_2D00_08_2D00_20_5F00_00.04.16_5F00_thumb.png" width="472" height="470"></a></p>
<p>The other use for the data was to send it to the Windows Performance Monitor.&nbsp; You've probably seen the charts of the CPU load, memory, disk write, and other low-level data, but you may not realize that you can track your own data this way as well.&nbsp; Some
 companies add performance counters for number of simultaneous users, failed logins, cache misses, or whatever else is relevant to their application.&nbsp; Adding counters for your own data is really easy.&nbsp; You can choose to either have a number of items, or an
 increment/decrement counter to keep track of something.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10053939/1854.SS_2D00_2010_2D00_08_2D00_20_5F00_00.02.56_5F00_2.png"><img title="SS-2010-08-20_00.02.56" border="0" alt="SS-2010-08-20_00.02.56" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10053939/8625.SS_2D00_2010_2D00_08_2D00_20_5F00_00.02.56_5F00_thumb.png" width="644" height="450"></a></p>
<p>Start by creating a category, then create the counter.&nbsp; You can set names, descriptions, and data types.&nbsp; For this project, I crated a category called “Sensors” and a counter called “Net force.”&nbsp; This is of type
<em>NumberOfItems64</em> so I set the <em>RawValue </em>property with each new value.&nbsp; The only caveat with performance counters, is that if you add the counter while Performance Monitor is running you won't see it until you restart it.</p>
<p><strong>Visual Basic</strong></p>
<p></p>
<pre class="csharpcode"><span class="kwrd">Private</span> <span class="kwrd">Sub</span> CreatePerfCounter()
    <span class="kwrd">If</span> (PerformanceCounterCategory.Exists(PerfCategoryName)) <span class="kwrd">Then</span>
        PerformanceCounterCategory.Delete(PerfCategoryName)
    <span class="kwrd">End</span> <span class="kwrd">If</span>

    <span class="rem">' Create a collection of type CounterCreationDataCollection.</span>
    <span class="kwrd">Dim</span> CounterCreationData <span class="kwrd">As</span> <span class="kwrd">New</span> CounterCreationDataCollection()

    <span class="rem">' Create the counter, set properties, and add to collection</span>
    <span class="kwrd">Dim</span> ccd <span class="kwrd">As</span> <span class="kwrd">New</span> CounterCreationData()
    <span class="kwrd">With</span> (ccd)
        .CounterName = PerfNetForceName
        .CounterHelp = <span class="str">&quot;The net acceleration value (in G's)&quot;</span>
        .CounterType = PerformanceCounterType.NumberOfItems64
    <span class="kwrd">End</span> <span class="kwrd">With</span>

    CounterCreationData.Add(ccd)

    <span class="rem">' Create the category and pass the collection to it.</span>
    _category = PerformanceCounterCategory.Create(PerfCategoryName, _
        <span class="str">&quot;The Sensors performance object tracks the value of various sensors over time&quot;</span>, _
        PerformanceCounterCategoryType.SingleInstance, CounterCreationData)

    _perfCounter = <span class="kwrd">New</span> PerformanceCounter(PerfCategoryName, PerfNetForceName, <span class="kwrd">False</span>)
<span class="kwrd">End</span> Sub</pre>
<strong>Visual C#</strong>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> CreatePerfCounter()
{
    <span class="kwrd">if</span> (PerformanceCounterCategory.Exists(PerfCategoryName))
    {
        PerformanceCounterCategory.Delete(PerfCategoryName);
    }

    <span class="rem">// Create a collection of type CounterCreationDataCollection.</span>
    var counterCreationData = <span class="kwrd">new</span> CounterCreationDataCollection();

    <span class="rem">// Create the counter, set properties, and add to collection</span>
    counterCreationData.Add(<span class="kwrd">new</span> CounterCreationData
    {
        CounterName = PerfNetForceName,
        CounterHelp = <span class="str">&quot;The net acceleration value (in G's)&quot;</span>,
        CounterType = PerformanceCounterType.NumberOfItems64
    });

    <span class="rem">// Create the category and pass the collection to it.</span>
    _category =
        PerformanceCounterCategory.Create(
        PerfCategoryName,
        <span class="str">&quot;The Sensors performance object tracks the value of various sensors over time&quot;</span>,
        PerformanceCounterCategoryType.SingleInstance,
        counterCreationData);

    _perfCounter = <span class="kwrd">new</span> PerformanceCounter(PerfCategoryName, PerfNetForceName, <span class="kwrd">false</span>);
}</pre>
<h3>Utility Runner</h3>
<p>This is not the first article to use my MEF-based Utility Runner application as the base.&nbsp; As usual, you'll need to install that package (listed at the top in the prerequisites) in order for this to work.&nbsp; You'll also need to go to your project's properties,
 to Debug, and tell it to use a specific executable for debugging.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10053939/4503.SS_2D00_2010_2D00_08_2D00_23_5F00_16.42.49_5F00_2.png"><img title="SS-2010-08-23_16.42.49" border="0" alt="SS-2010-08-23_16.42.49" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10053939/0880.SS_2D00_2010_2D00_08_2D00_23_5F00_16.42.49_5F00_thumb.png" width="622" height="193"></a></p>
<p>If you use Utility Runner and want to add this is a plugin, go into the bin\debug\Addins folder and create a ZIP file from the
<em>contents</em> of the MEFUtil-Seismo.util folder and rename it to MEFUtil-Seismo.util.&nbsp; From the
<strong>Addins </strong>tab in Utility Runner, click the <strong>Install Addin From File</strong> command from within Utility Runner.</p>
<h3>Possible Enhancements</h3>
<p>In addition to a sound, it might make sense to support other notifications like growl, Twitter, or email.&nbsp; It might also make sense to respond to changes in a different sensor, for example ambient light.&nbsp; If I turn off the light in my office, it could sound
 an alarm if the light went on and I didn't sign in within a certain amount of time.&nbsp; That would require a change to monitor a different sensor (not difficult), and to check to see if the desktop is locked or not.</p>
<h3>Conclusion</h3>
<p>Sensors really change the nature of your code by allowing you to interact with the real world.&nbsp; If your system isn't equipped with sensors (like mine, unfortunately), make do with an add-on/prototyping board so you can try things out.&nbsp; These sensors are
 basically standard on smartphones these days, and will quickly become common on laptops as well.&nbsp; Windows 7 included a great feature by providing common hardware and device support.&nbsp; Take advantage of it today!</p>
<h3>About Arian</h3>
<p><a href="http://www.ariankulp.com">Arian Kulp</a> is a software developer living in Western Oregon.&nbsp; He creates samples, screencasts, demos, labs, and articles; speaks at programming events about data, UI, Silverlight, and more; and enjoys spending time
 with his family. </p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/utilrunner/RSS&WT.dl=0&WT.entryid=Entry:RSSView:306396dff57142389eaf9e7600c8ada5">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Feeling-the-Earth-Move</comments>
      <itunes:summary>
Want to know if the earth is shaking?&amp;nbsp; How about if someone is moving your laptop?&amp;nbsp; Create a utility to detect movement so you&#39;ll know right away when something is happening! 
The Windows 7 sensors platform exposes a standard way of communicating with hardware for determining location, light, magnetic north (compass), distance, movement, and much more.&amp;nbsp; Through the accelerometer, movement is measured as force (G&#39;s) in up to three
 dimensions.&amp;nbsp; The Freescale Badge board that I use for sensor development includes ambient light, touch, and a 3D accelerometer. 
Working with the three axes of accelerometer data is incredibly easy.&amp;nbsp; Each sensor data report indicates the number of G&#39;s felt along each axis.&amp;nbsp; You can watch the values of movement in order to know more about the environment. 
My first thought with this application was to create a seismometer to measure ground tremors, but I&#39;m not so sure the one that I have would be nearly sensitive for that.&amp;nbsp; Then it occurred to me that the accelerometer would work great to detect a laptop being
 moved.&amp;nbsp; I see people leaving their laptop on a table and going up for a refill at a coffee shop.&amp;nbsp; When I do that I always feel pretty nervous.&amp;nbsp; Knowing that it could sound an alarm if someone moved it would make me feel more secure.&amp;nbsp;
 
For this application, you&#39;ll need a Windows 7 system, with a built-in or hardware add-on accelerometer.&amp;nbsp; Some hard drives have them, some Lenovo laptops have them, but you need to be able to access the sensor using standard Windows 7 Devices and Sensors
 drivers. 
With hardware in place, download Visual Studio 2010 Express, the Windows API Code Pack, and the Sensors and Location API, then you&#39;re ready to get started! 
Good Vibrations
The accelerometer is an interesting sensor.&amp;nbsp; You wiggle something physical around and get numbers that change.&amp;nbsp; The numbers represent how many G&#39;s are being experienced in up to three dimensions.&amp;nbsp; </itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Feeling-the-Earth-Move</link>
      <pubDate>Wed, 25 Aug 2010 13:00:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Feeling-the-Earth-Move</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/10053939_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/10053939_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>ArianKulp</dc:creator>
      <itunes:author>ArianKulp</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Feeling-the-Earth-Move/RSS</wfw:commentRss>
      <category>Sensor</category>
      <category>utility</category>
      <category>Windows 7</category>
      <category>sensors</category>
      <category>UtilRunner</category>
    </item>
  <item>
      <title>Creating An Application With Full Plug-in Support</title>
      <description><![CDATA[
<p>In this article, you'll learn how to create an application with full plug-in support.</p>

<h3>Introduction</h3>
<p>It's been a number of months since I released the <a href="http://blogs.msdn.com/coding4fun/archive/2009/04/14/9535026.aspx">
first version of my Utility Runner application</a>.&nbsp; Utility Runner makes it possible to run system utilities with as little overhead as possible: Instead of lots of tray icons, numerous EXE's, and the associated memory and startup time overhead, this application
 manages multiple utilities from one place.</p>
<p>To open this solution, you'll need Visual Studio 2008 Express Edition (Visual C# or Visual Basic), at least.&nbsp; If you don't have it yet, you should get it!</p>
<h3>Working with MEF</h3>
<p>Little has changed functionally from the last version of the application, beyond some refactoring that's taken place since the new version of MEF was released.&nbsp; For one thing, the attribute for marking an export is no longer sealed, so you can now create
 a subclassed attribute that encompasses the export name and any other metadata included with it.&nbsp; Consumers can simply use your new custom attribute for a stronger-typed experience.&nbsp; In my case, I created a WpfServiceMetadata class.&nbsp; Read on for more information.</p>
<h3>Managing Addins</h3>
<p>My big challenge was figuring out how to implement an addin manager to support multiple utility addins, like in Firefox.&nbsp; MEF lets you easily mark what classes are addins and where they should fit into your overall code, but I wanted to take it further.&nbsp;
 I decided that my goals were:</p>
<ul>
<li>The ability to load an addin through the UI </li><li>The ability to disable/enable addins </li><li>The ability to remove an addin&nbsp; </li></ul>
<p>There are a number of ways to achieve these goals.&nbsp; Mine isn't the ideal way, but it works pretty well nonetheless.</p>
<p><strong>Loading Addins</strong></p>
<blockquote>
<p>Loading addins is mostly handled by the MEF Framework itself, but there is some manual work involved as well.&nbsp; I decided that instead of scanning a folder for DLL's like in the first version, I'd take things a step further:&nbsp; I came up with a simple packaging
 format to contain the addin and its associated files.</p>
<p>The packaging format is simply a Zip file renamed with the .util extension.&nbsp; The file contains at least the DLL of the addin itself, but might also include associated libraries, images, sounds, or other resources.&nbsp; I toyed with creating a manifest file to
 help supply addin information that didn't require class loading, but I kept it simple for now.</p>
<p>Before loading DLL's with addins, the <b>AddinManager </b>class will scan the addins folder for .util files and unzip them to same-named folders.&nbsp; Each of these folders gets added to the list of folders in which MEF searches.&nbsp; The original file then gets
 deleted.</p>
</blockquote>
<p><strong>Adding an addin</strong></p>
<blockquote>
<p>An application that uses addins needs a way for users to add new ones.&nbsp; The easiest method would be to have the user just drag new .util files into the Addins folder, but this isn't very user-friendly.&nbsp; I wanted to make it easy for a user to click something
 in the application to install an addin.</p>
<p>If the user clicks the <b>Add New Addin From File </b>button, they use a file browse button to locate the file.&nbsp; The application then copies that file to the Addins folder and notifies the user that it will be loaded on next startup.&nbsp; It would be great to
 load the addin immediately, and MEF supports that, but I decided to skip dynamic addin control for simplicity.</p>
<p>Instead of going through the dialog when loading an addin, it would be nice to support double-clicking. To do this, an association needs to be made from the .util extension to the executable.&nbsp; If you launch the executable with a file argument and it's the
 right format, it will automatically copy it to the Addins folder.&nbsp; If an instance is already running, the new instance will just exit.&nbsp; Similarly, if you launch the executable when another instance is running, the existing instance will show itself and the
 new instance will exit.</p>
<p>It's important to note that standard users don't have write access to the <i>Program Files
</i>folder.&nbsp; For this reason, addins need to be stored in the user's local profile folder.&nbsp; System-level addins can be stored in the
<i>ProgramData </i>folder.&nbsp; Addins could be in the user's roaming profile folder, but I haven't thought through all of that yet.&nbsp; (For example, if a user logs into different machines, an addin might not run on each system due to different hardware configurations.)</p>
</blockquote>
<p><strong>Disabling an addin</strong></p>
<blockquote>
<p>Disabling an addin should be a simple matter of renaming the addin folder.&nbsp; You can't do this at runtime though, since the DLL's are locked and loaded.&nbsp; As an alternative, I create a file (zero-length) with the same name and add the .disable extension to
 it.&nbsp; I check for this upon startup and before loading, and can handle it properly.</p>
<p>Enabling and removing addins are handled similarly, using .enable and .delete extensions on the zero-length files.</p>
</blockquote>
<h3>Creating Addins</h3>
<p>To create an addin, you need to 1) implement the <b>IWpfService </b>interface, and 2) add the
<b>WpfServiceMetadata </b>attribute with a name for your addin.&nbsp; From there, be sure to implement all the methods in the interface.&nbsp; The
<b>Start </b>method is called at initialization (you shouldn't take much time in the constructor), and
<b>Stop </b>is called at the end, for cleanup.&nbsp; Any time you want to update the <b>
Status</b>, be sure to raise the <b>StatusChanged </b>event.</p>
<pre class="csharpcode">[WpfServiceMetadata(<span class="str">&quot;SampleAddin&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> SampleAddinImpl : IWpfService
{
}</pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
	{font-size:small;
	color:black;
	font-family:consolas,"Courier New",courier,monospace;
	background-color:#ffffff}
.csharpcode 
	{margin:0em}
.csharpcode .rem
	{color:#008000}
.csharpcode .kwrd
	{color:#0000ff}
.csharpcode .str
	{color:#006080}
.csharpcode .op
	{color:#0000c0}
.csharpcode .preproc
	{color:#cc6633}
.csharpcode .asp
	{background-color:#ffff00}
.csharpcode .html
	{color:#800000}
.csharpcode .attr
	{color:#ff0000}
.csharpcode .alt
	{background-color:#f4f4f4;
	width:100%;
	margin:0em}
.csharpcode .lnum
	{color:#606060}
-->
</style>
<p>The final thing you'll need to do is copy your addin DLL to a folder with your addin name, plus the .util extension (Yes, an extension on the folder name.&nbsp; I do this in Visual Studio with a post-build event.&nbsp; If you debug the application, it looks for an
 Addins folder under the current directory.&nbsp; When started normally (such as when installed) it uses the local user profile.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9941747/clip_image001_2.png"><img title="clip_image001" border="0" alt="clip_image001" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9941747/clip_image001_thumb.png" width="400" height="311"></a></p>
<p>When you're ready to distribute the addin, compress the DLL and any supporting files into the top-level of a ZIP file, then rename the .zip extension to .util.&nbsp; You can load this from the Addins page of the app settings, or manually move it to the
<i>MefUtilRuner\Addins</i> folder in your local profile folder (<i>c:\users\{USERNAME}\AppData</i>):</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9941747/clip_image002_2.png"><img title="clip_image002" border="0" alt="clip_image002" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9941747/clip_image002_thumb.png" width="457" height="283"></a></p>
<h3>TimedQueue</h3>
<p>Message boxes, balloon help, status bars—these are all great ways to display a message to the user, but they all only show one string at a time.&nbsp; If you call it again before the reader has the chance to see it, it's just gone.&nbsp; There are some nice message
 managers that make it easy to manage stacking alerts, but I decided to stick with the built-in balloon help provider, and just manage how often I send changes.&nbsp; It's basically a buffered balloon provider that will only show messages every x number of seconds,
 regardless of how many attempts the application makes.&nbsp; To use it, simply add items to the collection.&nbsp; An event is raised whenever an item is available.&nbsp; If an item has exceeded the maximum time-to-live threshold, the users of the collection never see it.</p>
<pre class="csharpcode"><span class="rem">// Repeat while there are items (one pulse may occur with several items ready)</span>
<span class="kwrd">while</span> (item != <span class="kwrd">null</span>)
{
    <span class="rem">// If this is an old item, no event is raised.  This could happen if</span>
    <span class="rem">// a process goes into a loop and dumps a large number in a very short</span>
    <span class="rem">// amount of time.  </span>
    <span class="kwrd">if</span> (DateTime.Now.Subtract(item.TimeStamp).TotalMilliseconds &lt; _maxTTL)
    {
        RaiseEvent(item.Item);
        Thread.Sleep(_interval);
    }

    item = <span class="kwrd">default</span>(ItemWrapper&lt;T&gt;);

    <span class="kwrd">lock</span> (_lock)
    {
        <span class="kwrd">if</span>( _items.Count &gt; 0 )
            item = _items.Dequeue();
    }
}</pre>
<p>The main window creates an instance of the TimedQueue class.&nbsp; Every time an addin wants to display a message, it's added to the collection.&nbsp; When
<b>ItemAvailableEvent</b> fires, it's dispatched to the UI thread to be displayed.&nbsp; Dispatching prevents cross-threading issues between the background
<b>TimedQueue </b>thread and the UI thread.</p>
<pre class="csharpcode"><span class="kwrd">void</span> statuses_ItemAvailableEvent(<span class="kwrd">object</span> sender,
    ItemAvailableEventArgs&lt;StatusMessage&gt; e)
{
    Dispatcher.BeginInvoke((ThreadStart)<span class="kwrd">delegate</span>() {
        StatusUpdatedHandler(e.Item); }
        , DispatcherPriority.Background);
}</pre>
<p></p>
<p>Though this instance is being used for status messages, you can also use <b>TimedQueue
</b>for other purposes, when you are willing to lose old messages.&nbsp; One example would be to throttle user input, such as a game that doesn't want constant firing or jumping as fast as the user clicks a button.</p>
<h3>Next Steps</h3>
<p>There are a number of things that would be nice to have in this application.&nbsp; It would be good to allow utilities to extend the context menu to enable or disable something, or at least to jump straight to their configuration page.</p>
<p>Using ClickOnce to deploy utilities would also be nice since it's so clean for the user, but there is a cost:&nbsp; ClickOnce is very strict about how applications can interact with the system.&nbsp; They are always per-user, and they live in “secret” folders.&nbsp; Developers
 can't read or write to the hard drive except to protected storage (similar to the iPhone I suppose).&nbsp; I'm not sure if they are restricted in other ways, but it could cause a hardship.</p>
<p>It would also be nice if addins could be added at runtime.&nbsp; This is a fairly simple case, but I didn't get to it yet.&nbsp; Furthermore, if you add, you might expect to enable/disable/remove at runtime too.&nbsp; Unfortunately, disabling and removing aren't really
 possible.&nbsp; Sure, I could call <b>Stop</b> on a utility and remove it from the UI (and not call
<b>Start </b>on it next time), but that's not really disabled since it could still be running until the next restart.&nbsp; I couldn't force it to die unless I used separate application domains, which I'm loath to do.</p>
<p>Finally, I'd really like to get an “app store” type of repository going.&nbsp; I imagine being able to publish utilities like Sidebar Gadgets or Windows Live Writer Plugins so users can browse, read information, and click-and-install.&nbsp; That could be a really
 great way to make the idea take off. </p>
<h3>Conclusion</h3>
<p>There are definitely some rough edges at this point, but it's getting there.&nbsp; The source code is fully available and I'd be willing to give commit access to anyone interested in moving things forward.&nbsp; Just drop me a line!</p>
<h3>About Arian</h3>
<p><a href="http://www.ariankulp.com">Arian Kulp</a> is a software developer living in Western Oregon.&nbsp; He creates samples, screencasts, demos, labs, and articles; speaks at programming events; and enjoys spending time with his family.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Tags/utilrunner/RSS&WT.dl=0&WT.entryid=Entry:RSSView:9f19caa631914b4ca4ba9e7600ca72db">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Creating-An-Application-With-Full-Plug-in-Support</comments>
      <itunes:summary>
In this article, you&#39;ll learn how to create an application with full plug-in support. 

Introduction
It&#39;s been a number of months since I released the 
first version of my Utility Runner application.&amp;nbsp; Utility Runner makes it possible to run system utilities with as little overhead as possible: Instead of lots of tray icons, numerous EXE&#39;s, and the associated memory and startup time overhead, this application
 manages multiple utilities from one place. 
To open this solution, you&#39;ll need Visual Studio 2008 Express Edition (Visual C# or Visual Basic), at least.&amp;nbsp; If you don&#39;t have it yet, you should get it! 
Working with MEF
Little has changed functionally from the last version of the application, beyond some refactoring that&#39;s taken place since the new version of MEF was released.&amp;nbsp; For one thing, the attribute for marking an export is no longer sealed, so you can now create
 a subclassed attribute that encompasses the export name and any other metadata included with it.&amp;nbsp; Consumers can simply use your new custom attribute for a stronger-typed experience.&amp;nbsp; In my case, I created a WpfServiceMetadata class.&amp;nbsp; Read on for more information. 
Managing Addins
My big challenge was figuring out how to implement an addin manager to support multiple utility addins, like in Firefox.&amp;nbsp; MEF lets you easily mark what classes are addins and where they should fit into your overall code, but I wanted to take it further.&amp;nbsp;
 I decided that my goals were: 

The ability to load an addin through the UI The ability to disable/enable addins The ability to remove an addin&amp;nbsp; 
There are a number of ways to achieve these goals.&amp;nbsp; Mine isn&#39;t the ideal way, but it works pretty well nonetheless. 
Loading Addins 

Loading addins is mostly handled by the MEF Framework itself, but there is some manual work involved as well.&amp;nbsp; I decided that instead of scanning a folder for DLL&#39;s like in the first version, I&#39;d take things a step further:&amp;nbsp; I came up w</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Creating-An-Application-With-Full-Plug-in-Support</link>
      <pubDate>Mon, 28 Dec 2009 19:43:20 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Creating-An-Application-With-Full-Plug-in-Support</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/9941747_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/9941747_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>ArianKulp</dc:creator>
      <itunes:author>ArianKulp</itunes:author>
      <slash:comments>0</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Creating-An-Application-With-Full-Plug-in-Support/RSS</wfw:commentRss>
      <category>MEF</category>
      <category>utility</category>
      <category>WPF</category>
      <category>UtilRunner</category>
    </item>    
</channel>
</rss>