Archive for the ‘.Net’ category

Bind to Method within a DataTemplate

June 12th, 2007

One of my play projects with WPF is a photo viewer for the pictures we put out on http://cromwellhaus.com.  One of the views is a montage of the latest photos with a random RotateTransform Angle applied to each image’s RenderTransform.  Getting the view itself set up as cake, but when I attempted to apply the random angle to each image, it wasn’t so random.

Here’s what happened and how to actually accomplish such a task:

I started out with an ItemsControl, rather than a ListView as most examples show, using a UniformGrid as the ItemsPanel.

<ItemsControl ItemTemplate="{StaticResource photoItem}" ItemsSource="{Binding Source={StaticResource dpPhotos}, XPath=/rss/channel/item}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <UniformGrid HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>

I bound the ItemsSource to an XmlDataProvider pointing to the photos RSS feed for Ryan Jr. pictures

<XmlDataProvider x:Key="dpPhotos" Source="http://cromwellhaus.com/photos/baby/pictures_rss.aspx?Tags=Ryan+Jr&amp;AndTags=1" XmlNamespaceManager="{StaticResource rssMapping}"/>

I run our site using Community Server 2007 Express Edition which provides RSS meta extensions for more detailed feeds.  This required that I apply an XmlNamespaceManager to define these extension namespaces.  That’s what this is for:

<XmlNamespaceMappingCollection x:Key="rssMapping">
  <XmlNamespaceMapping Uri="http://search.yahoo.com/mrss" Prefix="media" />
</XmlNamespaceMappingCollection>

Here is the DataTemplate used by the ItemsControl to display/render each image.  You’ll see this referred to in above as {StaticResource photoItem}:

<DataTemplate x:Key="photoItem">
  <Image Margin="12,12,12,12" Source="{Binding Mode=Default, XPath=media:thumbnail/@url}" ToolTip="{Binding XPath=title}" Width="{Binding Mode=Default, XPath=media:thumbnail/@width}" Height="{Binding Mode=Default, XPath=media:thumbnail/@height}" />
</DataTemplate>

You can see the use of the XmlNamespaceMapping in the XPath=media:thumbnail/@url.  That had me stumped for a few seconds, but opening the project up in Expression Blend and re-adding the XmlDataProvider created the Mappings for me.  (Sidebar: VS 2008 does do this for you – thank goodness)

At this point, we are displaying thumbnails and we are certainly aware that I make poor color choices, but we’re on our way.

Almost there...

Applying the RotateTransform is easy…

<Image Margin="12,12,12,12" Source="{Binding Mode=Default, XPath=media:thumbnail/@url}" ToolTip="{Binding XPath=title}" Width="{Binding Mode=Default, XPath=media:thumbnail/@width}" Height="{Binding Mode=Default, XPath=media:thumbnail/@height}">
  <Image.RenderTransform>
    <RotateTransform Angle="10" />
  </Image.RenderTransform>
</Image>

…and it’s almost as easy to use the System.Random class to generate the angle.  Just add the following ObjectDataProvider as a Window or Application Resource and bind the Angle property to it:

<ObjectDataProvider x:Key="randomAngle" ObjectType="{x:Type system:Random}" MethodName="Next">
  <ObjectDataProvider.MethodParameters>
    <system:Int32>-12</system:Int32>
    <system:Int32>12</system:Int32>
  </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

...
<RotateTransform Angle="{Binding Source={StaticResource randomAngle}" />

Well when you do this, you’ll find that you get the same Angle for every image.  This is because you are actually binding to a single instance of the ObjectDataProvider.  To resolve this we actually have to embed the ODP in the transform itself as so:

<RotateTransform>
  <RotateTransform.Angle>
    <Binding>
      <Binding.Source>
        <ObjectDataProvider ObjectType="{x:Type system:Random}" MethodName="Next">
          <ObjectDataProvider.MethodParameters>
            <system:Int32>-12</system:Int32>
            <system:Int32>12</system:Int32>
          </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
      </Binding.Source>
    </Binding>
  </RotateTransform.Angle>
