<?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:rssdatehelper="urn:rssdatehelper"><channel><title>Pete Brown's Blog (POKE 53280,0) for tag Silverlight</title><link>http://10rem.net</link><pubDate></pubDate><description>Pete Brown writes on a variety of topics from XAML with the Windows Runtime (WinRT), .NET programming using C#, WPF, Microcontroller programming with .NET Microframework, .NET Gadgeteer, Windows on Devices, and even plain old C, to raising two children in the suburbs of Maryland, woodworking, CNC and generally "making physical stuff". Oh, and Pete loves retro technology, especially Commodore (C64 and C128). If the content interests you, please subscribe using the subscription link to the right of every page.</description><generator>umbraco</generator><language>en-us</language><item><title>Sometimes coding a solution is faster than finding one: Simple Webcam app in Silverlight 5</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/11/11/sometimes-coding-a-solution-is-faster-than-finding-one-simple-webcam-app-in-silverlight-5</link><pubDate>Sun, 11 Nov 2012 20:08:26 GMT</pubDate><guid>http://10rem.net/blog/2012/11/11/sometimes-coding-a-solution-is-faster-than-finding-one-simple-webcam-app-in-silverlight-5</guid><description><![CDATA[ 
<p>I recently upgraded my main desktop PC to Windows 8. When I did
that, the Microsoft LifeCam software stopped working. It was
recognized as incompatible with Windows 8. For most people, this is
not an issue, as it works perfectly fine with the built-in Windows
8 camera app.</p>

<p>For me, however, I need a small camera app sitting on my desktop
so I can see the hallway leading to my office. I call it the
heart-attack preventer, as it makes it difficult for my children to
sneak up on me when I'm heads-down at work. This is because I'm
surrounded by displays and simply can't see over them. My home
office is in the basement, with a combined TV room and play room
(plus a bunch of storage) surrounding it, so the kids often sneak
in here to say "Hi".</p>

<p>I installed the latest version of the LifeCam software, and it
doesn't install the desktop camera app at all. Bummer. I quickly
checked, and this is a common observation about that install.</p>

<p>Rather than spend all afternoon looking for a solution, I
figured it would be easier to code my own in 15 minutes. I
considered using WPF 4.5, but WebCam access in WPF requires
third-party toolkits or DirectX code (or Win32 API calls), so that
wouldn't do it. Coding a solution as a Windows Store app wouldn't
do, as I need a very tiny window on my desktop, not a snapped app.
I sometimes snap other apps and wouldn't want the webcam app to
limit that, or take up that amount of room.</p>

<p><a
href="http://10rem.net/media/86652/Windows-Live-Writer_Sometimes-coding-a-solution-is-faster-th_D691_image_6.png"
 target="_blank"><img src="http://10rem.net/media/86657/Windows-Live-Writer_Sometimes-coding-a-solution-is-faster-th_D691_image_thumb_2.png" width="650" height="341" alt="image" border="0" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px"/></a></p>

<p>Silverlight has always had extremely simple WebCam APIs that are
quick to use. (WinRT's APIs are just as easy if not easier).</p>

<p>I created a quick Silverlight 5 project in Visual Studio 2012.
Made it an out-of-browser app with elevated permissions, and put
this as the MainPage.xaml markup</p>

<pre class="brush: xml;">
&lt;UserControl x:Class="SimpleWebcamSL.MainPage"<br />
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"<br />
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"<br />
    mc:Ignorable="d"<br />
    d:DesignHeight="300" d:DesignWidth="400"&gt;<br />
<br />
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;<br />
        &lt;Rectangle x:Name="VideoOutput"<br />
                   HorizontalAlignment="Stretch"<br />
                   VerticalAlignment="Stretch" MouseLeftButtonDown="VideoOutput_MouseLeftButtonDown_1" /&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/UserControl&gt;
</pre>

<p>And this as the code-behind:</p>

<pre class="brush: csharp;">
using System;<br />
using System.Collections.Generic;<br />
using System.Collections.ObjectModel;<br />
using System.Linq;<br />
using System.Net;<br />
using System.Windows;<br />
using System.Windows.Controls;<br />
using System.Windows.Documents;<br />
using System.Windows.Input;<br />
using System.Windows.Media;<br />
using System.Windows.Media.Animation;<br />
using System.Windows.Shapes;<br />
<br />
namespace SimpleWebcamSL<br />
{<br />
    public partial class MainPage : UserControl<br />
    {<br />
        public MainPage()<br />
        {<br />
            InitializeComponent();<br />
<br />
            Loaded += MainPage_Loaded;<br />
        }<br />
<br />
        ReadOnlyCollection&lt;VideoCaptureDevice&gt; _devices;<br />
<br />
        void MainPage_Loaded(object sender, RoutedEventArgs e)<br />
        {<br />
            _devices = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();<br />
<br />
            // specific to my system. Camera 1 is the one that points<br />
            // out of my home office. Camera 0 points at me.<br />
            if (_devices.Count &gt; 1)<br />
                SetCaptureDevice(_devices[1]);<br />
            else if (_devices.Count &gt; 0)<br />
                SetCaptureDevice(_devices[0]);<br />
        }<br />
<br />
<br />
        private void SetCaptureDevice(VideoCaptureDevice device)<br />
        {<br />
            var source = new CaptureSource();<br />
            source.VideoCaptureDevice = device;<br />
<br />
            var brush = new VideoBrush();<br />
            brush.Stretch = Stretch.UniformToFill;<br />
            brush.SetSource(source);<br />
            VideoOutput.Fill = brush;<br />
<br />
            source.Start();<br />
        }<br />
<br />
        private void VideoOutput_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)<br />
        {<br />
            Application.Current.MainWindow.DragMove();<br />
        }<br />
<br />
    }<br />
}<br />
</pre>

<p>I set the project properties for out of browser, no window
border, and elevated permissions (all covered in <a
href="http://manning.com/pbrown2" target="_blank">my Silverlight 5
book</a>) and then installed the app. All done in about 15 minutes.
It took longer to write this post than it did to create the
app.</p>

<p>This is hard-coded to my specific situation (second camera is
the camera which points away from my desk). I didn't bother with
icons, camera switching, or anything beyond what I needed for this
specific situation.</p>

<p>As a woodworker, I find it's sometimes quicker for me to build
something as opposed to search stores to find what I'm looking for.
<strong>As a programmer, sometimes it's faster just to code your
own solution rather than search the internet all day for
workarounds. :)</strong></p>
]]></description></item><item><title>Silverlight 5 in Action is Deal of the Day at Manning on 6/6/2012 - Save 50%</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/06/06/silverlight-5-in-action-is-deal-of-the-day-at-manning-on-6-6-2012---save-50percent</link><pubDate>Wed, 06 Jun 2012 23:18:46 GMT</pubDate><guid>http://10rem.net/blog/2012/06/06/silverlight-5-in-action-is-deal-of-the-day-at-manning-on-6-6-2012---save-50percent</guid><description><![CDATA[ 
<p>It's customary for a Manning book to be the Deal of the Day
shortly after it is released. <strong>My book, Silverlight 5 in
Action, is the Manning Deal of the Day for June 6, 2012</strong>.
Using the information and code below, you can get <strong>half off
(50% off) the retail purchase price</strong>. This deal is good
only for 24 hours, so be sure to pick it up now!</p>

<p><a href="http://www.manning.com/pbrown2/" target="_blank"><img src="http://10rem.net/media/85756/Windows-Live-Writer_57ea3ee1c01f_124CA_image19_629c6525-9512-41e4-b16e-870ef403e202.png" width="650" height="559" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></a></p>

<h3>Buy it Here</h3>

<ul>
<li><a
href="http://www.manning.com/pbrown2/">http://www.manning.com/pbrown2/</a></li>
</ul>

<h3>Discount Code</h3>

<p>Use this code starting at midnight tonight US eastern time
(GMT-5:00)</p>

<ul>
<li>dotd0606au</li>
</ul>

<h3>Additional Material</h3>

<p>While you are there, don't forget that in addition to the 965
printed pages, purchasers also have to access to 150 pages of
downloadable content, including:</p>

<ul>
<li>Media basics</li>

<li>Raw Media, Webcam, Microphone</li>

<li>Introduction to WCF RIA Services</li>

<li>WCF RIA Services Endpoints, Security, Logic and more</li>

<li>WCF RIA Services MVVM</li>
</ul>

<p>All the downloadable content went through the same quality and
editing process, so it's real book material.</p>

<p>Silverlight 5 is a great platform, especially for building
business applications. Among many other changes, the enhancements
to trusted applications and the addition of p-invoke make it an
excellent choice for building today's business applications. The
addition of a built-in 3d engine make it great for cutting edge
visualizations, interactive CAD-like tools, and even gaming.</p>

<p><a href="http://www.manning.com/pbrown2/"><img src="http://10rem.net/media/85391/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_thumb.png" width="207" height="249" alt="image" border="0"/></a>&nbsp;<a
href="http://www.manning.com/pbrown2/"><img src="http://10rem.net/media/85401/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_thumb_2.png" width="438" height="249" alt="image" border="0"/></a></p>

<p><a href="http://www.manning.com/pbrown2/"><img src="http://10rem.net/media/85411/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_thumb_1.png" width="650" height="488" alt="image" border="0"/></a></p>
]]></description></item><item><title>Windows 8 Release Preview and Visual Studio 2012 RC</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/05/31/windows-8-release-preview-and-visual-studio-2012-rc</link><pubDate>Thu, 31 May 2012 23:01:02 GMT</pubDate><guid>http://10rem.net/blog/2012/05/31/windows-8-release-preview-and-visual-studio-2012-rc</guid><description><![CDATA[ 
<p>Today we released the Windows 8 Release Preview (RP)! I haven't
been this excited about an operating system since Windows 95 first
came out, when there was no such thing as downloading an OS, and we
had to actually wait in line in a store to get our blue cloud box
full of floppies (or was it a CD? I forget).</p>

<p>Windows 95 was a big deal for users and developers alike. It had
a brand new interface, and a new set of programming APIs, common
controls (3d beveled gray the norm!), navigation patterns and more.
For most developers, this was their first taste of a 32 bit
operating system, and the first taste of the Win32 API. That
stuff's all old hat now, but it was new and exciting at the
time.</p>

<p>This excitement is a lot of what drove me to move to <a
href="http://10rem.net/blog/2012/05/22/my-new-role-at-microsoft"
target="_blank">my new role at Microsoft</a>.</p>

<p><img src="http://10rem.net/media/85661/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb3_thumb.png" width="650" height="365" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></p>

<p><a
href="http://windows.microsoft.com/en-US/windows-8/release-preview"
target="_blank">Get the Windows 8 Release Preview here</a>. Be sure
to watch the video at the top of the page. It's really well done
and shows a really well-rounded (if quick) view of the consumer
side of Windows 8. Read more about the release preview in <a
href="http://blogs.msdn.com/b/b8/archive/2012/05/31/delivering-the-windows-8-release-preview.aspx"
 target="_blank">Steven Sinofsky's post</a>.</p>

<p>Overall, this release feels smoother, faster, snappier, and more
stable when compared to the consumer preview (which was already
pretty good), as it should. As primarily a desktop user, the start
screen has really grown on me. I have to admit that my initial
reaction almost a year back was a bit "meh" and a lot "who moved my
cheese", but once I started using it every day, I found that I
really started to like it on my desktop. I switch back and forth
between Windows 7 and Windows 8 constantly (my home office alone
has 3 PCs running full time - soon to be four) so I get to make
comparisons constantly. I also do a lot more than just a few apps.
Lots of development, production, and much more. As much as I like
it on the desktop, <strong>I can't wait to use it on a tablet, as I
know it'll be even better there.</strong></p>

<p>As primarily a desktop user, I especially like the changes the
RP brings when it comes to using the mouse. The corners behave
better now, for example. Also, as a person who uses multiple large
displays (not yet running Windows 8 on that machine, but soon), I'm
<a
href="http://blogs.msdn.com/b/b8/archive/2012/05/21/enhancing-windows-8-for-multiple-monitors.aspx"
 target="_blank">happy to see what we've done to support power
users like us</a>. BTW, in case you're curious, dual 1560x1600 30"
backlit displays do a great job of heating your office on cold days
:)</p>

<h3>The Windows Store and Apps</h3>

<p>At the same time, we've launched an <strong>updated store with
TONS of great applications</strong>. You'll need the release
preview to see these. My thanks to all the people who have
submitted such great applications in time for this release, and to
the folks in corporate and field evangelism who spent the time to
help these customers deliver. I joined the team a little late to be
heavily involved here, but just watching the process (and lending a
small hand here and there) has been great.</p>

<p><img src="http://10rem.net/media/85671/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb30_thumb.png" width="652" height="367" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/>&nbsp;<img src="http://10rem.net/media/85681/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb31_thumb.png" width="652" height="367" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></p>

<p><img src="http://10rem.net/media/85691/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb47_thumb.png" width="324" height="183" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/>&nbsp;<img src="http://10rem.net/media/85701/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb48_thumb.png" width="324" height="183" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/>&nbsp;</p>

<p><img src="http://10rem.net/media/85711/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb49_thumb.png" width="324" height="183" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/>&nbsp;<img src="http://10rem.net/media/85721/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb50_thumb.png" width="324" height="183" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></p>

<p>To learn more about the developer changes to the store for the
release preview, watch the <a
href="http://blogs.msdn.com/b/windowsstore/"
target="_blank">Windows Store for Developers blog</a>.</p>

<h3>Developing for Windows</h3>

<p>I'm a Windows user, but like you, I'm also a developer. There
are a number of cool new things for developers in this release,
primarily centering on the new Visual Studio 2012.</p>

<h4>Visual Studio 2012 RC</h4>

<p><a
href="http://blogs.msdn.com/b/visualstudio/archive/2012/05/31/visual-studio-2012-rc-available-now.aspx"
 target="_blank">Today we released a new version of Visual
Studio</a>, now <a
href="http://blogs.msdn.com/b/jasonz/archive/2012/05/31/announcing-the-release-candidate-rc-of-visual-studio-2012-and-net-framework-4-5.aspx"
 target="_blank">branded Visual Studio 2012</a>. If you think about
it, this is some serious stuff. <strong>All at once, as a company,
we have Web teams, Client teams, Framework teams, Developer Tools
teams, Windows Teams, Windows API Teams, Windows Store teams, MSDN
content teams, and more all shipping stuff on the same
day</strong>. I'm impressed if I can manage to get both of my kids
dressed and out the door at the same time when we have a deadline.
Imagine driving most of an entire company towards a single date,
and with no mismatched socks.</p>

<p>Among other things, I really like what we've done with the
theming since the Consumer Preview / Beta. This is the tool I've
been using daily for a while now. Like Windows 8 RP, this is more
stable and reliable, and generally just feels more "done". I've
been using this for a bit now, and am really happy with where we've
taken it. Kudos to all the teams involved in developing Visual
Studio, including the .NET 4.5 framework teams.</p>

<p><img src="http://10rem.net/media/85731/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb7_thumb.png" width="650" height="365" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></p>

<p><em>(I don't usually run it at 1366x768 - the minimum full
tablet resolution, but I needed to for some screenshots/demos. I
also</em> <a
href="http://10rem.net/blog/2012/03/05/my-unofficial-tips-for-remoting-into-a-windows-8-machine-from-windows-7-plus-microsoft-account-tips"
 target="_blank"><em>use this via remote desktop from my main
PC</em></a><em>.)</em></p>

<p>I've been using various builds of Visual Studio 2012 RC for some
time now. With the latest set of UI changes, I really do find that
my eyes naturally focus on the code or markup far more than the
chrome. Sure, when you first see it, your eyes will want to take in
the whole picture, but after that, it's all code. To the Visual
Studio team, I say "Mission Accomplished".</p>

<p>Jason Zander <a
href="http://blogs.msdn.com/b/jasonz/archive/2012/05/31/announcing-the-release-candidate-rc-of-visual-studio-2012-and-net-framework-4-5.aspx"
 target="_blank">listed a number of enhancements</a> to the Metro
style templates and tooling for this release. Among the
highlights:</p>

<ul>
<li>A new Windows Runtime template so you can create WinRT
components using C# and VB</li>

<li>Better tooling support in Blend</li>

<li>Better keyboard and mouse navigation in the templates, by
default</li>

<li>A go-live license just like with the beta.</li>
</ul>

<p>If you install one of the appropriate SKUs, you can develop for
WPF, Silverlight, ASP.NET, WinRT/Metro and more all on Windows 8.
Even on Windows 7, you get the new tooling UI, which I find to be
pretty nice. You can also find <a
href="http://blogs.msdn.com/b/visualstudio/archive/2012/05/08/visual-studio-11-user-interface-updates-coming-in-rc.aspx"
 target="_blank">information on the new UI here</a>, and on <a
href="http://blogs.msdn.com/b/visualstudio/archive/2012/05/29/visual-studio-dark-theme.aspx"
 target="_blank">the dark theme here</a>.</p>

<p><a
href="http://www.microsoft.com/visualstudio/11/en-us/downloads"
target="_blank">Get Visual Studio 2012 RC here</a>. It works on
Windows 7 and Windows 8, as well as on our 2008 and 2012 server
products.</p>

<p>As you would expect, there are some breaking changes from the
consumer preview/beta, as you would expect. The full list of what
has changed for application developers can be found in this blog
post. Of course, the very best place to go to get started with
Windows 8 programming is the <a
href="http://msdn.microsoft.com/en-US/windows"
target="_blank">Windows Dev Center</a>. For Visual Studio 2012
development in general, visit <a
href="http://msdn.microsoft.com/en-US/"
target="_blank">MSDN</a>.</p>

<blockquote>
<p><strong>Aside on DPI</strong></p>

<p>Developers typically have laptops with high DPI screens. I have
a 1920x1080 laptop. If you do a clean install (and the driver has
appropriate support at install time) you'll likely see that your
DPI settings in Windows are higher than you've had in the past. On
my Lenovo, it defaulted to 125%. I actually like the higher DPI,
but I did turn it off when I went down to 1366x768 presentation
settings.</p>

<p>This also happened with clean installs of Windows 7, but due to
better driver support and other factors, you're likely to see more
of it in Windows 8. Feel free to change this, but also consider
that your users may have high DPI selected by default. I'm happy to
see us making these little steps towards <a
href="http://10rem.net/blog/2010/04/22/rant-hdtv-has-ruined-the-lcd-display-market-or-i-want-my-pixels-and-dpi-now"
 target="_blank">a future of higher resolution, higher DPI
displays</a>. This is not the same as the scaling you get when you
pick a lower resolution than your laptop supports, this is true
high DPI.</p>

<p><img src="http://10rem.net/media/85741/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb55_thumb.png" width="550" height="138" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></p>

<p><img src="http://10rem.net/media/85751/Windows-Live-Writer_57ea3ee1c01f_124CA_image_thumb56_thumb.png" width="550" height="152" alt="image" style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px"/></p>
</blockquote>

<h4>My Windows 8 XAML Book</h4>

<p>Yes, I'm still working on my Windows 8 XAML book :)</p>

<p><a
href="http://10rem.net/blog/2012/05/29/silverlight-5-in-action-printed-book-is-now-in"
 target="_blank">Silverlight 5 in Action showed up in boxes this
week</a>, so Manning (and I) can completely concentrate on the
Windows 8 book now during my should-be-sleeping time. My apx
1200-1300 pages (including download content) from the Silverlight
book is probably responsible for more overtime at Manning than most
anything else :)</p>

<p>Manning is working on getting the MEAP (Manning Early Access
Program) site set up for my Windows 8 XAML in Action book. They
just need me to wrap up some things today and tomorrow before they
can launch it. <strong>I'm only slightly better than Douglas Adams
when it comes to deadlines, but I do have several cool chapters to
be released.</strong> Based on feedback from folks internally, I
think you'll be pleased.</p>

<h3>Go Install It</h3>

<p>I've been running the release preview/candidate builds for a
week or so. My 6yo son's laptop is going to get Windows 8 tonight
or tomorrow. I know he'll love it, as well as the cool games and
other kid-oriented apps in the store. The UI will be easier for him
to navigate, and the full-screen approach in Metro far more
appropriate to his use, and IE10 now has much better support for
the sites he visits on a regular basis.</p>

<p>Oh, and now that I can show screen shots, expect more posts here
:)</p>

<p>Go get it all and write something cool.</p>
]]></description></item><item><title>Silverlight 5 in Action printed book is now in</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/05/29/silverlight-5-in-action-printed-book-is-now-in</link><pubDate>Tue, 29 May 2012 20:48:22 GMT</pubDate><guid>http://10rem.net/blog/2012/05/29/silverlight-5-in-action-printed-book-is-now-in</guid><description><![CDATA[ 
<p>It took forever to edit and print such a huge tome, but I'm
happy to say that Silverlight 5 in Action is now in. You should see
them available from <a href="http://www.manning.com/pbrown2/"
target="_blank">Manning this week</a>, and from <a
href="http://www.amazon.com/Silverlight-5-Action-Pete-Brown/dp/1617290319"
 target="_blank">Amazon next week</a>.</p>

<p><a
href="http://10rem.net/media/85386/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_2.png"
 target="_blank"><img src="http://10rem.net/media/85391/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_thumb.png" width="207" height="249" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a>&nbsp;<a
href="http://10rem.net/media/85396/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_6.png"
 target="_blank"><img src="http://10rem.net/media/85401/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_thumb_2.png" width="438" height="249" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Here are my four boxes, just delivered today. The UPS man
probably hates it when he has to deliver books to my place. At 968
pages each, they're pretty heavy. That top box: 1 book. Plus, there
are another 200-300 pages of good material, freely downloadable for
people who have purchased the print book (ebook purchasers should
find the chapters included automatically, but if not, the chapters
are available to you as well.) The additional material went through
the same editing process as the printed material, it was just too
much to include in the print edition.</p>

<p><a
href="http://10rem.net/media/85406/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_4.png"
 target="_blank"><img src="http://10rem.net/media/85411/Windows-Live-Writer_Silverlight-5-in-Action-printed-book-is-_EA85_image_thumb_1.png" width="650" height="488" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>If you have a copy, and like it, I encourage you to <a
href="http://www.amazon.com/Silverlight-5-Action-Pete-Brown/dp/1617290319"
 target="_blank">post a review on Amazon.com</a>. Every little bit
helps. Thanks!</p>
]]></description></item><item><title>Using async and await in Silverlight 5 and .NET 4 in Visual Studio 11 with the async targeting pack</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/05/22/using-async-and-await-in-silverlight-5-and-net-4-in-visual-studio-11-with-the-async-targeting-pack</link><pubDate>Tue, 22 May 2012 21:13:39 GMT</pubDate><guid>http://10rem.net/blog/2012/05/22/using-async-and-await-in-silverlight-5-and-net-4-in-visual-studio-11-with-the-async-targeting-pack</guid><description><![CDATA[ 
<p>Last September, I <a
href="http://10rem.net/blog/2011/09/04/simplifying-async-networking-with-tasks-in-silverlight-5"
 target="_blank">introduced the idea of Tasks in Silverlight</a>.
One of the things I really like about .NET 4.5, and the C# compiler
that comes with it, is the ability to simplify asynchronous code by
using the async modifier and await operator. Just yesterday, I <a
href="http://10rem.net/blog/2012/05/21/under-the-covers-of-the-async-modifier-and-await-operator-in-net-45-and-c-metro-style-applications"
 target="_blank">posted a bit on how these two keywords are used by
the compiler to take care of all the heavy lifting of asynchronous
code</a>.</p>

<p>The key thing to note here is that <strong>the work is done by
the compiler, not the runtime</strong>. That means that if you can
use the latest C# compiler, you can take advantage of this new
feature. A grasp of the async pattern and these two keywords will
also help prepare you for Windows Metro development. <strong>Note
that Silverlight doesn't have the same "asynchronous everywhere"
set of APIs that you'll find in WinRT or .NET 4.5 so async and
await won't be quite as useful here as they are there, but there's
some help for that too (read on).</strong> You can still create
your own async methods, however, which is especially useful if you
plan to share code with a WinRT XAML application.</p>

<blockquote>
<p>I'll focus on Silverlight 5 here, but understand that this works
with .NET 4 in VS11 as well. Note also that I'm using Visual Studio
11 beta for this post, so final details may change when VS11 is
released. Also, Visual Studio 11 and the compiler which supports
async/await requires Windows 7 or Windows 8. This will not work on
Windows XP or a Commodore 128.</p>
</blockquote>

<p>In Visual Studio, create a new Silverlight application.</p>

<p><a
href="http://10rem.net/media/85153/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_4.png"
 target="_blank"><img src="http://10rem.net/media/85158/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_thumb_1.png" width="650" height="329" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Choose all the normal options in the project creation dialog
(yes, create a new site, no on RIA)</p>

<p>For the MainPage.xaml, add a single button and wire up an event
handler.</p>

<pre class="brush: xml;">
&lt;UserControl x:Class="SilverlightAsyncDemo.MainPage"<br />
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"<br />
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"<br />
    mc:Ignorable="d"<br />
    d:DesignHeight="300" d:DesignWidth="400"&gt;<br />
<br />
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;<br />
        &lt;Button x:Name="TestAsync"<br />
                Content="Press Me!"<br />
                FontSize="25"<br />
                Width="200"<br />
                Height="75"<br />
                Click="TestAsync_Click" /&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/UserControl&gt;
</pre>

<p>The next step is to add the <a
href="http://www.microsoft.com/en-us/download/details.aspx?id=29576"
 target="_blank">Async Targeting Pack</a>. I'll use NuGet to grab
it.</p>

<p><img src="http://10rem.net/media/85163/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_7.png" width="446" height="390" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>Pick your favorite way to use NuGet. Some prefer the console.
I'm going to use the project's context menu and select "Manage
NuGet Packages". From there, I'll search for
AsyncTargetingPack.</p>

<p><a
href="http://10rem.net/media/85168/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_9.png"
 target="_blank"><img src="http://10rem.net/media/85173/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_thumb_3.png" width="650" height="337" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Once you see it, click "Install", accept the terms (maybe even
read them first), then close the NuGet package manager. You'll
notice that the Silverlight project now includes a reference to the
Microsoft.CompilerServices.AsyncTargetingPack Silverlight 5
library.</p>

<h3>A simple example using await</h3>

<p>If you have a call which uses the async callback pattern, such
as with a WebClient in Silverlight, using await is pretty easy, due
to the built-in extension methods:</p>

<pre class="brush: csharp;">
private async void TestAsync_Click(object sender, RoutedEventArgs e)<br />
{<br />
    var uri = new Uri("http://localhost:10697/SilverlightAsyncDemoTestPage.html");<br />
       <br />
    var client = new WebClient();<br />
<br />
    var results = await client.DownloadStringTaskAsync(uri);<br />
<br />
    Debug.WriteLine(results);<br />
}
</pre>

<p>Note that the event handler must be marked as async in order to
use the await keyword.</p>

<p>These extension methods, DownloadStringTaskAsync in this
example, are included in the AsyncCompatLibExtensions installed
with the async targeting pack.</p>

<p><a
href="http://10rem.net/media/85178/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_17.png"
 target="_blank"><img src="http://10rem.net/media/85183/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_thumb_7.png" width="650" height="524" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>The extension methods mimic many of the same async functions
already available in .NET 4.5. That's great for compatibility and
to help reduce how many different approaches you need to learn.</p>

<h3>Give me something to wait on</h3>

<p>"Hey teacher! I've got my pencil! Now give me something to write
on." - Pre-geriatric David Lee Roth</p>

<p>Let's do something a little more typical. In this case, I'm
going to create a web service that we'll use asynchronously.</p>

<p>In the web project, create a "Services" folder and in that,
create a new Silverlight-Enabled Web Service named
CustomerService.</p>

<pre class="brush: csharp;">
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Runtime.Serialization;<br />
using System.ServiceModel;<br />
using System.ServiceModel.Activation;<br />
<br />
namespace SilverlightAsyncDemo.Web.Services<br />
{<br />
    [ServiceContract(Namespace = "uri:demo.silverlight.async")]<br />
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]<br />
    public class CustomerService<br />
    {<br />
        [OperationContract]<br />
        public List&lt;Customer&gt; GetCustomers()<br />
        {<br />
            string[] firstNames = new string [] {"Pete", "Joe", "Ima", "John", "Jim", "Scott", "George", "Frank", "Al", "Jeremy", "Jason", "Alex", "Bob", "Bill", "William", "Severus", "Johnny", "Albus", "Han", "Harry", "Chris", "Christine", "Kristen", "Amy", "Leia", "Erin", "Heather", "Melissa", "Abby", "Ben", "Alice", "Morgan", "Chip"};<br />
            string[] lastNames = new string [] {"Brown", "Jones", "Braxton", "Huxley", "Solo", "Organa", "Vader", "Skywalker", "Potter", "Dumbledore", "Snape", "Avatar", "Cranks", "Bravo", "Grime", "Gee", "A.", "B.", "C.", "D.", "E.", "Z.", "X.", "Walker", "Franklin", "Moore", "Less"};<br />
<br />
            Random rnd = new Random();<br />
            const int CustomerCount = 200;<br />
<br />
            var customers = new List&lt;Customer&gt;();<br />
<br />
            // generate a bunch of dummy customer data<br />
            for (int i = 0; i &lt; CustomerCount; i ++)<br />
            {<br />
                int firstIndex = rnd.Next(0, firstNames.Length-1);<br />
                int lastIndex = rnd.Next(0, lastNames.Length-1);<br />
<br />
                customers.Add(<br />
                    new Customer()<br />
                        {<br />
                            FirstName = firstNames[firstIndex],<br />
                            LastName = lastNames[lastIndex]<br />
                        });<br />
            }<br />
<br />
            return customers;<br />
<br />
        }<br />
    }<br />
<br />
    public class Customer<br />
    {<br />
        public string LastName { get; set; }<br />
        public string FirstName { get; set; }<br />
    }<br />
}<br />
</pre>

<p>Build the solution, and then add a service reference from the
Silverlight client. When creating the service reference, name the
namespace "Services". But before you leave this dialog, we have one
VERY important thing to check. Click the "Advanced" button</p>

<p><a
href="http://10rem.net/media/85188/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_11.png"
 target="_blank"><img src="http://10rem.net/media/85193/Windows-Live-Writer_Using-async-and-await-in-Silverlig.NET-4_C022_image_thumb_4.png" width="450" height="464" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Foiled! We can't generate task-based service references. Why?
Well, Silverlight didn't have the necessary support until the async
targeting pack. So, we'll have to do this manually. If you were
using .NET 4, you could simply generate Task-based operations and
be done with it.</p>

<blockquote>
<p><strong>NOTE</strong></p>

<p>If we were using RESTful calls, the "add service reference"
stuff doesn't come into play at all - it's all just
POST/GET/DELETE/PUT/PATCH with a URL. SOAP, which is what many
folks use behind the firewall, is more difficult to work with, so
the service reference helps. I'm a big fan of the ASP.NET Web API
and RESTful services. You should check them out.</p>
</blockquote>

<h3>Creating an async-friendly wrapper for the service
reference</h3>

<p>Making your service method awaitable certainly makes it easier
to consume by other developers, and easier to work into your own
application workflow (especially if you have service calls that
rely on the results of other service calls). The code to make it
awaitable is not very complicated at all. However, I like to put
this type of code into a separate service proxy or client class in
the Silverlight project.</p>

<p>I created a new project folder named "Services" in the
Silverlight project. In that, I added a new class named
"CustomerServiceProxy". The code for the proxy is as follows:</p>

<pre class="brush: csharp;">
using System.Collections.ObjectModel;<br />
using System.Threading.Tasks;<br />
<br />
namespace SilverlightAsyncDemo.Services<br />
{<br />
    public class CustomerServiceProxy<br />
    {<br />
        public static Task&lt;ObservableCollection&lt;Customer&gt;&gt; GetCustomers()<br />
        {<br />
            var tcs = new TaskCompletionSource&lt;ObservableCollection&lt;Customer&gt;&gt;();<br />
<br />
            var client = new CustomerServiceClient();<br />
<br />
            client.GetCustomersCompleted += (s,e) =&gt;<br />
                {<br />
                    if (e.Error != null)<br />
                        tcs.TrySetException(e.Error);<br />
                    else if (e.Cancelled)<br />
                        tcs.TrySetCanceled();<br />
                    else<br />
                        tcs.TrySetResult(e.Result);<br />
                };<br />
<br />
            client.GetCustomersAsync();<br />
<br />
            return tcs.Task;<br />
        }<br />
    }<br />
}
</pre>

<p>The code for this was adapted from the Task-based Asynchronous
Pattern whitepaper listed under "Additional Information" below. The
task is set up to return an ObservableCollection of Customers,
which is (by default) what the service reference code generation
created for me in the CustomerServiceClient class. (I also love how
we managed to get both spellings of Canceled into the same method
O_o.)</p>

<p>Once you have the proxy created, it may be used from the
ViewModel, or any other code. Here it is in the button-click code
on MainPage. As before, the event handler has been marked with the
async modifier in order to support using the await operator.</p>

<pre class="brush: csharp;">
private async void TestAsync_Click(object sender, RoutedEventArgs e)<br />
{<br />
    var customers = await CustomerServiceProxy.GetCustomers();<br />
<br />
    foreach (Customer c in customers)<br />
    {<br />
        Debug.WriteLine(c.FirstName + " " + c.LastName);<br />
    }<br />
}
</pre>

<p>This can serve as a good starting point for your own code. Not
only will it make your async code easier to work with when using
Visual Studio 11, but it <strong>will also help you bridge towards
and share code with .NET 4.5 WPF, and to Metro style XAML
applications.</strong></p>

<h3>Additional Information</h3>

<ul>
<li><a
href="http://www.microsoft.com/en-us/download/details.aspx?id=19957">
Download: Task-based Asynchronous Pattern</a></li>

<li><a
href="http://10rem.net/blog/2011/09/04/simplifying-async-networking-with-tasks-in-silverlight-5">
Simplifying Async Networking with Tasks in Silverlight 5</a></li>

<li><a
href="http://10rem.net/blog/2012/05/21/under-the-covers-of-the-async-modifier-and-await-operator-in-net-45-and-c-metro-style-applications">
Under the covers of the async modifier and await operator in .NET
4.5 and C# Metro style applications</a></li>
</ul>
]]></description></item><item><title>My new role at Microsoft</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/05/22/my-new-role-at-microsoft</link><pubDate>Tue, 22 May 2012 18:27:40 GMT</pubDate><guid>http://10rem.net/blog/2012/05/22/my-new-role-at-microsoft</guid><description><![CDATA[ 
<p>This past Monday (May 14th), I officially started a new role at
Microsoft. I like to be as transparent as possible, so I thought
I'd share with you all the details of this role as well as where I
was before I moved to it.</p>

<blockquote>
<p><strong>TL;DR:</strong></p>

<p>XAML. Windows. Developers. 'nuf said.</p>
</blockquote>

<h3>A little (optional) history</h3>

<p>I've been working for Microsoft for a bit over two and a half
years now. In that time, I've learned that the old cliché about the
only constant being change is more true for Microsoft than just
about any other place I've seen. Mixing up teams, offices etc. from
time to time helps make the orgs more efficient, and injects new
ideas into groups.</p>

<p>When I was hired by Scott Hanselman in fall 2009, my primary
focus was to create a lot of content for <a
href="http://windowsclient.net/"
target="_blank">WindowsClient.net</a> and <a
href="http://silverlight.net/" target="_blank">Silverlight.net</a>,
as well as my blog. In addition to Scott, the team I joined
included Tim Heuer, Rey Bango, Joe Stagner, Jesse Liberty and Jon
Galloway. A few months later, Tim Heuer fulfilled a personal dream
and moved to the one of the product teams. Ten months after I
joined, Scott moved to the Web team, and Rey Bango moved to another
org to focus on some initiatives that he had been leading. Some of
this was due to the reorg that created the brand new organization
(with all brand new leadership) my team was moved to.</p>

<p>The people I worked with and for in that org were awesome. I've
enjoyed that role, and particularly enjoyed working closely with
patterns &amp; practices, MSDN, and more.</p>

<p>When Scott moved to the web team, I was given the lead of the
Community Team which by then included me, Jesse Liberty, Jon
Galloway, and Joe Stagner. We accomplished some really great
things, but at the same time, found ourselves focusing on tasks and
priorities which didn't quite fit the emerging mission, or in some
cases the capabilities, of our new org. Joe and Jesse moved on for
their own reasons, and are both now doing awesome stuff. Jon and I
stayed in the org, but a team of two is hard to keep effective and
impactful, despite excellent management support and an org full of
passionate and interesting people.</p>

<p>Jon and I agreed that he should <a
href="http://weblogs.asp.net/jgalloway/archive/2012/04/18/i-ve-joined-the-windows-azure-technical-evangelist-team.aspx">
pursue his interests and move to the Azure/Web evangelism team</a>,
a move that really fit what he wanted to do, and does best.
<strong>Jon is an awesome guy, and I really enjoyed having him work
for me.</strong> We continue to work together of course; the only
big change for us with his move is that I no longer need to approve
his expense reports (yay!). I was certainly able to stay where I
was, but once I was sure Jon was well-settled, and I no longer had
any direct reports, I was free to pursue something I was truly
excited about.</p>

<p><img src="http://10rem.net/media/85121/Windows-Live-Writer_2f4c22815519_14B7E_image_19.png" width="650" height="198" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<h3>My interests and passions</h3>

<p>I love working with XAML. Most of you have probably figured that
out. It's not my only interest by far, but it is a strong one. My
technical passions, in no particular order are:</p>