</RotateTransform>

Tada!image

Now you will find that your angle’s aren’t terribly “Random”.  This is because you are actually asking for a new instance of the Random class each time.  You can tell the ODP within the DataTemplate to use the same instance each time by adding this to the Window Resources:

<ObjectDataProvider x:Key="randomAngle" ObjectType="{x:Type system:Random}"/>

and modifying the Angle binding to the following, telling the transform ODP to use a specific resource instance rather than just giving it a type to instantiate each time.

<ObjectDataProvider ObjectInstance="{StaticResource randomAngle}" MethodName="Next">
  <ObjectDataProvider.MethodParameters>
    <system:Int32>-12</system:Int32>
    <system:Int32>12</system:Int32>
  </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

You can download a mini-version used to write this post here.

Silverlight: .Net for the masses

May 1st, 2007

While up in Redmond for the WPF Bootcamp, we had a short time to work with some of the WPF/E, now Silverlight, team members.  At the time Silverlight didn’t make a whole lot of sense in our strategy.  That said, I hope everyone sees the great potential that comes from some of the features surrounding Silverlight 1.1 specifically.

Let’s put this into context. Over the last couple of years, true web-based applications have really started to take shape.  I’m talking Google Docs & Spreadsheets, Yahoo! Local, Yahoo! Pipes and not YouTube, which is a glorified photo sharing site.  A bevy of AJAX toolkits have attempted to fill the enormous development gap between LCD-JavaScript and C#, Java, VB, Ruby, and Python, but there is only so much one can do with JavaScript before you go crazy.

Now imagine some “real” applications that actually attempt to provide a full feature set which accentuates an existing web model.  My favorite example is Shutterfly Studio.  They probably could have given you 20% of the Collage functionality with some goofy JavaScript or lots of uploading and postbacks, but how long would you wait around for your photos to upload while trying out different layouts?  Not long I’d imagine.  This is where Silverlight comes in.

Silverlight takes the untold story of Java and actually runs with it by providing a consolidated branch of the full .Net CLR, including JITter, Garbage-Collector, BCL, Threading namespace, Network stack and more.  Well this is all well and good, but why not just use Flash?  Well, if you want to deploy a Flash application, you are forced to use ActionScript, which doesn’t provide nearly the feature set of .Net nor is it useful in any other environment other than Flash, so your experience is isolated.  Flash also doesn’t provide the huge WCF communications platform for secure, transport independent communications, WPF for rich interactive media, and one of the most powerful IDE platforms in Visual Studio.

Imagine starting your family collage with Shutterfly Studio at home on your laptop, getting to work in the morning and flipping through real layouts with your pictures at work (lunch of course) and then sending your parents a link to the catalog of pictures where they can browse any layout and order their own version of the collage?  No Shutterfly Studio desktop icon or Start Menu shortcut.  Just a one time 20 second download of the Silverlight CLR – yeah the Silverlight CLR is only 4mb.  That’s what removing 90% of the named color members in System.Drawing.Color and asking people to look up the HEX value.

Have fun.

Visual Studio Orcas Beta 1

April 20th, 2007

The last few weeks I’ve felt like a little intern again.  With the WPF Bootcamp and the early stages WCF integration into the Speedy Rewards messaging infrastructure (I’ll be posting on this soon), I’ve had lots of time to play with .Net 3.0 stuff. 

For those that have had a chance to fiddle, there are two feasible options at this point: 1) VS.Net Extensions for WCF & WPF and 2) Orcas CTP’s.  The Extensions, in my opinion, were a valiant stop-gap effort to get people started.  This is especially true for WCF, because there isn’t a whole lot of design time experience necessary for web services with the exception of those monstrous config sections.  The WPF extensions were OK, but it was basically like having XAMLPad embedded in VS.  Orcas CTPS, on the other hand, have been virtually useless.  The WPF designer crashed regularly and was slower than waiting for me do math in my head.  This may be due to the Virtual PC requirements, since they hadn’t yet worked out the issue of Visual Studio 2005 and Orcas living happily side-by-side.