<ul>
<li>Client application development, primarily on Windows (I don't
own a Mac, and it's been around 12 years since I last ran a Linux
box)</li>

<li>Open source hardware (and general maker / electronics / CNC /
3d Printing and more)</li>

<li>Open source software</li>

<li>User experience and (to my limited ability) graphics
design</li>
</ul>

<p>I especially enjoy writing and speaking about C# + XAML,
although I'm starting to dabble in C++ + XAML (say that out loud)
as well. I've always liked working with Silverlight and WPF, and
the communities of people building awesome stuff using them.
Lately, I've been working a lot more with Windows 8 as well. I'm
really excited about what I see coming for Windows, and for Windows
8 devices like tablets/slates. <strong>In fact, some time ago, I
committed to creating a Windows 8 XAML book with Manning (the first
MEAP chapters will be out very soon - promise!).</strong></p>

<p><strong>I enjoy building applications and gadgets. I also love
speaking to</strong> <strong>developers, and wanted to speak more
at larger events.</strong> I like helping to represent the product
teams at Microsoft, as I've done for Silverlight and WPF. I wanted
to join an org where I can work with the technologies I love, the
communities I know and respect, and one which would allow me to
continue the personal policies of <strong>honesty, openness,
transparency, clarity, and authenticity</strong> that were so
important when working in Hanselman's (and later my) team.<img src="http://10rem.net/media/85126/Windows-Live-Writer_2f4c22815519_14B7E_image_13.png" width="650" height="165" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<h3>The new role</h3>

<p><strong>To that end, I've taken a very cool role working for <a
href="https://twitter.com/gisardo" target="_blank">Giorgio
Sardo</a> as a corporate Technical Evangelist on the Windows
Platform Evangelism team, focusing on XAML</strong>. (This is the
current incarnation of the team John Papa was on and that Brian
Keller, Jaime Rodriguez, and Giorgio Sardo, among others, are
currently on.) I will continue to be a remote employee, working out
of my house near Annapolis, MD (between Baltimore, Washington and
the Chesapeake Bay). I will also continue working with the
Silverlight and WPF community, but will add to that a much larger
focus on Windows 8 XAML going forward, and possibly some phone work
too. <strong>Metro style apps have huge potential both short term
and long term in all areas of client development from consumers to
line of business. I want to be a part of their success, part of
your success.</strong></p>

<p>Among the many things I'm going to try to accomplish are to help
find ways, <strong>for those who want to, to make it easier for
today's XAML developers to prepare for and migrate apps to WinRT
XAML if appropriate for their application</strong>. <em>No forcing.
You use the technology that best meets your business and
application goals and requirements</em>. I'll continue to do this
in a wide-reaching way through events, articles, toolkits, samples,
books, twitter, blogs and much more, and also add to that working
much more closely with people in the field, folks in the community,
and with some individual customers.</p>

<p><strong>During my interviews, I made it very clear that I am a
horrible sales person.</strong> Gladly, that's not this role. Some
community folks I speak with consider evangelism synonymous with
sales, but like so many roles at Microsoft, the role is really what
you make of it as an individual. The team I'm part of is full of
high-integrity individuals who all believe in the same things I do.
During the day of interviews, the ideas I proposed, ideas that I
believe many of you will find match with or support your own goals,
were received with enthusiasm and excitement.</p>

<p>I'm really happy to continue with XAML, and to continue working
with the community, now with more Metro. My first task? Helping to
build a cool and relevant keynote demo. EXACTLY the type of thing
I've wanted to do for a long time :)</p>

<p>In addition to that, last week I had VSLive NYC where I had
three sessions covering <strong>Silverlight, WPF, and Windows
8</strong>, a Saturday code camp session in Philly on
<strong>Windows 8 XAML</strong>, and coming up in June, a <a
href="http://northamerica.msteched.com/topic/details/2012/DEV335">Tech
Ed session on WPF 4.5</a>. Oh, and in August I'll be speaking at <a
href="http://www.thatconference.com/">thatConference</a> on
<strong>Windows 8 for Silverlight and WPF devs</strong>, and also
on <strong>open source hardware</strong>, and again at VSLive on
<strong>WPF and Windows 8 XAML</strong>. You can see that I have
quite a mix there, with good representation from all the client
members of the XAML family.</p>

<p>And, of course, I will <strong>continue with my NETMF and gadget
work</strong>. That's always been as much a personal passion as
anything. I often find a way to work it in with my primary focus,
and will be doing that here for sure.</p>

<p><img src="http://10rem.net/media/85131/Windows-Live-Writer_2f4c22815519_14B7E_image_10.png" width="650" height="136" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<h3>FAQ (or at least the Qs I think will be F)</h3>

<p>Forgive me if any of these are pretentious. I've jut made a best
guess as to the questions you may have.</p>

<h4>Q: Are you abandoning Silverlight / WPF?</h4>

<p>A: Nope. Those technologies are just as important now as ever.
Silverlight 5 was an exciting and huge release. WPF 4.5 is an
equally interesting release. I <strong>will focus more on XAML in
general and Windows 8 in particular</strong>, but I'm keeping my
fingers in all the pots. <strong>My Silverlight 5 book should be
back from the printers any day now</strong>, so you can enjoy all
1000 printed pages (and 200-300 downloadable pages) as well. I also
have Silverlight and WPF sessions at upcoming conferences, and as
long as folks keep showing up to learn, and I have something new to
teach, I'll keep teaching.</p>

<h4>Q: Are you going to focus exclusively on Windows 8 XAML</h4>

<p>A: Not exclusively, but I will certainly focus more time and
energy in that area. It's new. It's exciting, and I think
<strong>it's going to be a big deal for every developer</strong>.
See my list of events above for the current mix of sessions I'm
doing, for example.</p>

<h4>Q: What about your NETMF/Gadgeteer Stuff?</h4>

<p>A: I'll still work on that, as I really enjoy it. It was always
a hobby and will continue to be one. Also, I'm always looking for
ways to sneak it into other technology demos. :)</p>

<h4>Q: What happened to your Silverlight 5 book?</h4>

<p>A: I wrote WAY too much, so it took forever to edit and print.
It's out any day now. The delay is completely my fault.</p>

<h4>Q: What is your next book?</h4>

<p>A: Windows 8 XAML, of course. I've had this one in progress for
quite some time, but the burden of editing 1300 pages of my SL5
book caused a bit of a delay :). Expect to see the MEAP soon,
hopefully in time for our June Windows release. The next book will
be, by Manning's insistence,&nbsp;much shorter but equally as
useful :)</p>

<h4>Q: Are you moving to Redmond?</h4>

<p>A: Nope. I am very proud to be the first remote worker in this
team at Microsoft. Working remotely sometimes limits the things you
can do at Microsoft, but I'm really glad this org not only looked
past that, but embraced it as a strength. <strong>Besides, working
on the east coast lets me be a nightowl at home, but still appear
to be a morning person to those in Redmond</strong> ;)</p>

<h4>Q: Why Windows 8 XAML as a primary focus?</h4>

<p>A: I'm a super ADD person, just ask my wife. (Squirrel!!) I need
new and exciting things to keep me going. They also need to be new
things that <strong>I'm genuinely excited about</strong>, and which
I think will be a <strong>benefit to the community of
developers</strong>. Metro and WinRT + XAML + .NET 4.5 definitely
fits that criteria. <strong>I'm even excited about the HTML/JS side
of Windows 8 Metro, but I have close to zero skills there
currently.</strong></p>

<h4>Q: Why the corporate/platform evangelism team?</h4>

<p>A: This is the team that builds the customer connections,
creates the keynote demos, generally has earliest and best access
to cool stuff, and has a <strong>bunch of very cool people I
respect</strong>. It also helps that they wanted me to join :)</p>

<h4>Q: Will you continue to help run the Silverlight and WPF/Client
App Dev MVP programs</h4>

<p>A: Yes, in the same capacity as today.</p>

<h4>Q: Metro all the things?</h4>

<p>YES :)</p>

<p><a href="http://www.quickmeme.com/meme/35ogr3/"
target="_blank"><img src="http://10rem.net/media/85136/Windows-Live-Writer_2f4c22815519_14B7E_image_3.png" width="322" height="239" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>(<a href="http://www.flickr.com/photos/57933043@N00/6833646427/"
target="_blank">Robot minifig photo source</a>.)</p>
]]></description></item><item><title>The correct AdventureWorks database to use for Silverlight 5 in Action (and Silverlight 4 in Action) book examples</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/05/21/the-correct-adventureworks-database-to-use-for-silverlight-5-in-action-and-silverlight-4-in-action-book-examples</link><pubDate>Tue, 22 May 2012 01:33:45 GMT</pubDate><guid>http://10rem.net/blog/2012/05/21/the-correct-adventureworks-database-to-use-for-silverlight-5-in-action-and-silverlight-4-in-action-book-examples</guid><description><![CDATA[ 
<p>A reader tipped me off that the AdventureWorks schema has
changed since I (and my tech reviewers) last downloaded a copy.
Some of the schema changes make the database unworkable with the
in-book examples for Silverlight 4 in Action and <a
href="http://manning.com/pbrown2/" target="_blank">Silverlight 5 in
Action</a>. In particular, the Person table is no longer there in
recent versions.</p>

<p>A version of the database that is compatible with the examples
in my Silverlight book can be found on this page:</p>

<p><a
title="http://msftdbprodsamples.codeplex.com/releases/view/4004"
href="http://msftdbprodsamples.codeplex.com/releases/view/4004">http://msftdbprodsamples.codeplex.com/releases/view/4004</a></p>

<p>The top download, AdventureWorksDB.msi is what you want. It's
dated May 7, 2007. It's maked as SQL Server 2005, but it works with
more recent version. A later version of the database may work
(pretty sure the one I used was dated 2009 or 2010), but this one
is the only currently available compatible version we can find.</p>
]]></description></item><item><title>Workaround for CA0055 Error with Silverlight Projects in Visual Studio 2010</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/04/17/workaround-for-ca0055-error-with-silverlight-projects-in-visual-studio-2010</link><pubDate>Tue, 17 Apr 2012 19:07:46 GMT</pubDate><guid>http://10rem.net/blog/2012/04/17/workaround-for-ca0055-error-with-silverlight-projects-in-visual-studio-2010</guid><description><![CDATA[ 
<p><a
href="https://connect.microsoft.com/VisualStudio/feedback/details/713608/ca0055-silverlight5-business-application-project">
This connect bug</a> describes an issue with creating certain types
of Silverlight projects in Visual Studio. If you're referencing
Silverlight 4 DLLs from a Silverlight 5 project, you may run into
this <a
href="http://msdn.microsoft.com/en-us/library/y8hcsad3(v=vs.80).aspx">
code analysis/FXCop</a> issue yourself if code analysis is part of
your process. The core of the problem is a versioning decision in
Silverlight 5 which results in compile-time violation due to
loading two different versions of mscorlib in the same project. It
manifests as the following error:</p>

<ul>
<li>Error 2 CA0055 : Could not unify the platforms (mscorlib,
Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e,
mscorlib, Version=5.0.5.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e) for
'MyProject.Silverlight\obj\Debug\MyProject.dll'.</li>
</ul>

<p>More <a
href="http://msdn.microsoft.com/en-us/library/ms244741.aspx">information
on CA0055 may be found on MSDN</a>.</p>

<h3>How to Reproduce the Issue … in theory</h3>

<p>In theory, all you need to do to reproduce the issue is
reference a SL4-targeted DLL from an SL5 application. However, in
practice, there are other factors in play. For example, it may
matter which mscorlib version gets loaded first.</p>

<p><strong>These steps won't repro the problem on my installation,
but I'm putting them out here in case they help you visualize the
issue (and also because I had already written them up when I
realized they don't repro here -- I don't want all these bits to go
to waste).</strong></p>

<p>Create a Silverlight 4 class library. Make sure you target
Silverlight 4. I named mine SL4ClassLibrary. The actual code is
unimportant, but I set it to the following:</p>

<pre class="brush: csharp;">
namespace SL4ClassLibrary<br />
{<br />
    public class Class1<br />
    {<br />
        public string Foo = "Bar";<br />
    }<br />
}<br />
</pre>

<p>Next, add a Silverlight 5 Application project. Make sure it
targets Silverlight 5. Here's what my solution looks like:</p>

<p><a
href="http://10rem.net/media/84844/Windows-Live-Writer_3f6292c37abe_F3BC_image_2.png"
 target="_blank"><img src="http://10rem.net/media/84849/Windows-Live-Writer_3f6292c37abe_F3BC_image_thumb.png" width="308" height="335" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Build the solution.</p>

<p>Next, add a File Reference (not a project reference) from the
Silverlight 5 client app to the Silverlight 4 DLL.</p>

<p><a
href="http://10rem.net/media/84854/Windows-Live-Writer_3f6292c37abe_F3BC_image_4.png"
 target="_blank"><img src="http://10rem.net/media/84859/Windows-Live-Writer_3f6292c37abe_F3BC_image_thumb_1.png" width="500" height="269" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>If you build it now, everything works fine. The key step here is
to add code analysis. Many organizations have code analysis as a
required part of their build process, using the compiler
command-line arguments. If you don't, you can turn it on via the
menu:</p>

<p><a
href="http://10rem.net/media/84864/Windows-Live-Writer_3f6292c37abe_F3BC_image_8.png"
 target="_blank"><img src="http://10rem.net/media/84869/Windows-Live-Writer_3f6292c37abe_F3BC_image_thumb_3.png" width="342" height="257" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Then check the "Enable Code Analysis on Build" checkbox.</p>

<p><a
href="http://10rem.net/media/84874/Windows-Live-Writer_3f6292c37abe_F3BC_image_6.png"
 target="_blank"><img src="http://10rem.net/media/84879/Windows-Live-Writer_3f6292c37abe_F3BC_image_thumb_2.png" width="500" height="339" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Now build the solution. In theory, you'll get a CA0055 error,
but as I mentioned at the top, that doesn't happen on my install.
Most of the people who have reported this issue on the connect bug
have mentioned it in the context of the Business Application
Template or third party controls.</p>

<p><strong>Remember, this is a code analysis compile/build issue,
not a runtime issue, so if you get past compiling your application,
you're good.</strong></p>

<h3>The Workaround</h3>

<p>This is already planned to be fixed in Visual Studio 11 RC.
However, we do have a manual workaround for this to help you
continue working if you're running into this scenario today. This
will unblock using FxCop in Visual Studio 2010.</p>

<p>A high level walkthrough of how this works from the command line
is:</p>

<ul>
<li>We will tell FxCop which version of the runtime it will be
using by pointing it to Silverlight 5's installed mscorlib.dll
using the /platform argument</li>

<li>Tell FxCop where to find all of the referenced assemblies using
/d (short for /directory) arguments: Use as many /d:&lt;folder&gt;
arguments as necessary for FxCop to find all of the referenced
assemblies.</li>

<li>Use either /console to tell FxCop to output the results to the
console window, or /out:&lt;file&gt; to tell FxCop to write the
results to an .xml file</li>
</ul>

<p>To run FxCop from the command line for a default Business
Application:</p>

<ul>
<li>Add the %Visual Studio Install Directory%\Team Tools\Static
Analysis\FxCop folder to PATH</li>

<li>Run "fxcopcmd.exe /file:&lt;SL Business Application binary&gt;
/platform:&lt;SL5 Reference Assemblies Directory\mscorlib.dll&gt;
/d:&lt;SL4 Reference Assemblies Directory&gt; /d:&lt;SL4 SDK Client
Libraries Directory&gt;"</li>
</ul>

<p>An example of what this looks like on an x64 operating system
with all of the default install directories is:</p>

<ul>
<li>SET PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio
10.0\Team Tools\Static Analysis Tools\FxCop</li>

<li>fxcopcmd /file:BusinessApplication1.dll /platform:"C:\Program
Files (x86)\Reference
Assemblies\Microsoft\Framework\Silverlight\v5.0\mscorlib.dll"
/d:"C:\Program Files (x86)\Reference
Assemblies\Microsoft\Framework\Silverlight\v4.0" /d:"C:\Program
Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client"
/out:results.xml</li>

<li>NOTE: If you receive a CA0001 error: "The following error was
encountered while reading module 'XXXX.YYYYY' : Assembly reference
cannot be resolved…" this means that you need to find where that
assembly is installed to on your machine and add an additional
/d:&lt;installed directory&gt; argument pointing FxCop to where
those assemblies are installed.&nbsp;</li>
</ul>

<p>My thanks to the Silverlight Team and to Andrew Hall for the
information on this workaround.</p>

<p>Of course, the easiest and best solution, if you can do it, is
to use libraries that specifically target Silverlight 5, and make
sure all references from your Silverlight 5 project are to
libraries targeting Silverlight 5.&nbsp; We know that's not
possible in all cases, including the specific reported business
application case, which is why we documented this workaround.</p>
]]></description></item><item><title>Released: New Version of Expression Blend for Silverlight 5</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/03/29/released-new-version-of-expression-blend-for-silverlight-5</link><pubDate>Thu, 29 Mar 2012 18:32:38 GMT</pubDate><guid>http://10rem.net/blog/2012/03/29/released-new-version-of-expression-blend-for-silverlight-5</guid><description><![CDATA[ 
<p>You may have noticed that your current copy of Expression Blend
for Silverlight 5 expires in the next day or two. A new version of
Expression Blend Preview for Silverlight 5 is now out. <a
href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=9503"
 target="_blank">Get it here</a>.</p>

<p>This new version has the all important go-live license, and also
extends the expiration date to June 20, 2013 (over a year from
now)..</p>

<p>More information on the <a
href="http://blendinsider.com/version-expression-blend-4/updated-microsoft-expression-blend-preview-for-silverlight-5-2012-03-29/"
 target="_blank">Expression Blend Team Blog</a>.</p>
]]></description></item><item><title>XAML Tip: Setting Attached Properties from Code</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/03/29/xaml-tip-setting-attached-properties-from-code</link><pubDate>Thu, 29 Mar 2012 17:36:39 GMT</pubDate><guid>http://10rem.net/blog/2012/03/29/xaml-tip-setting-attached-properties-from-code</guid><description><![CDATA[ 
<p>Recently, <a
href="http://10rem.net/blog/2011/09/02/silverlight-5-and-wpf-4-opentype-support#comments"
 target="_blank">a reader asked</a> how they should go about
setting the Typography properties from code-behind.</p>

<p>The original question was about Silverlight, but the approach
works in WPF, Windows 8 and more.</p>

<p>Given the following markup:</p>

<pre class="brush: xml;">
&lt;StackPanel&gt;<br />
    &lt;TextBlock x:Name="OriginalText"<br />
               FontSize="72"<br />
               FontFamily="Gabriola"<br />
               Text="Hello World!" /&gt;<br />
<br />
    &lt;TextBlock x:Name="ExampleText"<br />
               FontSize="72"<br />
               FontFamily="Gabriola"<br />
               Text="Hello World!" /&gt;<br />
&lt;/StackPanel&gt;<br />
</pre>

<p>You can set an <a
href="http://msdn.microsoft.com/en-us/library/ms749011.aspx"
target="_blank">attached property</a> such as
<strong>Typography.StylisticSet5</strong> by using the
<strong>SetValue</strong> method like this:</p>

<pre class="brush: csharp;">
private void SetTextOptions()<br />
{<br />
    ExampleText.SetValue(Typography.StylisticSet5Property, true);<br />
}
</pre>

<p>The <strong>SetValue</strong> method comes from the
<strong>DependencyObject</strong> base class.
<strong>Typography.StylisticSet5Property</strong> is the name of a
dependency property - an attached property in this case. This could
easily have been the <strong>Canvas.Left</strong> property, the
<strong>Grid.Row</strong> property or any number of other attached
properties. The resulting display looks like this:</p>

<p><a
href="http://10rem.net/media/84198/Windows-Live-Writer_XAML-Tip-Setting-Attached-Properties-fro_BBAD_image_2.png"
 target="_blank"><img src="http://10rem.net/media/84203/Windows-Live-Writer_XAML-Tip-Setting-Attached-Properties-fro_BBAD_image_thumb.png" width="257" height="166" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Note how the second TextBlock has had the stylistic set applied
to it.</p>

<p>This approach used the <strong>SetValue</strong> method of the
dependency object. There's also another way:</p>

<pre class="brush: csharp;">
private void SetTextOptions()<br />
{<br />
    Typography.SetStylisticSet5(ExampleText, true);<br />
}
</pre>

<p>This version uses the <strong>Set[dpname]</strong> method of the
class which owns the property. Use the most convenient method. Both
are equivalent.</p>

<p>I also cover dependency properties and attached properties in
both of my <a href="http://manning.com/pbrown2/"
target="_blank">Silverlight books</a>, as well as in my upcoming
Windows 8 XAML book.</p>
]]></description></item><item><title>Tip: Binding an Image element’s Source property to a Uri in WinRT XAML</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/03/27/tip-binding-an-image-elements-source-property-to-a-uri-in-winrt-xaml</link><pubDate>Tue, 27 Mar 2012 19:00:23 GMT</pubDate><guid>http://10rem.net/blog/2012/03/27/tip-binding-an-image-elements-source-property-to-a-uri-in-winrt-xaml</guid><description><![CDATA[ 
<p>Over the years, I've conditioned myself to use the Uri class
when surfacing web URLs in my application. Early versions of
Silverlight couldn't bind an image source directly to an instance
of a Uri because they lacked an appropriate type converter; the
usual workaround was to change the property to a string type.</p>

<p>Subsequent versions Silverlight added that capability and the
converter. For example. Given an instance of the following model
class as the data context:</p>

<pre class="brush: csharp;">
public class Tweet<br />
{<br />
    public string Message { get; set; }<br />
    public Uri Image { get; set; }<br />
}
</pre>

<p>In Silverlight, you can bind in XAML like this:</p>

<pre class="brush: xml;">
<br />
&lt;Image Source="{Binding Image}" /&gt;<br />
</pre>

<p>In the current version of Windows 8/WinRT XAML, you can't bind
image sources directly to Uris, but there's a nice way to do it by
using property element syntax and and a BitmapImage class. It's
more verbose, but may be just the ticket if you need to bind to
Uris and not strings, and can't change, or don't want to change,
your [view]model.</p>

<pre class="brush: xml;">
&lt;Image&gt;<br />
    &lt;Image.Source&gt;<br />
        &lt;BitmapImage UriSource="{Binding Image}" /&gt;<br />
    &lt;/Image.Source&gt;<br />
&lt;/Image&gt;<br />
</pre>

<p>The team is aware of this difference, and have it in their
backlog of things to prioritize for future revs. In case you're
sharing markup or anything between WinRT XAML and Silverlight, it's
good to know this more verbose approach works in both.</p>
]]></description></item><item><title>Getting Started with XAML: Slides and demos</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/02/26/getting-started-with-xaml-slides-and-demos</link><pubDate>Mon, 27 Feb 2012 00:22:17 GMT</pubDate><guid>http://10rem.net/blog/2012/02/26/getting-started-with-xaml-slides-and-demos</guid><description><![CDATA[ 
<p>At the South Florida Code Camp last week, I gave an early
morning talk titled "Getting Started with XAML". In this talk, I
covered the basics of XAML, the property system, layout, and other
things you need to know as a XAML developer for WPF, Silverlight,
or Windows 8.</p>

<p><img src="http://10rem.net/media/83828/Windows-Live-Writer_ff6b33035bc2_11C5E_image_3.png" width="644" height="363" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<h3>Slides</h3>

<ul>
<li>Attached to this post</li>
</ul>

<h3>Demos</h3>

<p>It was all real-time stuff in this talk. No downloadable demos.
I encourage you to use the Getting Started content on MSDN:</p>

<ul>
<li><a href="http://msdn.microsoft.com/en-us/ff728590">Build your
first Silverlight web application</a></li>

<li><a href="http://msdn.microsoft.com/en-us/ff728576">Build your
first desktop RIA application with Silverlight</a></li>
</ul>

<p>Both include downloadable code in both C# and Visual Basic.</p>

<h3>My Silverlight Book</h3>

<ul>
<li><a href="http://manning.com/pbrown2/">Silverlight 5 in
Action</a></li>

<li>I also have a Windows 8 XAML book in progress. More on that
when it gets closer to publication</li>
</ul>

<h3>Related Links</h3>

<ul>
<li><a href="http://www.silverlight.net/">Home:
Silverlight.NET</a></li>

<li><a href="http://msdn.microsoft.com/en-us/windows">Windows Dev
Center</a> (for Windows 8 Metro XAML)</li>

<li><a href="http://windowsclient.net/">The Official Microsoft WPF
and Windows Forms Site</a></li>
</ul>
]]></description></item><item><title>REST with Silverlight 5, ASP.NET Web API, and MVC 4 Beta</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/02/26/rest-with-silverlight-5-aspnet-web-api-and-mvc-4-beta</link><pubDate>Sun, 26 Feb 2012 23:50:21 GMT</pubDate><guid>http://10rem.net/blog/2012/02/26/rest-with-silverlight-5-aspnet-web-api-and-mvc-4-beta</guid><description><![CDATA[ 
<p>At the South Florida Code Camp I gave a newer version of the
REST Silverlight talk using the just released MVC 4 Beta and
ASP.NET Web API.</p>

<p>This talk shows how to share code between different versions of
the framework, how to use the ASP.NET Web API from Silverlight, and
how to integrate a Silverlight application into an MVC 4 site.</p>

<p><img src="http://10rem.net/media/83782/Windows-Live-Writer_REST-with-Silverlight-5_1133C_image_thumb.png" width="644" height="364" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<h3>Powerpoint Slides</h3>

<ul>
<li>Attached to this post</li>
</ul>

<h3>Demos and Examples</h3>

<ul>
<li>Download the <a href="http://10rem.net/pub/demos/MVC4Beta_REST_SL5_Demo.zip"
target="_blank">full source and my demo snippit text file
here</a>.</li>
</ul>

<h3>My Book</h3>

<p>I cover this in my Silverlight 5 book. At the time of this
writing, the MEAP has the MVC3 version. I'll update it for the
print and ebook shortly.</p>

<ul>
<li><a href="http://manning.com/pbrown2/">Silverlight 5 in
Action</a></li>
</ul>

<h3>Related Links</h3>

<ul>
<li><a
href="http://weblogs.asp.net/jgalloway/archive/2012/02/16/asp-net-4-beta-released.aspx">
ASP.NET MVC 4 Beta Released! - Jon Galloway</a></li>

<li><a href="http://www.asp.net/web-api">Web API: The Official
Microsoft ASP.NET Site</a></li>

<li><a
href="http://10rem.net/blog/2011/08/01/creating-a-silverlight-5-helper-for-aspnet-mvc3-razor">
Creating a Silverlight 5 Helper for ASP.NET MVC3 Razor</a></li>

<li><a
href="http://www.hanselman.com/blog/OneASPNETMakingJSONWebAPIsWithASPNETMVC4BetaAndASPNETWebAPI.aspx">
One ASP.NET - Making JSON Web APIs with ASP.NET MVC 4 Beta and
ASP.NET Web API - Scott Hanselman</a></li>

<li><a href="http://wcf.codeplex.com/">WCF Community Site</a> (for
older WCF version)</li>
</ul>

<h3>Previous Versions</h3>

<ul>
<li><a
href="http://10rem.net/blog/2011/12/15/slides-and-code-from-my-vslive-silverlight-5-rest-wcf-web-api-mvc-talk">
Slides and Code from my VSLive Silverlight 5, REST, WCF Web API,
MVC talk</a> (MVC 3 version)</li>
</ul>
]]></description></item><item><title>A Lap Around Silverlight 5: Slides and Code</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/02/26/a-lap-around-silverlight-5-slides-and-code</link><pubDate>Sun, 26 Feb 2012 23:30:47 GMT</pubDate><guid>http://10rem.net/blog/2012/02/26/a-lap-around-silverlight-5-slides-and-code</guid><description><![CDATA[ 
<p>At the South Florida Code Camp, I gave the "Lap Around
Silverlight 5" talk. The slides and code are all available via the
links below.</p>

<p><img src="http://10rem.net/media/83760/Windows-Live-Writer_65e267c6fe8f_F85C_image_3.png" width="644" height="364" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<h3>Powerpoint Slides</h3>

<ul>
<li>Attached to this post</li>
</ul>

<h3>Demos and Examples</h3>

<ul>
<li><a
href="http://10rem.net/blog/2011/09/04/the-big-list-of-whats-new-or-improved-in-silverlight-5">
The Big List of What's New or Improved in Silverlight 5 - Pete
Brown's 10rem.net</a></li>

<li><a
href="http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5">
Threading Considerations for Binding and Change Notification in
Silverlight 5</a></li>

<li><a
href="http://10rem.net/blog/2012/02/07/creating-big-silverlight-windows-and-getting-monitor-resolutions-and-positions-with-pinvoke">
Creating Big Silverlight Windows and Getting Monitor Resolutions
and Positions with PInvoke</a></li>

<li><a
href="http://10rem.net/blog/2011/04/13/silverlight-5-using-the-soundeffect-class-for-low-latency-sound-and-play-wav-files-in-silverlight">
Silverlight 5: Using the SoundEffect Class for Low-Latency Sound
(and play WAV files in Silverlight)</a></li>

<li><a
href="http://10rem.net/blog/2011/04/13/silverlight-5-working-with-operating-system-windows">
Silverlight 5: Working with Operating System Windows</a></li>

<li><a
href="http://10rem.net/blog/2011/04/13/silverlight-5-working-with-implicit-templates">
Silverlight 5: Working with Implicit Templates</a></li>

<li><a
href="http://10rem.net/blog/2011/04/13/silverlight-5-debugging-bindings-with-xaml-breakpoints">
Silverlight 5: Debugging Bindings with Xaml Breakpoints</a></li>

<li><a
href="http://10rem.net/blog/2011/04/13/silverlight-5-supporting-double-and-even-triple-click-for-the-mouse">
Silverlight 5: Supporting Double and Even Triple Click for the
Mouse</a></li>

<li style="list-style: none">
<ul>
<li><a
href="http://10rem.net/blog/2011/04/25/supporting-both-double-and-triple-click-in-silverlight-5">
Supporting both Double and Triple Click in Silverlight 5</a>
(article with the timer approach)</li>
</ul>
</li>

<li><a
href="http://10rem.net/blog/2011/04/13/silverlight-5-advancements-in-text">Silverlight
5: Advancements in Text</a></li>
</ul>

<h3>My Book</h3>

<ul>
<li><a href="http://manning.com/pbrown2/"
target="_blank">Silverlight 5 in Action</a><!--EndFragment--></li>
</ul>

<h3>Downloads</h3>

<ul>
<li><a
href="http://code.msdn.microsoft.com/3D-Housebuilder-demo-from-def4af04">
Download the 3D House Builder Demo Application</a></li>

<li><a href="http://babylontoolkit.codeplex.com/">See the Babylon
3d Engine on CodePlex</a></li>
</ul>

<h3>Related Links</h3>

<ul>
<li><a
href="http://www.silverlight.net/getstarted/silverlight-5-beta/">Silverlight
5 Page on Silverlight.net</a></li>

<li><a
href="http://10rem.net/blog/2011/04/13/announcing-the-silverlight-5-beta-release-and-the-silverlightnet-redesign">
Announcing the Silverlight 5 Beta Release and the Silverlight.net
Redesign</a></li>
</ul>

<h3>Previous Versions</h3>

<ul>
<li><a
href="http://10rem.net/blog/2011/05/23/slides-videos-and-downloads-from-my-tech-ed-atlanta-2011-and-recent-user-group-talks">
Slides, Videos, and Downloads from my Tech Ed Atlanta 2011 and
Recent User Group Talks</a></li>

<li><a
href="http://10rem.net/blog/2011/10/25/updated-slides-and-demos-from-vslive-redmond-2011">
Updated Slides and Demos from VSLive Redmond 2011</a></li>
</ul>
]]></description></item><item><title>Windows Client Developer Roundup 087 for 2/9/2012</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/02/08/windows-client-developer-roundup-087-for-2-9-2012</link><pubDate>Thu, 09 Feb 2012 02:44:11 GMT</pubDate><guid>http://10rem.net/blog/2012/02/08/windows-client-developer-roundup-087-for-2-9-2012</guid><description><![CDATA[ 
<p>The Windows Client Developer Roundup aggregates information of
interest to Windows Client Developers, including <a
href="http://dev.windows.com/">WinRT XAML</a>, <a
href="http://windowsclient.net/">WPF</a>, <a
href="http://silverlight.net/">Silverlight</a>, <a
href="http://msdn.microsoft.com/en-us/visualc/default.aspx">Visual
C++</a>, <a href="http://creators.xna.com/">XNA</a>, <a
href="http://expression.microsoft.com/">Expression Blend</a>, <a
href="http://www.microsoft.com/surface/">Surface</a>, <a
href="http://msdn.microsoft.com/en-us/windows/default.aspx">Windows
7</a>, <a
href="http://msdn.microsoft.com/en-us/ff380145.aspx">Windows
Phone</a>, Visual Studio, <a
href="http://silverlight.net/riaservices/">WCF RIA Services</a> and
more. Sometimes I even include a little jQuery and HTML5. If you
have something interesting you've done or have run across, or you
blog regularly on the topics included here, please send me the URL
and brief description via the <a href="http://10rem.net/contact">contact
link</a>.</p>

<p>Note that I've started breaking the Netduino, Electronics,
Robotics, Synthesizer and similar content into a new roundup series
called the <a href="http://10rem.net/blog?filterby=MakerRoundup">Maker Geek
Roundup</a>.</p>

<p><strong>Oh and you'll get Windows 8 Consumer Preview on February
29. Get ready to code (and</strong> <a
href="http://10rem.net/blog/2012/01/25/now-more-than-ever-you-need-a-designer">
<strong>design</strong></a><strong>) :)</strong></p>

<h3>Windows 8 and WinRT/Metro General</h3>

<ul>
<li><a
href="http://blogs.msdn.com/b/b8/archive/2012/02/07/improving-power-efficiency-for-applications.aspx">
Improving power efficiency for applications</a> (Sharif Farag and
Ben Srour)</li>
</ul>

<h3>XAML Technologies (Silverlight, WPF, WinRT Metro XAML)</h3>

<ul>
<li><a
href="http://grokys.blogspot.com/2012/02/mvvm-and-multiple-selection-part-iv.html">
Bad Entropy: MVVM and Multiple Selection - Part IV - DataGrid</a>
(Bad Entropy)</li>

<li><a
href="http://www.sharpgis.net/post/2012/01/23/Overwriting-the-default-WebRequest-used-by-WebClient.aspx">
Overwriting the default WebRequest used by WebClient</a> (Morten
Nielsen)</li>

<li><a
href="http://www.sharpgis.net/post/2012/01/17/Building-A-Multi-Touch-Photo-Viewer-Control.aspx">
Building A Multi-Touch Photo Viewer Control</a> (Morten
Nielsen)</li>

<li><a
href="http://www.abhisheksur.com/2012/02/optimizing-inpc-objects-against-memory.html">
DOT NET TRICKS: Optimizing INPC Objects against memory leaks using
WeakEvents</a> (Abhishek Sur)</li>

<li style="list-style: none">
<ul>
<li>Also see <a
href="http://10rem.net/blog/2012/02/01/event-handler-memory-leaks-unwiring-events-and-the-weakeventmanager-in-wpf-45">
my post on weak events.</a></li>
</ul>
</li>

<li><a
href="http://michaelcrump.net/using-the-live-sdk-in-windows-8-xaml/c-metro-applications">
Using the Live SDK in Windows 8 XAML/C# Metro Applications -
Michael Crump</a> (Michael Crump)</li>

<li><a
href="http://www.sharpgis.net/post/2012/01/12/Reading-and-Writing-text-files-in-Windows-8-Metro.aspx">
Reading and Writing text files in Windows 8 Metro</a> (Morten
Nielsen)</li>

<li><a
href="http://www.scottlogic.co.uk/blog/colin/2012/02/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight/">
A Simple Pattern for Creating Re-useable UserControls in WPF /
Silverlight</a> (Colin Eberhardt)</li>
</ul>

<h3>DirectX Technologies (DirectX, XNA, WinRT DirectX, GPU and Game
Programming)</h3>

<ul>
<li><a
href="http://xna-uk.net/blogs/darkgenesis/archive/2012/01/20/the-starter2d-and-starter3d-tutorials-now-on-the-marketplace.aspx">
The Starter2D and Starter3D tutorials now on the Marketplace</a>
(Dark Genesis)</li>

<li><a
href="http://channel9.msdn.com/coding4fun/blog/Large-Scale-Terrain-Rendering">
Large Scale Terrain Rendering</a> (Coding4Fun)</li>
</ul>

<h3>C++ and Native Development</h3>

<ul>
<li><a
href="http://geekswithblogs.net/mikebmcl/archive/2012/02/02/c-to-c-ndash-a-somewhat-short-guide.aspx">
C# to C++ - A Somewhat Short Guide</a> (Bob Taco Industries)</li>

<li><a
href="http://blogs.msdn.com/b/vcblog/archive/2012/02/02/10263304.aspx">
C++11 Conformance Survey</a> (Vikas Bhatia)</li>

<li><a
href="http://blogs.msdn.com/b/vcblog/archive/2012/02/03/10263262.aspx">
The Microsoft C++ Compiler Turns 20!</a> (Visual C++ Blog)</li>

<li><a
href="http://blogs.msdn.com/b/somasegar/archive/2012/02/03/c-amp-open-specification.aspx">
C++ AMP Open Specification</a> (Soma)</li>