Anyway’s, as of today, there is a better #2.  Orcas has hit Beta 2.  Go get it.  There are Express SKU’s too, so don’t worry if you aren’t an MSDN Subscriber, you can join the party too.

Happy coding – go make something cool.

PerformanceHelper for easy PerformanceCounter integration

April 19th, 2007

In the Speedy Rewards team here we use custom PerformanceCounters quite extensively to monitor and trend our host systems.  You may not know, but our rewards program implements real-time host integration for transactions that are Id’ed as a SpeedyRewards member such that systems like the in-store kiosk, www.SpeedyRewards.com, and any other store you may soon visit can accurately reflect balance updates immediately.  With 1600+ stores doing this and a sub-1 second response time, we need to keep a close eye on things.

Today I was trying to do some preliminary performance profiling on our new WCF based messaging infrastructure.  To make my life a little easier, I put together a PerformanceHelper class that I actually modeling off the Tracer class found in the Enterprise Library 1.1.  To use it, you wrap a section of code you wish to monitor performance for with the following:

using(new PerformanceHelper(CATEGORY, "<BlockInstanceName>") )
{
    //...
}

This will provide you with a RateOfCountsPerSecond32 counter and an AverageTimer32 counter called “Operations/sec\<BlockInstanceName>” and “Average Time/Operation\<BlockInstanceName>” respectively.  You can download the PerformanceHelper class here and a sample project here

Feel free to use and abuse it, but be aware that this has not fully tested and may well contain bugs.  I provide NO warranty or guarantees, so don’t come to me when your server blue-screens from a corrupt registry (not that I’ve ever done that).  Use at your own peril.

Microsoft Expression Blend available to from MSDN

April 3rd, 2007

One of the cool tools we had a chance to use while up at the WPF Bootcamp in Redmond was Expression Blend.  While there I became pretty engrossed in the ease with which you could create fairly cool animations without an intimate knowledge of Xaml.  This made it all that harder to leave seeing as we had the latest bits at the time (the Release Candidate is available as a 30 trial).  Fortunately, or gratefully?, Microsoft has decided to make it available on MSDN.  That means me!

I will say though, while reading Charles Petzold’s book Application = Code + Markup which starts with Code and then moves to Xaml, I believe developers and designers alike will be fooled into trying to generate a number of more complex animations with paths, triggers/timelines, etc. rather than implement new animations via code.  Karsten Januszewski, who we were lucky enough to meet last week, pointed this exact scenario out while I was attempting to mimic the North Face kiosk carousel via a path.  He referenced a previous post of his which shows how to create a custom animation.  Until I grasp the animation framework in WPF, I’ll not risk embarrassing myself by attempting to better explain what Karsten already does much better than I.

WPF Bootcamp Day 2 – Blend

April 1st, 2007

[Update: These are being posted due to the ftp access restrictions at the Microsoft Campus]

Today has been pretty intense which has kept me away from blogging “live”.  Today started with Kevin Moore, Program Manager for WPF/Blend(?), and a lightning round with Expression Blend.  As I mentioned yesterday, I’m not a designer, so Kevin had my mind spinning before breakfast had even settled. 

For those dev-signers (developers who design out of necessity) Blend is initially a very overwhelming experience.  Don’t expect to create the North Face demo your first time out.  That said, I was able grasp the benefit of a few concepts including DataTemplates and Styles.  This stuff is like OO for UI.  Pretty cool.

  As soon as Kevin had lost me (quickly), I decided to start playing with Blend Styles and Templates.  At the same time, I decided I’d design my own button.  It turns out my reasoning for wanting to do this, super-rounded ends, were already possible in the standard button, but it was a good learning experience.

Styles