<li><a
href="http://channel9.msdn.com/posts/Announcing-the-GoingNative-2012-Full-Schedule">
GoingNative 2012: All Sessions are now available On-Demand!</a>
(Channel 9)</li>
</ul>

<h3>Visual Studio and .NET General</h3>

<ul>
<li><a
href="http://blogs.msdn.com/b/visualstudio/archive/2012/01/18/announcing-visual-studio-achievements.aspx">
Bring Some Game To Your Code!</a> (Visual Studio Blog)</li>
</ul>

<h3>NUI (Kinect, Surface, More)</h3>

<ul>
<li><a
href="http://robrelyea.wordpress.com/2012/02/01/k4w-details-of-api-changes-from-beta2-to-v1-managed/">
Kinect for Windows - Details of API Changes from Beta2 to v1.0
(C#/VB)</a> (Rob Relyea)</li>

<li><a
href="http://blogs.msdn.com/b/surface/archive/2012/02/05/microsoft-surface-2-sdk-and-runtime-update.aspx">
Microsoft® Surface® 2.0 SDK and Runtime Update</a> (Luis
Cabrera)</li>

<li><a
href="http://kinecthacks.net/interactive-portfolio/">Interactive
Portfolio</a> (Kinect Hacks)</li>
</ul>

<h3>Off-Topic Fun</h3>

<ul>
<li><a href="http://www.youtube.com/watch?v=LJSZ1TwjcsQ">The Karate
Rap</a> (YouTube)</li>
</ul>

<p>I leave you with only the one "off-topic" item today, because
after watching that, nothing else will ever suffice. Ever.</p>
]]></description></item><item><title>Creating Big Silverlight Windows and Getting Monitor Resolutions and Positions with PInvoke</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/02/07/creating-big-silverlight-windows-and-getting-monitor-resolutions-and-positions-with-pinvoke</link><pubDate>Wed, 08 Feb 2012 03:59:11 GMT</pubDate><guid>http://10rem.net/blog/2012/02/07/creating-big-silverlight-windows-and-getting-monitor-resolutions-and-positions-with-pinvoke</guid><description><![CDATA[ 
<p>While doing the (long!) tech review for Silverlight 5 in Action,
my friend and former coworker <a
href="http://codemares.blogspot.com/">Tom McKearney</a> mentioned
that we should put together some code to make handling windows
across multiple monitors a reasonable task in Silverlight 5. Then,
on a mailing list, I recently saw the question:</p>

<blockquote>
<p>Hi all -- I'm wondering if there is a maximum window size for
Silverlight documented anywhere. For example if I had hardware that
could support a 3x3 or 3x4 grid of 1920x1080 displays, can I make
an SL5 OOB window that big? Can I make individual items in the
window that big? Can I get hardware acceleration on all of it? Does
the 3D API have any different limits than XAML? Or maybe
Silverlight has no specific limit, but it's up to the hardware?</p>
</blockquote>

<p>Curious about that, I decided to try it myself, and combine this
with what Tom had requested. I don't have a 3x3 array of screens
that size, however. It really is a serious number of pixels.</p>

<p><a
href="http://10rem.net/media/83370/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_2.png"
 target="_blank"><img src="http://10rem.net/media/83375/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb.png" width="650" height="234" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Cost of screens aside, most people don't have the video hardware
to be able to run 6 displays. ATI has some displayport cards which
will do that, but otherwise you're looking at a minimum of three
video cards and a variety of connections. You're also looking at a
shedload of video memory.</p>

<p>What I do have is a pair of 30" displays each running at
2560x1600. That's quite a bit smaller, but still much larger than
most people have. It ends up being a bit less than half the
requested pixels. I do get almost the right width, but the height
is lacking.</p>

<p><a
href="http://10rem.net/media/83380/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_4.png"
 target="_blank"><img src="http://10rem.net/media/83385/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb_1.png" width="650" height="142" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>I wouldn't want 3x3 of the HD res screens (too much bevel)
unless they were big old TV-style ones and you were doing
relatively low-res graphics. 3x3 of the 2560x1600 though?
*drool*</p>

<p>In any case, my two combined are still quite a bit larger than
the typical HD res 1920x1080 screen people have, with its 2,073,600
pixels, and is a valid test of creating big windows in
Silverlight.</p>

<p>My displays are also oriented a little differently than you may
expect:</p>

<p><a
href="http://10rem.net/media/83390/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_6.png"
 target="_blank"><img src="http://10rem.net/media/83395/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb_2.png" width="500" height="326" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>That means that logical 0,0 is in the middle of the combined
display. We'll need to know that for later.</p>

<h3>Creating the Window</h3>

<p>If you want to learn how to create out-of-browser windows in
Silverlight 5, <a
href="http://10rem.net/blog/2011/04/13/silverlight-5-working-with-operating-system-windows">
see my post here</a>.</p>

<p>The first test is to see if I can create a window that fits the
dimensions of my two screens. All sizes here will be
hard-coded.</p>

<p>XAML</p>

<pre class="brush: xml;">
&lt;UserControl x:Class="PeteBrown.SilverlightBigWindow.MainPage"<br />
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"<br />
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"<br />
    mc:Ignorable="d"<br />
    d:DesignHeight="175<br />
             " d:DesignWidth="800"&gt;<br />
<br />
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;<br />
        &lt;ListBox x:Name="DisplayList"<br />
                 Margin="126,12,12,12"&gt;<br />
            &lt;ListBox.ItemTemplate&gt;<br />
                &lt;DataTemplate&gt;<br />
                    &lt;Grid&gt;<br />
                        &lt;Grid.ColumnDefinitions&gt;<br />
                            &lt;ColumnDefinition Width="150" /&gt;<br />
                            &lt;ColumnDefinition Width="50" /&gt;<br />
                            &lt;ColumnDefinition Width="150" /&gt;<br />
                            &lt;ColumnDefinition Width="150" /&gt;<br />
                            &lt;ColumnDefinition Width="75" /&gt;<br />
                            &lt;ColumnDefinition Width="75" /&gt;<br />
                        &lt;/Grid.ColumnDefinitions&gt;<br />
<br />
                        &lt;TextBlock Grid.Column="0"<br />
                                   Text="{Binding MonitorName}" /&gt;<br />
                        &lt;TextBlock Grid.Column="1"<br />
                                   Text="{Binding IsPrimary}" /&gt;<br />
                        &lt;TextBlock Grid.Column="2"<br />
                                   Text="{Binding MonitorArea}" /&gt;<br />
                        &lt;TextBlock Grid.Column="3"<br />
                                   Text="{Binding WorkArea}" /&gt;<br />
                        &lt;TextBlock Grid.Column="4"<br />
                                   Text="{Binding Width}" /&gt;<br />
                        &lt;TextBlock Grid.Column="5"<br />
                                   Text="{Binding Height}" /&gt;<br />
<br />
<br />
                    &lt;/Grid&gt;<br />
                &lt;/DataTemplate&gt;<br />
            &lt;/ListBox.ItemTemplate&gt;<br />
        &lt;/ListBox&gt;<br />
     <br />
     <br />
        &lt;Button Content="Open Full"<br />
                Height="23"<br />
                HorizontalAlignment="Left"<br />
                Margin="12,12,0,0"<br />
                Name="OpenWindow"<br />
                VerticalAlignment="Top"<br />
                Width="108"<br />
                Click="OpenWindow_Click" /&gt;<br />
        &lt;Button Content="Open Primary"<br />
                Height="23"<br />
                HorizontalAlignment="Left"<br />
                Margin="12,41,0,0"<br />
                Name="OpenPrimary"<br />
                VerticalAlignment="Top"<br />
                Width="108"<br />
                Click="OpenPrimary_Click" /&gt;<br />
        &lt;Button Content="Open Secondary"<br />
                Height="23"<br />
                HorizontalAlignment="Left"<br />
                Margin="12,70,0,0"<br />
                Name="OpenSecondary"<br />
                VerticalAlignment="Top"<br />
                Width="108"<br />
                Click="OpenSecondary_Click" /&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/UserControl&gt;<br />
</pre>

<p>C# code</p>

<pre class="brush: csharp;">
private void OpenWindow_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Window w = new Window();<br />
<br />
    w.Width = 5120;<br />
    w.Height = 1600;<br />
<br />
    w.Show();<br />
}<br />
<br />
private void OpenPrimary_Click(object sender, RoutedEventArgs e)<br />
{<br />
}<br />
<br />
private void OpenSecondary_Click(object sender, RoutedEventArgs e)<br />
{<br />
}
</pre>

<p>This will allow me to click a button and have it open a giant
window on the screen. The window has no content, so it'll appear as
a plain white empty window.</p>

<p>Run it (remember, must be elevated trust out-of-browser app) and
what do you see? No problem. One giant white window which fits
across my screen.</p>

<p><a
href="http://10rem.net/media/83400/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_8.png"
 target="_blank"><img src="http://10rem.net/media/83405/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb_3.png" width="650" height="203" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>The problem is, however, that it starts in the middle of my
displays instead of over at the far left. I had to drag it to the
far left to get it to take up the whole set of displays. How do we
figure out how to position and size the window?</p>

<h3>Positioning and Sizing the Window</h3>

<p>On my setup, the monitor to the left is all in negative space.
So, to move the window to the far left, I need to move it to -2560.
Then we can open the window and then tell it to move to the top
left, or to take up just a single display.</p>

<pre class="brush: csharp;">
private void OpenWindow_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Window w = new Window();<br />
<br />
    w.Width = 5120;<br />
    w.Height = 1600;<br />
<br />
    w.Left = -2560;<br />
    w.Top = 0;<br />
    w.Show();<br />
}<br />
<br />
private void OpenPrimary_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Window w = new Window();<br />
<br />
    w.Width = 2560;<br />
    w.Height = 1600;<br />
<br />
<br />
    w.Left = 0;<br />
    w.Top = 0;<br />
    w.Show();<br />
}<br />
<br />
private void OpenSecondary_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Window w = new Window();<br />
<br />
    w.Width = 2560;<br />
    w.Height = 1600;<br />
<br />
    w.WindowStyle = WindowStyle.None;<br />
<br />
    w.WindowState = WindowState.Maximized;<br />
<br />
    w.Left = -2560;<br />
    w.Top = 0;<br />
    w.Show();<br />
}
</pre>

<p>Ok, so we've verified that it can be done. Now we need to make
it work for arbitrary resolutions and monitor configurations.
<strong>Before we do that, though, did you notice that the sizing
was off a bit?</strong> Both the width and height appear to be off
by the measurements of the window chrome. It turns out this happens
whether or not you're using custom chrome. <strong>I've reported a
bug to the team and they're investigating</strong>, so for now
we're going to have to ignore the size issues. <strong>If you work
around the sizing in your own code, stick it in an conditional
compilation block</strong> or something so you can easily change it
if/when the bug is fixed.</p>

<h3>Getting Display Informatin Using PInvoke</h3>

<p>We're running in elevated OOB mode anyway, so as long as you
only care about Windows, you can also throw in some P/Invoke. The
main functions we're interested in are <a
href="http://pinvoke.net/default.aspx/user32.EnumDisplayMonitors">EnumDisplayMonitors</a>
and <a
href="http://msdn.microsoft.com/en-us/library/dd144901(v=VS.85).aspx">
GetMonitorInfo</a>.</p>

<p>The PInvoke.net example was enough to get me started, but it
lacked a few necessary steps. Of course, it also needed some
changes to work with Silverlight.</p>

<p>The first addition is the DisplayInfo class. We'll use this to
hold information about a single monitor.</p>

<pre class="brush: csharp;">
namespace PeteBrown.SilverlightBigWindow<br />
{<br />
    public class DisplayInfo<br />
    {<br />
        public string MonitorName { get; internal set; }<br />
        public Win32Rect MonitorArea { get; internal set; }<br />
        public Win32Rect WorkArea { get; internal set; }<br />
        public int Width { get; internal set; }<br />
        public int Height { get; internal set; }<br />
        public bool IsPrimary { get; internal set; }<br />
    }<br />
}
</pre>

<p>Next, I need a way to populate this class. Here's where all the
PInvoke action happens.</p>

<pre class="brush: csharp;">
using System;<br />
using System.Runtime.InteropServices;<br />
using System.Collections.ObjectModel;<br />
<br />
namespace PeteBrown.SilverlightBigWindow<br />
{<br />
<br />
    [StructLayout(LayoutKind.Sequential)]<br />
    public struct Win32Rect<br />
    {<br />
        public int Left { get; set; }<br />
        public int Top { get; set; }<br />
        public int Right { get; set; }<br />
        public int Bottom { get; set; }<br />
<br />
        public override string ToString()<br />
        {<br />
            return string.Format("{0}, {1}, {2}, {3}", Left, Top, Right, Bottom);<br />
        }<br />
    }<br />
<br />
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]<br />
    internal struct MonitorInfoEx<br />
    {<br />
        public int Size;<br />
        public Win32Rect Monitor;<br />
        public Win32Rect WorkArea;<br />
        public uint Flags;<br />
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = DisplayManager.DeviceNameCharacterCount)]<br />
        public string DeviceName;<br />
<br />
        public void Init()<br />
        {<br />
            this.Size = 40 + 2 * DisplayManager.DeviceNameCharacterCount;<br />
            this.DeviceName = string.Empty;<br />
        }<br />
    }<br />
<br />
 <br />
    public class DisplayManager<br />
    {<br />
        // size of a device name string<br />
        internal const int DeviceNameCharacterCount = 32;<br />
<br />
<br />
        private delegate bool MonitorEnumProcDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref Win32Rect lprcMonitor, uint dwData);<br />
<br />
        [DllImport("user32.dll")]<br />
        private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProcDelegate lpfnEnum, uint dwData);<br />
<br />
        [DllImport("user32.dll", CharSet = CharSet.Auto)]<br />
        private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);<br />
<br />
        private static ObservableCollection&lt;DisplayInfo&gt; _displays = new ObservableCollection&lt;DisplayInfo&gt;();<br />
        public static ObservableCollection&lt;DisplayInfo&gt; Displays<br />
        {<br />
            get { return _displays; }<br />
        }<br />
<br />
<br />
        public static void LoadDisplays()<br />
        {<br />
            EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, MonitorEnumProc, 0);<br />
        }<br />
<br />
        [AllowReversePInvokeCalls]<br />
        internal static bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref Win32Rect lprcMonitor, uint dwData)<br />
        {<br />
            var monitor = new MonitorInfoEx();<br />
            monitor.Init();<br />
<br />
            bool success = GetMonitorInfo(hMonitor, ref monitor);<br />
<br />
            if (success)<br />
            {<br />
                var display = new DisplayInfo();<br />
<br />
                display.MonitorName = monitor.DeviceName;<br />
<br />
                display.Width = monitor.Monitor.Right - monitor.Monitor.Left;<br />
                display.Height = monitor.Monitor.Bottom - monitor.Monitor.Top;<br />
<br />
                display.MonitorArea = monitor.Monitor;<br />
                display.WorkArea = monitor.WorkArea;<br />
                display.IsPrimary = (monitor.Flags &gt; 0);<br />
<br />
                _displays.Add(display);<br />
            }<br />
<br />
            return true;<br />
        }<br />
    }<br />
}<br />
</pre>

<p>This code calls EnumDisplayMonitors to enumerate the monitors on
the system. For each monitor found, I then call GetMonitorInfo to
pull back the details. From that call, I create a DisplayInfo class
and populate it, ready to be used by the rest of the Silverlight
application. The list of DisplayInfo classes is stored in a
class-scope collection.</p>

<p>Note the "AllowReversePInvokeCalls" attribute on
MonitorEnumProc. That attribute is required for any callbacks. It
also means we couldn't use a simple anonymous delegate for the
callback, as those can't have attributes.</p>

<p>Finally, a short call in MainPage.xaml and we're able to get the
display sizes</p>

<pre class="brush: csharp;">
public MainPage()<br />
{<br />
    InitializeComponent();<br />
<br />
    DisplayManager.LoadDisplays();<br />
<br />
    DisplayList.ItemsSource = DisplayManager.Displays;<br />
}
</pre>

<p>Run the application. On my screen, it looks like this:</p>

<p><a
href="http://10rem.net/media/83410/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_12.png"
 target="_blank"><img src="http://10rem.net/media/83415/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb_5.png" width="650" height="177" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Ok, so now we know how to position a display using hard-coded
values, and how to get the display list from windows. Now, to
combine the two to help with sizing and positioning.</p>

<h3>Positioning and Sizing the Window</h3>

<p>Positioning the window can be tricky. There are any number of
ways that monitors can be configured. Here are just a few
interesting (and common) ones, in addition to the ones mentioned
above:</p>

<p><a
href="http://10rem.net/media/83420/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_16.png"
 target="_blank"><img src="http://10rem.net/media/83425/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb_7.png" width="650" height="176" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>If you look at the teal and the green examples, you can see
where a rectangular pixel mapping puts some logical pixels out into
never-never land. On systems like that, a single window spanning
all displays is not particularly practical. In any case, most
multi-display configurations are two, or at most, three displays
because that's all you can typically drive from a single typical
video card.</p>

<p>As an aside, I've run with all four examples shown above, plus a
few extras. My current layout is 2x 30" displays side by side with
primary on right and secondary on left, plus a 23" display on top
of the primary. The 23" display is connected to a different
computer, however, and shared using Input Director, so it doesn't
factor into this discussion.</p>

<p>With just the two displays I have, it's easy to test a number of
different scenarios simply by changing resolution and monitor
position in display settings. First, some code to position the
window on a specific screen.</p>

<h4>Position Window on Primary Display</h4>

<p>A PC can have only one primary display. Conveniently, the
display is called out as such via the API.</p>

<pre class="brush: csharp;">
private void PositionWindowOnSingleScreen(DisplayInfo screen, Window window, bool SizeToScreen = true, bool maximize = false)<br />
{<br />
    window.Left = screen.MonitorArea.Left;<br />
    window.Top = screen.MonitorArea.Top;<br />
<br />
    if (SizeToScreen)<br />
    {<br />
        window.Width = screen.Width;<br />
        window.Height = screen.Height;<br />
    }<br />
<br />
    if (maximize)<br />
        window.WindowState = WindowState.Maximized;<br />
}<br />
<br />
<br />
private void OpenPrimary_Click(object sender, RoutedEventArgs e)<br />
{<br />
    if (DisplayManager.Displays.Count &gt; 0)<br />
    {<br />
        // find primary display<br />
        DisplayInfo info = (from DisplayInfo di in DisplayManager.Displays<br />
                            where di.IsPrimary<br />
                            select di).FirstOrDefault();<br />
<br />
        if (info != null)<br />
        {<br />
            Window w = new Window();<br />
<br />
            PositionWindowOnSingleScreen(info, w, true, false);<br />
<br />
            w.Show();<br />
        }<br />
        else<br />
        {<br />
            MessageBox.Show("No primary display. I suppose you won't see this message.");<br />
        }<br />
    }<br />
    else<br />
    {<br />
        MessageBox.Show("Display list not yet loaded.");<br />
    }<br />
<br />
}
</pre>

<p>This example uses a little LINQ to find the primary screen and
then a separate function to position the window on that screen. I
can't think of a case where you'd have no primary display, but I
check for it anyway.</p>

<h4>Position Window on Secondary Display</h4>

<p>Primary is cool. You can do that without any API calls.
Secondary is normally a little more work, but I have you
covered.</p>

<p>You can, of course, have more than one secondary display. In my
case, I have only one, so I'm going to position this window in the
first secondary display I have.</p>

<pre class="brush: csharp; highlight: [7];">
private void OpenSecondary_Click(object sender, RoutedEventArgs e)<br />
{<br />
    if (DisplayManager.Displays.Count &gt; 0)<br />
    {<br />
        // find first secondary display<br />
        DisplayInfo info = (from DisplayInfo di in DisplayManager.Displays<br />
                            where !di.IsPrimary<br />
                            select di).FirstOrDefault();<br />
<br />
        if (info != null)<br />
        {<br />
            Window w = new Window();<br />
<br />
            PositionWindowOnSingleScreen(info, w, true, false);<br />
<br />
            w.Show();<br />
        }<br />
        else<br />
        {<br />
            MessageBox.Show("No secondary display available.");<br />
        }<br />
    }<br />
    else<br />
    {<br />
        MessageBox.Show("Display list not yet loaded.");<br />
    }<br />
}
</pre>

<p>In this case, all I needed to change was the error message and
add a little bang in the where clause of the LINQ query.</p>

<h4>Make a window take up all Display Space</h4>

<p>This goes specifically to the 3x3 screen scenario. As I
mentioned, we'll need to assume rectangular window space here, as
anything else is going to be pretty application-specific.</p>

<pre class="brush: csharp;">
private void OpenWindow_Click(object sender, RoutedEventArgs e)<br />
{<br />
    if (DisplayManager.Displays.Count &gt; 0)<br />
    {<br />
        Window w = new Window();<br />
<br />
        w.Left = (from DisplayInfo di in DisplayManager.Displays<br />
                  select di.MonitorArea.Left).Min();<br />
<br />
        w.Top = (from DisplayInfo di in DisplayManager.Displays<br />
                 select di.MonitorArea.Top).Min();<br />
<br />
        w.Width = (from DisplayInfo di in DisplayManager.Displays<br />
                   select di.Width).Sum();<br />
<br />
        w.Height = (from DisplayInfo di in DisplayManager.Displays<br />
                    select di.Height).Sum();<br />
<br />
        w.Show();<br />
    }<br />
    else<br />
    {<br />
        MessageBox.Show("Display list not yet loaded.");<br />
    }<br />
}
</pre>

<p>Because we're assuming a reasonably logical rectangle, I can
simply take the minimum left and top values and use that to
position the window, and then sum the height and width values in
order to size the window.</p>

<p>As an aside, Silverlight had no issues opening this window on my
machine. I'm not sure I'd recommend stretching a video across it,
though.</p>

<p>Well, actually, I can't let that lie out there like that. Let's
try it. Add this code right after the w.Height setting and before
the w.Show() line</p>

<pre class="brush: csharp;">
MediaElement video = new MediaElement();<br />
video.Width = w.Width;<br />
video.Height = w.Height;<br />
video.Source = new Uri("/pub/sl5iA/NetduinoRobot_SmallM.wmv", UriKind.Absolute);<br />
video.Stretch = Stretch.UniformToFill;<br />
video.AutoPlay = true;<br />
<br />
w.Content = video;
</pre>

<p>I stretch the video so it takes up all space (UniformToFill) and
clips the video so the aspect ratio stays correct. It works, and
works well, If the the video was high enough resolution, it would
even look good.</p>

<p><a
href="http://10rem.net/media/83430/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_18.png"
 target="_blank"><img src="http://10rem.net/media/83435/Windows-Live-Writer_Creating-Big-Silverlight-Windows_123FB_image_thumb_8.png" width="531" height="166" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Sweet! Big video. That's almost like IMax or <a
href="http://en.wikipedia.org/wiki/Ultra_High_Definition_Television">
UHDTV</a> :)</p>

<h4>Position Main Window on a Named Display</h4>

<p>This is particularly useful if you're restoring windows when
starting up a new session. You could store the display device name
and then do some checks on startup and if the device name and
resolution are still valid (they could have swapped displays,
bought new ones, got rid of one, etc.) position the window on that
display. If not, position it on the main display.</p>

<p>In this case, I'm simply going to position the main Silverlight
window on to the display you click on in the ListBox. The code is
simple enough. First, add a button to the MainPage, under the other
buttons.</p>

<pre class="brush: xml;">
&lt;Button Content="Move to Selected"<br />
        Height="23"<br />
        HorizontalAlignment="Left"<br />
        Margin="12,115,0,0"<br />
        Name="MoveToSelectedButton"<br />
        VerticalAlignment="Top"<br />
        Width="108"<br />
        Click="MoveToSelectedButton_Click" /&gt;<br />
</pre>

<p>Next, the event handler and work function in the code-behind.
<strong>There are many ways I could have done this (especially
using SelectedItem), but I specifically want to show using the
device name</strong>. I know it's extra work, but I'm doing it
on-purpose; the value you store upon exiting is not going to be an
object instance, it's going to be a screen device name string.</p>

<pre class="brush: csharp;">
private void MoveMainWindowToSelectedDisplay()<br />
{<br />
    // see comments in blog post as to why I went with strings<br />
    string deviceName = ((DisplayInfo)DisplayList.SelectedItem).MonitorName;<br />
<br />
    DisplayInfo display = (from DisplayInfo di in DisplayManager.Displays<br />
                            where di.MonitorName.ToLower() == deviceName.ToLower()<br />
                            select di).FirstOrDefault();<br />
<br />
    var mainWindow = Application.Current.MainWindow;<br />
<br />
    // center on the display<br />
<br />
    mainWindow.Left = display.MonitorArea.Left + (display.Width - mainWindow.Width) / 2;<br />
    mainWindow.Top = display.MonitorArea.Top + (display.Height - mainWindow.Height) / 2;<br />
<br />
}<br />
<br />
private void MoveToSelectedButton_Click(object sender, RoutedEventArgs e)<br />
{<br />
    if (DisplayList.SelectedItem != null)<br />
    {<br />
        MoveMainWindowToSelectedDisplay();<br />
    }<br />
    else<br />
    {<br />
        MessageBox.Show("Please select a screen from the list");<br />
    }<br />
}
</pre>

<p>The code moves the window to the selected monitor and then
centers in that monitor. Some additional checking to make sure the
window isn't wider than that monitor would be a good idea.</p>

<h3>Summary</h3>

<p>The intent of this post was to give you the foundation you'll
need in order to do window manipulation in Silverlight. Once you
start doing multi-monitor window manipulation, you probably have a
good idea of what you want to do with it. I'll leave it up to you
to take this code and run with it to suit your specific application
needs.</p>
]]></description></item><item><title>The Commodore 64 Emulator: Emulating Pointers in a sandbox when the real thing is not allowed</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/02/06/the-commodore-64-emulator-emulating-pointers-in-a-sandbox-when-the-real-thing-is-not-allowed</link><pubDate>Tue, 07 Feb 2012 00:02:46 GMT</pubDate><guid>http://10rem.net/blog/2012/02/06/the-commodore-64-emulator-emulating-pointers-in-a-sandbox-when-the-real-thing-is-not-allowed</guid><description><![CDATA[ 
<p>Late last week, I cracked open the <a
href="http://silverlightc64.codeplex.com/">Commodore 64 emulator
code</a> once again, in preparation to post it. However, I had to
have a change made to the source control on CodePlex, so I had a
few days to make some changes. So far, it's shaping up quite
nicely:</p>

<p><a
href="http://10rem.net/media/83308/Windows-Live-Writer_1244081fb4e8_EF48_image_16.png"
 target="_blank"><img src="http://10rem.net/media/83313/Windows-Live-Writer_1244081fb4e8_EF48_image_thumb_7.png" width="320" height="202" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a><a
href="http://10rem.net/media/83318/Windows-Live-Writer_1244081fb4e8_EF48_image_18.png"
 target="_blank"><img src="http://10rem.net/media/83323/Windows-Live-Writer_1244081fb4e8_EF48_image_thumb_8.png" width="320" height="202" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>I went back to the latest version of the <a
href="http://www.cebix.net/viewcvs/cebix/Frodo4/Src/">Frodo C64
emulator source code</a> and decided to port some of their changes
over to this version. Frodo is written in C and C++, and makes very
heavy use of pointers (and not always safe use of them, as there
was at least one logical overrun). In the previous version, I had
replaced pointers with array manipulation, but I did it in a way
that resulted in an awful lot of array copies floating around. The
arrays were small, so this wasn't a big deal memory-wise, but the
copies all took time in an otherwise time-critical application.</p>

<p>Silverlight doesn't support pointers or unsafe code. Of course,
in elevated trust mode, with a not-really-supported hack, you can
have pointers in Silverlight. However, I wanted to stay away from
that for now as it only works in Silverlight 5, only on Windows,
and won't port to any other sandboxed XAML platforms.</p>

<p>So, I decided to finish what I started and build out some decent
almost-pointerish safe analogs in Silverlight. It was a fairly
large amount of effort, but I thought it might also be interesting
to read about here.</p>

<h3>How Pointers Work</h3>

<p>If you've never written any C/C++ code, there's a better than
zero chance that you haven't done any explicit pointer manipulation
in your own code. That's not a bad thing, really, as the typical
business application (and many other types) simply doesn't need to
do pointer arithmetic. It's not worth the inherent danger for the
small performance increase. That said, <strong>an understanding of
how pointers work is&nbsp; fundamental computer science, and is
important for all developers to know.</strong></p>

<p>It's only when you have to do a lot of memory walking in a
performance-critical application that you run into this. <a
href="http://10rem.net/blog/2012/01/15/gnu-cplusplus-blinkenled-part-1-on-the-avr-atmega1284p-with-mikroelektronika-easyavr6-and-atmel-avr-studio-51">
Programming for microcontrollers like the AVR</a> is a great way to
refresh your memory as to how pointers work and what they bring to
the table.</p>

<p>A pointer is an address in memory and an associated type size.
For example, if we have some fictional 6 byte memory chunk and
declare a pointer to a byte, we end up with something like this
(bonus points if you can figure out the significance of the 5 bytes
starting at 0x01):</p>

<p><a
href="http://10rem.net/media/83328/Windows-Live-Writer_1244081fb4e8_EF48_image_8.png"
 target="_blank"><img src="http://10rem.net/media/83333/Windows-Live-Writer_1244081fb4e8_EF48_image_thumb_3.png" width="650" height="204" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>In this case, our byte pointer points to the 8 bits starting at
the address 0x01. You can then manipulate memory using pointer
arithmetic:</p>

<pre class="brush: cpp;">
byte* p = 0x01;    // declare pointer to memory address 0x01<br />
<br />
*p = 0x30;         // changes value at 0x01 to 0x30 from 0x78<br />
<br />
*(p+3) = 0x00;     // changes value at 0x04 to 0x00 from 0x7A<br />
<br />
while (p &lt; 0x06)   // clear rest of memory<br />
  *p++ = 0x00;
</pre>

<p>This is very fast because there really is no indirection. You're
telling the compiler exactly what address to manipulate - it
doesn't have to look anything up.</p>

<p>The size of the pointer variable has to do with the architecture
of the system and its addressing scheme (8 bit, 16 bit, 32 bit, 64
bit), as well as compiler options you select. (In the case of the
Commodore 64, it's all 8 bit.).</p>

<p>You're not limited to the smallest memory unit size, though. If
you wanted to declare a pointer to a 16 bit integer, you'd get this
(assuming "short" is 16 bits on your system):</p>

<p><a
href="http://10rem.net/media/83338/Windows-Live-Writer_1244081fb4e8_EF48_image_10.png"
 target="_blank"><img src="http://10rem.net/media/83343/Windows-Live-Writer_1244081fb4e8_EF48_image_thumb_4.png" width="650" height="204" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>Now, depending on the <a
href="http://en.wikipedia.org/wiki/Endian">endian-ness</a> of your
system, the resulting 16 bit number may be 0x7879 (big endian) or
0x7978 (little endian).</p>

<p>It starts to get really powerful when you consider that a
pointer to a structure could also be considered a pointer to a
number of bytes. That allows you to, for example, read a bunch of
bytes from a disk, look at the first couple bytes to figure out
what you have, and then cast the remaining X bytes as the pointer a
directory structure or something. The original C++ C64 emulator
code does a ton of that.</p>

<h4>How pointers are used in Frodo</h4>

<p>In addition to pointers to structures in byte buffers, frodo
does a lot of string parsing using pointers. In particular, the
1541 drive emulation code uses this for command parsing. In that
code, the first character is often some command identifier, the
next is a delimiter (like a colon) and then some number of
comma-separated values.</p>

<p>In our normal pointer-less code, we'd typically parse the string
and then make copies for each of the individual components. Another
way to deal with it is to simply provide pointers to each of the
sections therefore avoiding making copies of memory. That's
typically how the Frodo code works.</p>

<p>In my first version of the code, I used array indexes to
simulate this. However, that code got incredibly nasty to work
with. I needed another solution.</p>

<h3>The Simulated Pointer</h3>

<p>You can simulate pointers by simply passing around arrays,
making copies, or even using array indexes. But, as I mentioned,
that code tends to get pretty messy as you have lots of dependent
variables. Instead, I needed a way to encapsulate all of this and
provide pointer-like functionality to handle the majority of the
cases.</p>

<ul>
<li>The primary goal of this effort is to make it easy to have code
which is close to 1:1 with its C++ counterparts. For example, if
the C++ code increments a pointer and then assigns a value, I want
to be able to do something similar without having to worry about
which array the pointer points to, or what index value is. The code
won't be 1:1, but I want it as close as possible.</li>

<li>Another goal of this effort is to minimize the number of times
I copy arrays around. Primarily this is for performance reasons as
the emulator code needs to loop at least one million times a second
(1MHz). Minimizing array copies and object instances helps keep GC
under control as well.</li>

<li>A non-goal of this effort is efficient use of actual memory. In
fact, my pointer structures use more memory than a pointer just to
simulate a pointer. I'm ok with that.</li>

<li>Another non-goal is the ability to cast a pointer to a
structure or other complex type. I'd love to do that, but that's
not sandbox-friendly and it's not going to happen that way in this
code.</li>
</ul>

<p>The C64 code has a number of places where it has memory
allocated in chunks. The most obvious is the main memory of the
system (64K), but there's also 2K in the VIC-1541 drive. Beyond
those, there are several chunks of ROM code which get loaded up and
then mapped into various address locations (cartridges too). In the
emulator code, these are just large arrays of bytes.</p>

<p>If you ever had to simulate an operating system in college,
you've done this before.</p>

<p>Here's an example of two pointers "A" and "B". Pointer A points
to address 0x01 in the memory array. Pointer B points to address
0x05.</p>

<p><a
href="http://10rem.net/media/83348/Windows-Live-Writer_1244081fb4e8_EF48_image_14.png"
 target="_blank"><img src="http://10rem.net/media/83353/Windows-Live-Writer_1244081fb4e8_EF48_image_thumb_6.png" width="650" height="272" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>The code to create these looks something like this:</p>

<pre class="brush: csharp;">
SystemRam ram = new SystemRam();<br />
<br />
var a = new RamBytePointer(ram, 0x00);<br />
var b = new RamBytePointer(ram, 0x05);<br />
</pre>

<p>The RamBytePointer structure represents the pointer. It has a
member Value which can be used to get/set the value at that
position. It also has a number of other helper methods to do things
like copy values from arrays, comparisons with other pointers, etc.
Note that the pointer structure takes a reference to the memory it
is allowed to manipulate. A real pointer has pretty much free run
of memory, so you need to keep the RAM pretty broadly defined if
you need that flexibility.</p>

<p>Here's the current version of the structure. It doesn't do quite
everything I want yet (for example, nothing with comparisons
between pointers, for example), but it does a fair bit.</p>

<pre class="brush: csharp;">
using System.Diagnostics;<br />
using System.Text;<br />
using System;<br />
<br />
namespace PeteBrown.C64.Core.Memory<br />
{<br />
    public struct RamBytePointer<br />
    {<br />
        public RamBytePointer(RamBase memory, int address)<br />
            : this(memory)<br />
        {<br />
            _address = address;<br />
        }<br />
<br />
        public RamBytePointer(RamBase memory)<br />
        {<br />
            _memory = memory;<br />
            _address = 0;<br />
        }<br />
<br />
<br />
        private RamBase _memory;<br />
        private RamBase Memory<br />
        {<br />
            [DebuggerStepThrough]<br />
            get { return _memory; }<br />
            [DebuggerStepThrough]<br />
            set { _memory = value; }<br />
        }<br />
<br />
        private int _address;<br />
        public int Address<br />
        {<br />
            [DebuggerStepThrough]<br />
            get { return _address; }<br />
            [DebuggerStepThrough]<br />
            set { _address = value; }<br />
        }<br />
<br />
        public byte this[int offset]<br />
        {<br />
            [DebuggerStepThrough]<br />
            get { return _memory[_address + offset]; }<br />
            [DebuggerStepThrough]<br />
            set { _memory[_address + offset] = value; }<br />
        }<br />
<br />
        public byte Value<br />
        {<br />
            [DebuggerStepThrough]<br />
            get { return _memory[_address]; }<br />
            [DebuggerStepThrough]<br />
            set { _memory[_address] = value; }<br />
        }<br />
<br />
        public byte[] GetValues(int length)<br />
        {<br />
            return _memory.Read(_address, length);<br />
        }<br />
<br />
        public void SetValues(byte[] values)<br />
        {<br />
            _memory.Write(_address, values);<br />
        }<br />
<br />
<br />
        public void CopyFrom(byte[] values, bool incrementPointer)<br />
        {<br />
            for (int i = 0; i &lt; values.Length; i++)<br />
            {<br />
                _memory[_address + i] = values[i];<br />
            }<br />
<br />
            if (incrementPointer)<br />
                _address += values.Length;<br />
        }<br />
<br />
        public void CopyFrom(char[] characters, bool incrementPointer)<br />
        {<br />
            for (int i = 0; i &lt; characters.Length; i++)<br />
            {<br />
                _memory[_address + i] = (byte)characters[i];<br />
            }<br />
<br />
            if (incrementPointer)<br />
                _address += characters.Length;<br />
        }<br />
<br />
        public void CopyFrom(string characters, bool incrementPointer)<br />
        {<br />
            for (int i = 0; i &lt; characters.Length; i++)<br />
            {<br />
                _memory[_address + i] = (byte)characters[i];<br />
            }<br />
<br />
            if (incrementPointer)<br />
                _address += characters.Length;<br />
        }<br />
<br />
        public RamBytePointer NewPointerAtOffset(int offset)<br />
        {<br />
            return new RamBytePointer(_memory, _address + offset);<br />
        }<br />
<br />
<br />
        public static RamBytePointer operator +(RamBytePointer p, int offset)<br />
        {<br />
            return new RamBytePointer(p.Memory, p.Address + offset);<br />
        }<br />
<br />
<br />
        public static RamBytePointer operator -(RamBytePointer p, int offset)<br />
        {<br />
            return new RamBytePointer(p.Memory, p.Address - offset);<br />
        }<br />
<br />
<br />
        public static RamBytePointer operator ++(RamBytePointer p)<br />
        {<br />
            p.Address += 1;<br />
<br />
            return p;<br />
        }<br />
<br />
        public static RamBytePointer operator --(RamBytePointer p)<br />
        {<br />
            p.Address -= 1;<br />
<br />
            return p;<br />
        }<br />
<br />
<br />
        public int IndexOf(byte value, int count)<br />
        {<br />
            return _memory.IndexOf(value, 0, count);<br />
        }<br />
<br />
        public int IndexOf(char value, int count)<br />
        {<br />
            return _memory.IndexOf(value, 0, count);<br />
        }<br />
<br />
        public bool Contains(char value, int count)<br />
        {<br />
            return _memory.Contains(value, 0, count);<br />
        }<br />
<br />
        public bool Contains(byte value, int count)<br />
        {<br />
            return _memory.Contains(value, 0, count);<br />
        }<br />
<br />
<br />
        public string ToString(int startIndex, int length)<br />
        {<br />
            StringBuilder builder = new StringBuilder();<br />
<br />
            for (int i = startIndex; i &lt; length; i++)<br />
            {<br />
                builder.Append((char)_memory[i]);<br />
            }<br />
<br />
            return builder.ToString();<br />
        }<br />
<br />
    }<br />
}<br />
</pre>

<p>The memory array itself is always created and maintained outside
of this class. It must be valid when the pointer is created.</p>

<h4>Operator overloading and Offsets</h4>

<p>Of interest is the operator overloading. This allows me to do
things like p++ or p += 1 in order to modify the address that the
pointer is pointing to. That's an important part of keeping the C#
code as similar as possible to the C++ code. However, it doesn't
allow everything the C++ code allows. For example, I can't do the
exact equivalent of this code:</p>

<pre class="brush: cpp;">
*(p + 5) = 0x05;<br />
*(p - 7) = 0x0A;
</pre>

<p>If I try to do the equivalent of that, the compiler will barf at
me as it needs an actual LValue on the left side. Instead, code
like that must use something like this:</p>

<pre class="brush: cpp;">
p[5] = 0x05;<br />
p[-7] = 0x0A;
</pre>

<p>The code is similar enough that I'm happy with it, although
developers new to the code may raise a few eyebrows at the p[-7]
version.</p>

<h4>Converting Strings</h4>

<p>Because much of the C++ code treats characters and bytes as
interchangeable (something you can't really do with arrays in C# on
Windows), I also have a few overloads that can take characters or
bytes. This helps clean up the consuming code so it doesn't have so
many casts.</p>

<p>I have helper functions in there to copy from strings. This
helps me easily translate code such as this:</p>

<pre class="brush: cpp;">
*p++ = 'B';<br />
*p++ = 'L';<br />
*p++ = 'O';<br />
*p++ = 'C';<br />
*p++ = 'K';<br />
*p++ = 'S';<br />
*p++ = ' ';<br />
*p++ = 'F';<br />
*p++ = 'R';<br />
*p++ = 'E';<br />
*p++ = 'E';<br />
*p++ = '.';
</pre>

<p>Into a nice single-liner like p.CopyFrom("BLOCKS FREE.",
true);</p>

<h4>A Structure, not a Class</h4>

<p>Note that this is a structure, not a class. Why? Having it as a
structure lets me make copies easily. It's common practice in C/C++
code to have a pointer passed into a function, and then make a copy
of it to increment yourself. For example:</p>

<pre class="brush: cpp;">
void DoSomething (byte * baseAddress)<br />
{<br />
    byte * p = baseAddress;<br />
<br />
    while (p++ != 0x0A)<br />
        ...<br />
}
</pre>

<p>In this example C++ function, p starts off at the same address
as "baseAddress", but then increments it. The value for baseAddress
must be left alone.</p>

<p>Reference types like class in C# are themselves pointers. So,
due to the level of indirection this has, we'd end up modifying the
original value:</p>

<pre class="brush: csharp;">
class RamBytePointer { ... }<br />
<br />
void DoSomething (RamBytePointer baseAddress)<br />
{<br />
    RamBytePointer p = baseAddress;<br />
<br />
    p += 5;<br />
<br />
    Debug.WriteLine(p.Address);<br />
    Debug.WriteLine(baseAddress.Address);<br />
}<br />
<br />
// ---------------------------------------<br />
<br />
struct RamBytePointer { ... }<br />
<br />
void DoSomething (RamBytePointer baseAddress)<br />
{<br />
    RamBytePointer p = baseAddress;<br />
<br />
    p += 5;<br />
<br />
    Debug.WriteLine(p.Address);<br />
    Debug.WriteLine(baseAddress.Address);<br />
}
</pre>

<p>The first example doesn't work like pointers in C++ at all.
Incrementing p also increments baseAddress. The second example,
however, works as we would expect because p is a copy of
baseAddress, not a reference to it.</p>

<p>The downside of using a struct is there's no inheritance. So, I
instead put a fair bit of the potentially reusable code into the
memory classes instead, and simply call that from the pointer
class.</p>

<h3>Summary</h3>

<p>Simulating pointers in pointer-free sandboxed platforms is a bit
unorthodox, but can make translating code easier.</p>

<p>This isn't something you're likely to need to do in your own
code, but it an interesting exercise in any case. There's no
downloadable source code yet, as I'm still refining this
implementation. You'll be able to get a version of these classes in
the <a href="http://silverlightc64.codeplex.com/">SilverlightC64
code</a> when I post it in the next week or less. It's taking
longer to swap out all this code than I had intended :)</p>