Styles are pretty straight forward and many references to CSS have been made.  Styles seem to be a way to share design properties between elements, especially similar elements.  It seems pretty intuitive, but every time you change the visual appearance of a control, even via Visual Studio or XamlPad, you are styling your control/element.  It becomes really powerful as you share these styles across your project by including these styles in your App Resources section.  From within Blend this is pretty easy after you’ve gone through and stylized one of your controls by selecting that element and going to the Object -> Edit Style -> Edit Copy.   

You can then Right Click your other elements, go to Edit Control Parts (Template) -> Apply Resource and Select the Style you just created.  You now have a sharable style across your WPF application.  I’m still curious about the ability of sharing these styles across multiple projects and applications if you have a suite of tools.  Are these considered Assets for Expression Media?  That would be cool.

Templates

The way I feel Templating is best described in relationship to Styling is to say that Styling helps describe the visual appearance of one or more elements, while templating describes the Element tree that makes up a visual entity.  For instance, my button above used a template to combine two Ellipses and a Rectangle.  But an ellipse on each end of the Rectangle and you’ve got a rounded edge button.

To get started with templating, I right click on the standard button and drilled down to Edit Control Parts (Template) -> Create Empty.  If you’ve done cool stuff with your element already, you can Edit Copy and apply that to other elements rather than start over.  I’ll go over a demo to create a pretty cool button that uses lots of composite elements to have rollover effects (glow), transition effects, etc.

 

WPF Bootcamp Day 3 – Hardware capability

March 28th, 2007

To avoid disappointing users after they’ve gotten as far as running your application on their 1997 300mhz Pentium II, determine their capabilities using the RenderCapability.Tier value before hand and notifying them that they’ll need to joing the 21st century before running your app. 

Henry Hahn has a quick overview and, the always welcome, code samples of using this value to make your application conform to the different tiers.

Don’t forget your bit shifting, cause the Tier is set up to support new Tiers/platforms in future releases.

WPF Bootcamp Day 1 – Expression

March 26th, 2007

For those who don’t already know, I want to make it perfectly clear that I am the last person you would ask to design an appealling interface.  Messaging, thread syncronization, etc I’m your guy, but pretty pictures I am not.

WPF Bootcamp Day 1 – Visual Studio "Orcas" Demo

March 26th, 2007

We moved past the introductions quickly and are getting down and dirty.  Rob Relyea took us through the basics of WPF from the latest Visual Studio Orcas perspective.  Starting simple by creating a button via Xaml and a duplicate example using purely C# code.  I’ve posted a copy of the sample here for Visual Studio 2005 with the WPF Extensions.

One of the interesting new classes for you code junkies is the ObservableCollection class available now in .Net 3.0.  This class implements the INotifyPropertyChanged interface allowing the dynamic databinding in WPF.  This is cool for all sorts of reasons, but specifically because we can use this dynamic, event based collections infrastructure for in memory lists of more than your list of employee names, but also videos, complex business objects like product definitions, pages in a book that you are rendering, or files in a directory which you are monitoring.

WPF Bootcamp Day 1

March 26th, 2007

My co-worker Steve and I are here in Redmond this week for a WPF Bootcamp training session.  We started off by meeting the WPF Product Unit Manager, Ian Ellison-Tayler, and Lead Program Manager, Rob Relyea.  Ian ran through some existing WPF applications floating around the intersphere.  As early as it is for WPF, there are some cool apps already.  Take a look at iBloks, definitely a fun little app.  The British Library has a cool XBAP application as well.

Amongst all the glitz and glamour of the pretty pictures and transitions demoed and blogged about are the features of WPF that make those things possible.  One of the questions I found very intriguing involved how Xaml and the “Element-Content” model would affect future standards.  The “Element/Content” model provides the ability to dress up what is still your standard button with content of all shapes and sizes.  Adding animations, movies, complex text to buttons with ease will open up the options for designers and developers to question what is a functional and usable layout for their software.  It was met with snickers, but the comment that market dynamics would play out the designs that are acceptable really holds true that the design standards are moving from the platform groups to the designers.  What an excitingly simple concept.