<p><strong>If you've ever had to do anything like this in your own
code, I'd love to hear about it.</strong></p>
]]></description></item><item><title>Windows Client Developer Roundup 086 for 1/11/2012</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/01/11/windows-client-developer-roundup-086-for-1-11-2012</link><pubDate>Thu, 12 Jan 2012 01:02:35 GMT</pubDate><guid>http://10rem.net/blog/2012/01/11/windows-client-developer-roundup-086-for-1-11-2012</guid><description><![CDATA[ 
<p>The Windows Client Developer Roundup aggregates information of
interest to Windows Client Developers, including <a
href="http://dev.windows.com/">WinRT XAML</a>, <a
href="http://windowsclient.net/">WPF</a>, <a
href="http://silverlight.net/">Silverlight</a>, <a
href="http://msdn.microsoft.com/en-us/visualc/default.aspx">Visual
C++</a>, <a href="http://creators.xna.com/">XNA</a>, <a
href="http://expression.microsoft.com/">Expression Blend</a>, <a
href="http://www.microsoft.com/surface/">Surface</a>, <a
href="http://msdn.microsoft.com/en-us/windows/default.aspx">Windows
7</a>, <a
href="http://msdn.microsoft.com/en-us/ff380145.aspx">Windows
Phone</a>, Visual Studio, <a
href="http://silverlight.net/riaservices/">WCF RIA Services</a> and
more. Sometimes I even include a little jQuery and HTML5. If you
have something interesting you've done or have run across, or you
blog regularly on the topics included here, please send me the URL
and brief description via the <a href="http://10rem.net/contact">contact
link</a>.</p>

<p>Note that I've started breaking the Netduino, Electronics,
Robotics, Synthesizer and similar content into a new roundup series
called the <a href="http://10rem.net/blog?filterby=MakerRoundup">Maker Geek
Roundup</a>.</p>

<h3>Shout-Outs</h3>

<ul>
<li><a
href="http://blogs.msdn.com/b/visualstudio/archive/2012/01/04/give-us-your-feedback-on-visual-studio-11-and-receive-a-gift.aspx">
Give us your feedback on Visual Studio 11 etc. and receive a
gift!</a> (Visual Studio Blog)</li>
</ul>

<h3>Windows 8 and WinRT/Metro General</h3>

<ul>
<li><a
href="http://blogs.msdn.com/b/davedev/archive/2012/01/05/windows-8-first-apps-contest.aspx">
Windows 8 - First Apps Contest</a> (Dave Isbitski)</li>

<li><a
href="http://kellabyte.com/2011/12/19/when-metro-design-falls-off-the-tracks/">
When Metro design falls off the tracks</a> (Kelly Sommers)</li>

<li><a
href="http://www.sharpgis.net/post/2011/12/11/Make-your-Windows-8-Video-App-use-the-PlayTo-feature.aspx">
SharpGIS | Make your Windows 8 Video App use the PlayTo feature</a>
(Morten Nielsen)</li>
</ul>

<h3>XAML Technologies (Silverlight, WPF, WinRT Metro XAML)</h3>

<ul>
<li><a
href="http://www.andybeaulieu.com/Home/tabid/67/EntryID/223/Default.aspx">
"Physamajig" for Windows 8</a> (Andy Beaulieu)</li>

<li><a
href="http://www.sharpgis.net/post/2011/12/07/Building-an-Augmented-Reality-XAML-control.aspx">
Building an Augmented Reality XAML control</a> (Morten
Nielsen)</li>
</ul>

<h3>WinJS / JavaScript and HTML Applications for Windows Metro</h3>

<ul>
<li><a
href="http://adamkinney.com/blog/2011/12/07/setting-up-your-first-use-of-the-animation-library-in-winjs/">
Setting up your first use of the Animation library in WinJS</a>
(Adam Kinney)</li>

<li><a
href="http://adamkinney.com/blog/2011/12/05/no-alert-in-winjs-use-console-or-messagedialog-instead/">
No Alert in WinJS! Use console or MessageDialog instead</a> (Adam
Kinney)</li>
</ul>

<h3>Direct X Technologies (DirectX, XNA, WinRT DirectX, General GPU
and Game Programming)</h3>

<ul>
<li><a
href="http://geekswithblogs.net/mikebmcl/archive/2011/12/31/getting-started-with-metro-style-directx.aspx">
Getting started with Metro style DirectX</a> (Bob Taco
Industries)</li>

<li><a
href="http://digitalerr0r.wordpress.com/2011/12/12/xna-4-0-shader-programming-1intro-to-hlsl-ambient-light/">
XNA 4.0 Shader Programming #1-Intro to HLSL, Ambient light</a>
(digitalerr0r)</li>

<li><a
href="http://digitalerr0r.wordpress.com/2011/12/13/xna-4-0-shader-programming-2diffuse-light/">
XNA 4.0 Shader Programming #2-Diffuse light</a> (digitalerr0r)</li>

<li><a
href="http://digitalerr0r.wordpress.com/2011/12/20/xna-4-0-shader-programming-3specular-light/">
XNA 4.0 Shader Programming #3-Specular light</a>
(digitalerr0r)</li>
</ul>

<h3>C++ and Native Development</h3>

<ul>
<li><a
href="http://blogs.msdn.com/b/sdl/archive/2011/12/02/security.aspx">
Compiler Security Enhancements in Visual Studio 11</a> (SDL
Team)</li>
</ul>

<h3>Visual Studio and .NET General</h3>

<ul>
<li><a
href="http://blogs.msdn.com/b/somasegar/archive/2011/12/15/visual-studio-11-platform-tooling-advances.aspx">
Visual Studio 11 Platform Tooling Advances</a> (Soma)</li>

<li style="list-style: none">
<ul>
<li>Good DirectX content in this one as well</li>
</ul>
</li>

<li><a
href="http://blogs.msdn.com/b/delay/archive/2012/01/09/make-things-as-simple-as-possible-but-not-simpler-managedmsiexec-sample-app-shows-how-to-use-the-windows-installer-api-from-managed-code.aspx">
ManagedMsiExec sample app shows how to use the Windows Installer
API from managed code</a> (David Anson)</li>
</ul>

<h3>NUI (Kinect, Surface, More)</h3>

<ul>
<li><a
href="http://kinecthacks.net/microsoft-kinect-coming-to-windows-on-february-1st-up-for-pre-order-now/">
Microsoft Kinect coming to Windows on February 1st, up for
pre-order now!</a> (KinectHacks)</li>

<li><a
href="http://robrelyea.wordpress.com/2012/01/11/kinect-apps-ensuring-kinect-runtime-is-installed/">
Kinect Apps - ensuring Kinect Runtime is installed</a> (Rob
Relyea)</li>

<li><a
href="http://robrelyea.wordpress.com/2011/12/17/depth-api-improvements-in-v1/">
Examples of depth API improvements coming in v1</a> (Rob
Relyea)</li>

<li><a
href="http://channel9.msdn.com/coding4fun/kinect/Kinect--3D--Fusion4D">
Kinect + 3D = Fusion4D</a> (Greg Duncan)</li>

<li><a
href="http://channel9.msdn.com/coding4fun/blog/Connecting-your-Netduino-to-your-Kinect">
Connecting your Netduino to your Kinect</a> (Greg Duncan)</li>

<li><a
href="http://digitalerr0r.wordpress.com/2011/12/13/kinect-fundamentals-4-implementing-skeletal-tracking/">
Kinect Fundamentals #4: Implementing Skeletal Tracking |
digitalerr0r</a> (digitalerr0r)</li>

<li><a
href="http://studentguru.gr/b/vangos/archive/2012/01/01/kinect-amp-html5-using-websockets-and-canvas.aspx">
Kinect &amp; HTML5 using WebSockets and Canvas</a> (Vangos
Pterneas)</li>
</ul>

<h3>Off-Topic Fun</h3>

<ul>
<li><a
href="http://poorlydrawnlines.com/comic/when-its-cold/">Poorly
Drawn Lines - When It's Cold</a> (for all the ADD types)</li>

<li><a href="http://xkcd.com/1002/">xkcd: Game AIs</a> (xkcd)</li>

<li><a
href="http://www.smbc-comics.com/index.php?db=comics&amp;id=2470&amp;">
Benoit Mandelbrot: Master of seduction</a> (SMBC)</li>

<li style="list-style: none">
<ul>
<li>and <a
href="http://www.smbc-comics.com/index.php?db=comics&amp;id=2471&amp;">
Saturday Morning Breakfast Cereal</a>&nbsp;</li>

<li>and <a
href="http://www.smbc-comics.com/index.php?db=comics&amp;id=2475&amp;">
Saturday Morning Breakfast Cereal</a>&nbsp;</li>
</ul>
</li>

<li><a
href="http://www.smbc-comics.com/index.php?db=comics&amp;id=2478">Grammar!</a>
(SMBC)</li>

<li><a
href="http://moistproduction.blogspot.com/2011/12/lego-skeleton-cross-section-for-purists.html">
Lego Skeleton inside Mini Figure (for the purists)</a>
(MoistProduction)</li>
</ul>
]]></description></item><item><title>Threading Considerations for Binding and Change Notification in Silverlight 5</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5</link><pubDate>Tue, 10 Jan 2012 16:48:00 GMT</pubDate><guid>http://10rem.net/blog/2012/01/10/threading-considerations-for-binding-and-change-notification-in-silverlight-5</guid><description><![CDATA[ 
<p>A reader of <a href="http://manning.com/pbrown2"
target="_blank">my Silverlight 5 book</a> recently reached out to
me about threading and why I create some objects on the UI thread
in the examples. We discussed some of the reasons, but I felt this
would be a good topic to share with everyone. In fact, this is one
area where it would have been fun to go into great detail in my
book, but there simply wasn't the space. Threading and cross-thread
exceptions can be a bit of a mystery to new Silverlight and WPF
developers.</p>

<h3>Background</h3>

<p>The user interface in Silverlight runs on a thread commonly
known as the UI Thread. Any code you create in the code-behind, and
any code it calls all the way down the chain, unless it explicitly
creates another thread, runs on this same UI thread. It's not at
all uncommon to see Silverlight and WPF applications which never
explicitly create a second thread, but do make calls to other
services which create background threads for processing.</p>

<p>There are many other examples, but networking is one place where
the Silverlight .NET Framework explicitly creates (or uses)
different threads. Not all calls return on the UI thread.</p>

<p><strong>Threads other than the UI thread are not allowed to
access or manipulate UI objects</strong>. If they attempt to do so,
the runtime throws an Invalid Cross-Thread Access exception. It
looks like this:</p>

<p><a
href="http://10rem.net/media/82267/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_2.png"
 target="_blank"><img src="http://10rem.net/media/82272/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_thumb.png" width="477" height="277" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>But wait! I wasn't accessing any UI objects from my code. What
gives?</p>

<p>It's not always obvious that you're interacting with UI objects
on the UI thread, though. Here's the stack trace from this
particular exception:</p>

<pre class="brush: csharp; highlight: [2];">
{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---&gt;<br />
  System.UnauthorizedAccessException: Invalid cross-thread access.<br />
   at MS.Internal.XcpImports.CheckThread()<br />
   at MS.Internal.XcpImports.GetValue(IManagedPeerBase managedPeer, DependencyProperty property)<br />
   at System.Windows.DependencyObject.GetOldValue(DependencyProperty property, EffectiveValueEntry&amp; oldEntry)<br />
   at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry&amp; newEntry, ValueOperation operation)<br />
   at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)<br />
   at System.Windows.Data.BindingExpression.SendDataToTarget()<br />
   at System.Windows.Data.BindingExpression.SourcePropertyChanged(PropertyPathListener sender, PropertyPathChangedEventArgs args)<br />
   at System.Windows.PropertyPathListener.ReconnectPath()<br />
   at System.Windows.Data.Debugging.BindingBreakPoint.&lt;&gt;c__DisplayClass4.&lt;BreakOnSharedType&gt;b__3()<br />
   --- End of inner exception stack trace ---<br />
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)<br />
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)<br />
   at System.Delegate.DynamicInvokeImpl(Object[] args)<br />
   at System.Delegate.DynamicInvoke(Object[] args)<br />
   at MainPagexaml.BindingOperation(Object BindingState, Int32 , Action )}
</pre>

<p>This stack trace was generated by <strong>trying to raise a
PropertyChangedNotification when I manipulated a model object from
a background thread</strong>. So, it was obvious that I was working
with an object on the background thread, but it wasn't obvious that
I'd get a cross-thread exception (well it was in this case, as I
contrived the example). If you consider a larger application where
you have division of ownership for different pieces, a client-side
developer may simply work with your viewmodel, but not realize
you're farming some work out to another thread.</p>

<p>I wrote a blog post back in 2010 ( <a
href="http://10rem.net/blog/2010/04/23/essential-silverlight-and-wpf-skills-the-ui-thread-dispatchers-background-workers-and-async-network-programming">
Essential Silverlight and WPF Skills: The UI Thread, Dispatchers,
Background Workers and Async Network Programming</a>) explaining
some of the ways to work with threads and dispatching. I didn't
have SynchronizationContext in there at the time, but it's
something I tend to use a lot these days.</p>

<p>Let's take a look at a few of the common scenarios and how it
works with threading.</p>

<h3>Common Scenarios</h3>

<p>All of these scenarios make use of a simple Customer class with
a single property:</p>

<pre class="brush: csharp;">
namespace SilverlightThreadingExample.Model<br />
{<br />
    public class Customer : Observable<br />
    {<br />
        private string _firstName;<br />
        public string FirstName<br />
        {<br />
            get { return _firstName; }<br />
            set { _firstName = value; NotifyPropertyChanged("FirstName"); }<br />
        }<br />
    }<br />
}
</pre>

<p>The customer is <em>observable</em> that is, it notifies any
listeners when properties change. While not necessary, I
encapsulated the observable code in this base class. You could,
instead, put the implementation in a partial class if you wanted to
make sure your model object's signature from your ORM or whatever
remains the same as it was on the server.</p>

<pre class="brush: csharp;">
using System.ComponentModel;<br />
<br />
namespace SilverlightThreadingExample<br />
{<br />
    public class Observable : INotifyPropertyChanged<br />
    {<br />
        public event PropertyChangedEventHandler PropertyChanged;<br />
<br />
        protected void NotifyPropertyChanged(string propertyName)<br />
        {<br />
            if (PropertyChanged != null)<br />
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
        }<br />
    }<br />
}
</pre>

<p>This is actually a pretty typical approach to handling
INotifyPropertyChanged. There are even more robust versions out
there which use lambdas and reflection to help avoid passing in
strings, but they ultimately come down to raising the
PropertyChanged event. Many of them also fail to work properly in
cross-thread situations.</p>

<p>I expose the Customer class and a collection of customers from a
ViewModel class.</p>

<pre class="brush: csharp;">
namespace SilverlightThreadingExample.ViewModel<br />
{<br />
    public class CustomerEntryViewModel : Observable<br />
    {<br />
        private Customer _currentCustomer;<br />
        public Customer CurrentCustomer<br />
        {<br />
            get { return _currentCustomer; }<br />
            set { _currentCustomer = value; NotifyPropertyChanged("CurrentCustomer"); }<br />
        }<br />
<br />
        private ObservableCollection&lt;Customer&gt; _customers = new ObservableCollection&lt;Customer&gt;();<br />
        public ObservableCollection&lt;Customer&gt; Customers<br />
        {<br />
            get { return _customers; }<br />
        }<br />
<br />
        public void LoadCustomersOnSameThread()<br />
        {<br />
            LoadDummyData();<br />
        }<br />
<br />
        private void LoadDummyData()<br />
        {<br />
            _customers.Add(new Customer() { FirstName = "Pete" });<br />
            _customers.Add(new Customer() { FirstName = "Jon" });<br />
            _customers.Add(new Customer() { FirstName = "Tim" });<br />
            _customers.Add(new Customer() { FirstName = "Scott" });<br />
            _customers.Add(new Customer() { FirstName = "Andy" });<br />
            _customers.Add(new Customer() { FirstName = "Blaine" });<br />
            _customers.Add(new Customer() { FirstName = "Jesse" });<br />
            _customers.Add(new Customer() { FirstName = "Rey" });<br />
<br />
            _currentCustomer = _customers[0];<br />
        }<br />
<br />
    }<br />
}
</pre>

<p>Finally, the UI is bound to those classes. The DataContext for
the UI (which will be set in code-behind) is the ViewModel.</p>

<pre class="brush: xml;">
&lt;UserControl x:Class="SilverlightThreadingExample.MainPage"<br />
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"<br />
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"<br />
    mc:Ignorable="d"<br />
    d:DesignHeight="400" d:DesignWidth="600"&gt;<br />
<br />
    &lt;Grid x:Name="LayoutRoot" Background="White"&gt;<br />
        &lt;Grid Width="500"&gt;<br />
            &lt;Grid.ColumnDefinitions&gt;<br />
                &lt;ColumnDefinition Width="*" /&gt;<br />
                &lt;ColumnDefinition Width="250" /&gt;<br />
            &lt;/Grid.ColumnDefinitions&gt;<br />
<br />
            &lt;ListBox x:Name="CustomerList"<br />
                     Grid.Column="0" Margin="10"<br />
                     ItemsSource="{Binding Customers}"<br />
                     SelectedItem="{Binding CurrentCustomer, Mode=TwoWay}"&gt;<br />
                &lt;ListBox.ItemTemplate&gt;<br />
                    &lt;DataTemplate&gt;<br />
                        &lt;TextBlock Text="{Binding FirstName}" /&gt;<br />
                    &lt;/DataTemplate&gt;<br />
                &lt;/ListBox.ItemTemplate&gt;<br />
            &lt;/ListBox&gt;<br />
<br />
            &lt;StackPanel Grid.Column="1"&gt;<br />
                &lt;TextBox x:Name="FirstNameField" Margin="10"<br />
                         DataContext="{Binding CurrentCustomer}"<br />
                         Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /&gt;<br />
<br />
                &lt;Button x:Name="AddCustomer"<br />
                        Content="Add Customer from UI Thread"<br />
                        Height="30" Margin="5"<br />
                        Click="AddCustomer_Click" /&gt;<br />
                &lt;Button x:Name="AddCustomerSecond"<br />
                        Content="Add Customer from Second Thread"<br />
                        Height="30" Margin="5"<br />
                        Click="AddCustomerSecond_Click" /&gt;<br />
                &lt;Button x:Name="ChangeNameFromSecondThread"<br />
                        Content="Change Name from Second Thread"<br />
                        Height="30" Margin="5"<br />
                        Click="ChangeNameFromSecondThread_Click" /&gt;<br />
            &lt;/StackPanel&gt;<br />
<br />
        &lt;/Grid&gt;<br />
   <br />
    &lt;/Grid&gt;<br />
&lt;/UserControl&gt;
</pre>

<p>The code-behind looks like this</p>

<pre class="brush: csharp;">
using System.Windows;<br />
using System.Windows.Controls;<br />
using SilverlightThreadingExample.ViewModel;<br />
using System.Threading;<br />
using SilverlightThreadingExample.Model;<br />
<br />
namespace SilverlightThreadingExample<br />
{<br />
    public partial class MainPage : UserControl<br />
    {<br />
        CustomerEntryViewModel _vm;<br />
<br />
        public MainPage()<br />
        {<br />
            InitializeComponent();<br />
<br />
            CreateViewModelOnUIThread();<br />
        }<br />
<br />
<br />
        private void CreateViewModelOnUIThread()<br />
        {<br />
            _vm = new CustomerEntryViewModel();<br />
<br />
            _vm.LoadCustomersOnSameThread();<br />
<br />
            DataContext = _vm;<br />
        }<br />
<br />
<br />
        private void AddCustomer_Click(object sender, RoutedEventArgs e)<br />
        {<br />
        }<br />
<br />
<br />
        private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
        {<br />
        }<br />
<br />
<br />
        private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
        {<br />
        }<br />
<br />
<br />
    }<br />
}<br />
</pre>

<p>The methods are named to keep the context clear in this example.
I wouldn't expect you to name your VM instantiation/locator method
"CreateViewModelOnUIThread", for example.</p>

<p>Now let's look at those scenarios.</p>

<h4>Changing a property value from a background thread</h4>

<p>Often in an application, you have a class which is used in UI
binding (an entity/model object) but still need to modify a
property from code. Sometimes, you need to do that from a
background thread. For example, you make a network call to get an
updated price for an item. You will get a cross-thread access error
when the class raises change notification events from that property
setter. If the class is truly POCO (Plan Old CLR Object) and
doesn't do any change notification or other event raising, you'll
be fine. If, however, change notification is involved, you'll get
the cross-thread exception.</p>

<p><img src="http://10rem.net/media/82277/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_13.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>Assuming the same Customer and Observable classes defined above,
and the same XAML UI, the following code in the code-behind will
throw that exception.</p>

<pre class="brush: csharp;">
private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
        {<br />
            _vm.CurrentCustomer.FirstName = "UpdatedFromSecondThread";<br />
        });<br />
<br />
    t.Start();<br />
}
</pre>

<p>The exception doesn't happen when you set the property value;
that's perfectly acceptable. It happens here, at the highlighted
line:</p>

<pre class="brush: csharp; highlight: [4];">
protected void NotifyPropertyChanged(string propertyName)<br />
{<br />
    if (PropertyChanged != null)<br />
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
}
</pre>

<p>So, what are the options for working around this? Let's consider
two common approaches.</p>

<h5>Approach 1</h5>

<p>The first approach is to do the whole property change from the
UI thread. To do this, simply wrap the property set code with a
call to the dispatcher. You can use either the Dispatcher object,
or if you keep a copy of the SynchronizationContext around, use
that.</p>

<p><img src="http://10rem.net/media/82282/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_22.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>Here's some example code which implements this. The code looks a
bit silly because I'm forcing a background thread. However, pretend
that the background thread is a given and you need to work from it
(again, the callback from a network call or something.)</p>

<pre class="brush: csharp;">
private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
    {<br />
        Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<br />
            {<br />
                _vm.CurrentCustomer.FirstName = "UpdatedFromSecondThread";<br />
            });<br />
    });<br />
<br />
    t.Start();<br />
}
</pre>

<p>This approach works well, but requires the calling code to
handle all the dispatching. If you have a number of properties to
change in different bits of code, it gets a bit cumbersome. Let's
look at another approach.</p>

<h5>Approach 2</h5>

<p>The real problem is the property change notification, so the the
second approach is to dispatch just the change notification to the
UI thread.</p>

<p><a
href="http://10rem.net/media/82287/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_24.png"
 target="_blank"><img src="http://10rem.net/media/82292/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_thumb_8.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>You can put this code into the Observable base class in order to
avoid repeating it throughout all your classes.</p>

<pre class="brush: csharp;">
// Code-behind<br />
// ----------------------------------------------<br />
<br />
<br />
// this version throws an exception if the Observable base class isn't doing thread checking<br />
private void ChangeNameFromSecondThread_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
        {<br />
            _vm.CurrentCustomer.FirstName = "UpdatedFromSecondThread";<br />
        });<br />
<br />
    t.Start();<br />
}<br />
<br />
<br />
// Observable<br />
// ----------------------------------------------<br />
<br />
<br />
using System.ComponentModel;<br />
using System.Windows;<br />
<br />
namespace SilverlightThreadingExample<br />
{<br />
    public class Observable : INotifyPropertyChanged<br />
    {<br />
        public event PropertyChangedEventHandler PropertyChanged;<br />
<br />
        protected void NotifyPropertyChanged(string propertyName)<br />
        {<br />
            if (PropertyChanged != null)<br />
            {<br />
                if (Deployment.Current.Dispatcher.CheckAccess())<br />
                {<br />
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
                }<br />
                else<br />
                {<br />
                    Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<br />
                    {<br />
                        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));<br />
                    });<br />
                }<br />
            }<br />
        }<br />
    }<br />
}
</pre>

<p>Note how I first check to see if we have access to the UI thread
using the CheckAccess call. If we do, there's no reason to incur
the overhead and delay of a dispatcher call. However, if we are
running on the background thread, then the call is dispatched to
the UI thread. In either case, we avoid the errors cause by
cross-thread property change notification.</p>

<p>Next up: Collections</p>

<h4>Populating an ObservableCollection from a networking return
call</h4>

<p>A more robust Observable base class like this won't help with
collection change notification (WPF 4.5 has a great solution for
that using BindingOperations.EnableCollectionSynchronization, but
unfortunately Silverlight does not).</p>

<p>Most applications make networking calls to get information from
some resource on an intranet or out on the web. In Silverlight (and
WPF), it's common practice to populate an ObservableCollection with
the results from those calls. The ObservableCollection class is
nice because it implements INotifyCollectionChanged and raises an
event whenever items are added to or deleted from the collection,
or when the collection is cleared. It's this notification that
enables the various items controls and grids in the UI to stay in
sync with the items in the collection.</p>

<p><img src="http://10rem.net/media/82297/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_16.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>This version is very similar to what we saw with individual
properties earlier. That's because, it's really the same problem:
we're trying to notify the binding system across threads.</p>

<pre class="brush: csharp;">
private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
{<br />
    Thread t = new Thread((o) =&gt;<br />
    {<br />
        var cust = new Customer() { FirstName = "AddedFromSecondThread" };<br />
        _vm.Customers.Add(cust);<br />
    });<br />
<br />
    t.Start();<br />
}
</pre>

<p>Note that the problem exists regardless of where you actually
create the customer. For example, this code will also fail:</p>

<pre class="brush: csharp;">
private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
{<br />
    var cust = new Customer() { FirstName = "AddedFromSecondThread" };<br />
<br />
    Thread t = new Thread((o) =&gt;<br />
    {<br />
        _vm.Customers.Add(cust);<br />
    });<br />
<br />
    t.Start();<br />
}
</pre>

<p>The reason is, again, it's not the object access that is causing
the cross-thread exception, it's the collection changed
notification that's full of hate here.</p>

<p>So, how do you get around this? Unless you want to create your
own ObservableCollection type class for Silverlight, you'll need to
dispatch all collection add calls. Luckily, you'll typically have
fewer of these scattered throughout the application, so it's not
quite so onerous.</p>

<p><img src="http://10rem.net/media/82302/Windows-Live-Writer_Threading-Considerations-for-Binding-in-_EF97_image_27.png" width="640" height="261" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></p>

<p>The code to implement this is just another easy call to the
dispatcher (or SynchronizationContext, if you prefer).</p>

<pre class="brush: csharp;">
private void AddCustomerSecond_Click(object sender, RoutedEventArgs e)<br />
{<br />
    // you can create customer on any thread<br />
    var cust = new Customer() { FirstName = "AddedFromSecondThread" };<br />
<br />
    Thread t = new Thread((o) =&gt;<br />
        {<br />
<br />
            // dispatch to UI thread to add it to the collection. You can't<br />
            // access the observable collection x-thread<br />
            Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<br />
                {<br />
                    _vm.Customers.Add(cust);<br />
                });<br />
        });<br />
<br />
    t.Start();<br />
}
</pre>

<p>If you're going to run from an unknown state, be sure to call
CheckAccess to see if you really need to do the dispatching. In
this case, I know I'm always going to be on a background thread, so
I don't bother.</p>

<h3>Summary</h3>

<p>The intent here was to show a few of the common threading
pitfalls in Silverlight (and WPF) applications, specifically in the
context of change notification. In most code, it's easy to tell
when you're accessing objects cross-thread, but change notification
is a somewhat behind the scenes operation, so it's not always
obvious.</p>

<p>For property change notification, the solutions were:</p>

<ul>
<li>Dispatch the entire property change operation to the UI
thread</li>

<li>Update the NotifyPropertyChanged code to check to see which
thread it's running on, and then dispatch the event as
appropriate</li>
</ul>

<p>Either way works, but I prefer the update to the
NotifyPropertyChanged method.</p>

<p>For collection change notifications in Silverlight, the
solutions are:</p>

<ul>
<li>Create (or find) an implementation of ObservableCollection
which does the cross-thread checking. The reason this isn't
built-in is change notification happens often, and dispatching each
and every change notification can be a real performance drain.
That's also why WPF has a separate and optimized solution. You'd
need to enable batching to avoid the overhead of hundreds of
dispatch calls.</li>

<li>Dispatch the entire collection update when you're running on a
background thread.</li>
</ul>

<p>In contrast to the property change notifications, for collection
change, I prefer to dispatch the entire call. If you're adding 1
object or 100, you'll still get only one dispatch call, so
performance is better.</p>

<p>The Task Parallel Library in WPF, and the subset of it in
Silverlight also offer some alternative approaches to handling
cross-thread work. Similarly, the async and await keywords in .NET
4.5 and Windows 8 XAML can also come into play. More on those in
the future.</p>
]]></description></item><item><title>Silverlight Reporting Open Source Printing/Reports Example Updated for Silverlight 5</title><author>Pete Brown	</author><link>http://10rem.net/blog/2012/01/09/silverlight-reporting-open-source-printing-reports-example-updated-for-silverlight-5</link><pubDate>Mon, 09 Jan 2012 20:44:30 GMT</pubDate><guid>http://10rem.net/blog/2012/01/09/silverlight-reporting-open-source-printing-reports-example-updated-for-silverlight-5</guid><description><![CDATA[ 
<p>I recently posted an updated version of Silverlight reporting on
<a href="http://silverlightreporting.codeplex.com/"
target="_blank">codeplex</a>. Here's the overview.</p>

<p><a href="http://silverlightreporting.codeplex.com/"
target="_blank"><img src="http://10rem.net/media/82245/Windows-Live-Writer_Silverlight-Reporting-Open-Source-Printi_EA02_image_5.png" width="490" height="100" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>This project, a unofficial project by Pete Brown of Microsoft,
provides a a very basic framework for building simple, short,
multi-page reports using Silverlight 5.</p>

<p>The intent is not to be an all-encompassing reporting solution,
or a solution for large reports. Instead, this is a set of code you
can build upon to create short (2-5 page) reports from your
Silverlight applications.</p>

<p>Currently the sample consists of the full source code of a
simple report writer. It includes:</p>

<ul>
<li>automatic pagination</li>

<li>support for line items of varying height</li>

<li>total page count</li>

<li>templating</li>

<li>page headers and footers</li>

<li>report footer with support for calculated fields</li>

<li>events to allow hooking into printing at various stages</li>
</ul>

<h3>Latest Release</h3>

<p>Version information changed to use semantic versioning. This
vesion is numbered: <a
href="http://silverlightreporting.codeplex.com/releases/view/80092"
target="_blank">1.0.0-alpha.3</a></p>

<ul>
<li>Now targets Silverlight 5</li>

<li>Added ability to specify postscript (vector) printing. The
selected driver must support PostScript or this setting will have
no effect.</li>

<li>Fixed issue with not being able to re-print the report. (and
fixed leaky event handlers)</li>

<li>Added null check on templates</li>
</ul>

<p><a href="http://silverlightreporting.codeplex.com/"
target="_blank"><img src="http://10rem.net/media/82250/Windows-Live-Writer_Silverlight-Reporting-Open-Source-Printi_EA02_image_6.png" width="366" height="468" alt="image" border="0" style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px"/></a></p>

<p>This is still alpha, and is a minor project. Expect bugs. Report
them when you do. Offer fixes if you can :)</p>

<p><a
href="http://silverlightreporting.codeplex.com/releases/view/80092"
target="_blank">Get the latest release here</a>.</p>
]]></description></item></channel></rss>