Silverlight Christmas Cards for 2009
Continuing the tradition from last year here is a list of Silverlight-based Holiday cards I could find. The cards are definitely getting fancier as the technology advances.
Archetype Holiday Card Creator
Shape, Decorate, Bake and Share
Inside Xbox
Happy Holidays from around the world
Happy Holidays Art Generator
my own attempt at some holiday fun
Desktop Snow
Technically a WPF app, but its too cool not to include
Microsoft Partner Network Festive Game
Grab the pudding, dodge the elves and beat the reindeers!
Santa Present Kicker
Help Santa drop-kick presents into his sleigh
Christmas Tree Decorator
drag and drop ornaments on to the tree
RunAtServer Consulting
digging the music
If you feel like making your own cards, check out:
- Designing a Christmas card, print to Silverlight – from clear breeze design
- Falling Snow in Silverlight – kirupa.com tutorial
As a present to you from the team, check out the limited time 30% discount on Expression Studio 3 offer.
Happy holidays! Here’s to a rocking 2010!
Transforming grouped elements in Expression Blend
I found this question about resizing elements on Stack Overflow and thought I’d share what I found with others. This also gives me a little more room to put together an answer.
jhubsharp is walking through the Eyes of Blend Drawing tutorial and has run into an issue when resizing grouped elements. In the tutorial, three ellipses are used to create an eyeball. Once they are grouped into a Grid the resizing behavior appears to have changed. Let’s take a look at what’s going on.
At this stage in the tutorial here’s the object tree:
- Grid (LayoutRoot)
- Ellipse
- Grid
- Ellipse
- Ellipse
- Ellipse
If you select the child Grid and drag the handles to resize, the Grid’s Height, Width may be changed. Additionally because the Grid is a child of another Grid the Blend Designer may change the Margin, HorizontalAlignment and VerticalAlignment properties.
The Blend Designer may also modify the Margin, HorizontalAlignment and VerticalAlignment properties of the child Ellipses so they maintain their position. The Blend Designer makes changes for you in the XAML behind the scenes to persist your visual design as much as possible. A good example of this behavior is if you were to add a Grid Column, the child Ellipses would be set to Grid.ColumnSpan = 2, so they would continue to fill the same space.
If you select a single Ellipse in the child Grid, dragging the handles to resize may modify the Height, Width, alignment and Margin properties as expected. Not a lot of surprises here.
Now if you select multiple Ellipses, by holding Shift down and clicking the Ellipses or selecting them in the Object panel there is added functionality to be aware of. In the picture above (click to see a larger version), you can see I have added two rectangles, a red one and a green one. When you select multiple elements, two handles appear on the element you select first (in this case I selected the larger white Ellipse). Dragging the handle under the green rectangle will resize the whole group of elements. Dragging the handle under the red rectangle will only resize the larger white Ellipse.
This may not be so obvious when the elements are small or closely positioned together. I know at first, I saw the two different behaviors and couldn’t figure out why it appeared to be randomly resizing the group or a single item. This compounded with the fact that I wasn’t always choosing the same element first, added to the confusion.
Now that I am aware of the feature though, it makes it all the more useful. Hopefully this explains jhubsharp’s issue and hopefully it may help you out as well.
Flash to Silverlight Guide – MovieClip to UserControl
The first sections of the new Flash to Silverlight Guide are up!
The purpose of this guide is to familiarize developers and designers with Silverlight concepts by relating them to Flash concepts. Comparisons are drawn between each pair of concepts in effort to map knowledge from one platform to another.
This is the first edition of the guide covering the topics Fundamentals and Tools, MovieClip To UserControl and Flex Components to Silverlight Controls. The next edition will include comparisons of different features from both platforms including Graphics, Animation, Coding and Out Of Browser.
The guide works as a standalone reference, as well as the base of knowledge for upcoming tutorials covering specific topics. There is a ton of content to cover, so we’ll be posting different sections as we get them completed.
During the research process, I’ve built up a large list of ideas that I’m excited to write about. This will be my main focus for the foreseeable future. I will be hitting the road next year with this content and will be posting event details on this blog.
One event I’ll be attending for certain is MIX10 (still hoping to get a “Flash to Silverlight” session). I’ve seen some of the behind the scenes planning for MIX10, and let me say – this is going to be the best MIX ever. For real, it will be a heck of a 5th year birthday for the event. I hope you can make it.
Happy Holidays in Silverlight with help from COLOURlovers
A collision of ideas happened yesterday. The second run of the MIX 10k contest was announced and I realized just how close we are to the holidays. So I thought to myself, “I need a holiday card generator that runs on less than 10k of code”. And that’s exactly what I made.
I’ve run the program a few times now and below are a few of my favorite prints. Here’s how you can make your own:
- Open the Holiday Card Generator page.
- A random palette will be selected using the awesome COLOURlovers API.
- If you want a new palette of colors, refresh the page.
- Random holiday shapes will begin appearing on the screen.
- if you want a new arrangement, click one of the shapes with your mouse.
- Once the all the shapes appear, move the mouse to slide the arrangement around.
- Use some screen capture like the Snipping Tool or old Print Screen to save it.
- Or, just hit refresh and start all over again.
This was a lot of fun and pretty easy to do. I can see how once you get started on the “generated art” you just keep going.
Happy Holidays!
TWC9 features Silverlight AR, BugCamSmash and Blend Extensibility
Very cool to see that this week’s episode of This Week on Channel 9 feature BugCamSmash along with Rene Schulte’s Augmented Reality Proof of Concept.
An extra treat though was to see they also featured the videos from the Visual Studio Ecosystem Summit. The summit is all about extending .NET development tools, like Visual Studio and Expression Blend, with your own Add-Ins and custom control support.
Unni Ravidranathan, a program manager on the Blend team, presented and the video as available on Ch 9: VSX107: Extending the Design Capabilities of Blend 3
Below are my rough notes from his talk. For more information on Blend Extensibility check out the video and definitely take a look at Unni’s blog.
- Toolbox
- permanent installation
- descriptions
- custom icons
- categorization
- Design Surface
- Adorners
- Context Menus
- Design Mode Value Provider
- Property Grid
- Project and Item templates
- Applies to Controls, Behaviors and Shaders
- Consistent API between WPF and Silverlight
- shared with Visual Studio 2010
- Side by Side support with Blend 2 and VS2008
- Blend Only features
- AlternateContent Property
- Toolbox Category
- Number Ranges/Increments
- More to come in Blend 4!
Creating a Blend Extensible sample is definitely on my list and I have a few ideas of what I’d like to create. I need to finish explaining how BugCamSmash works first though, so far I’ve left out the juiciest parts (WebCam and Performance).
BugCamSmash Dissected part 3 – Give the Bugs Brains
This part of of the series explaining how BugCamSmash was made is truly the quiet before the storm. The tipping point before the big finale. In part 1, we created a bug we could smash with a rock. In part 2, we gave the bug the ability to crawl towards a location specified by a mouse click (to be then smashed with a rock). In this part, we will cover giving the bugs their own will to move and making sure they are not too coordinated in their movements.
Giving the Bugs some direction
Now that the bugs can crawl to a point, its time to give them the power to decide when and where to move on their own. I created another short Storyboard called destTimer to choose a new point to MoveTo after a random amount of time. The following code was added to the Bug class to handle the completed event of the new Storyboard:
void destTimer_Completed(object sender, EventArgs e)
{
parent = Parent as FrameworkElement;
destTimer.Stop();
MoveTo(new Point(r.NextDouble() * parent.ActualWidth – this.ActualWidth,
r.NextDouble() * parent.ActualHeight – this.ActualHeight));
destTimer.Duration = TimeSpan.FromMilliseconds(r.Next(3000, (10000));
destTimer.Begin();
}
The time between movement is defined by the Duration of destTimer which is randomly generated on load as well as every time the Storyaboard Completes. During that time a new Point is randomly chosen within the bounds of the LayoutRoot Canvas and the move is executed using the MoveTo method from before.

Randomizing the Bugs
Now that I had the bug moving on its on, I thought it was time to give it some friends. On the first run of the SizeChanged event of MainPage, I added a four more calls to the AddBug method. As expected, when the app was run, five bugs appeared randomly positioned on the stage.
Unexpectedly though, it was evident that they were all choosing the same location to move towards. After the second point they merged to fill the same space and look as if they were a single bug with extra thick legs. This was due to the fact that the Random class is only a “pseudo-random number generator”.
From the MSDN site on the Random class:
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.
Because my goal was to keep this experiment simple, I went with hard-coding a few numbers as seed values and then passing those through the constructor of the Bug class.
One way to improve performance and avoid this problem is to create one Random object to generate many number over time.
For a truly random number you can use the something like the RNGCryptoServiceProvider class.

Hooking up the WebCam
With the bugs on the move (and ehading towards different locations) its time to bring in the WebCam. In MainPage.xaml, I added a new Grid to LayoutRoot called screenGrid and inside that Grid I added a Rectangle called screen. I removed the BugSmashDrag behavior and added an EventHandler to the MouseLeftButtonUp event of the Rock Canvas.
The following code requests from the user access to the WebCam and creates a CaptureSource object. The CaptureSource object is then used as the source for a VideoBrush which is painted as the Fill of the screen Rectangle.
private void Rock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (CaptureDeviceConfiguration.AllowedDeviceAccess ||
CaptureDeviceConfiguration.RequestDeviceAccess())
{
VideoCaptureDevice vcd = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
if (vcd != null)
{
cs = new CaptureSource();
cs.VideoCaptureDevice = vcd;
cs.Start();
VideoBrush videoBrush = new VideoBrush();
videoBrush.Stretch = Stretch.Uniform;
videoBrush.SetSource(cs);
screen.Fill = videoBrush;
}
}
}
Bugs running around, WebCam in place, next its time bring in Mantis Boy!
The next part will cover the hit detection using image diff and multi-threads
BugCamSmash Dissected part 2 – Make the Bugs Crawl
In part 1 of this series, explaining how BugCamSmash we walked through the creating the bug sprite, placing the bug at a random position on the screen and triggering a Smash animation when a rock sprite collides with the bug sprite.
In this part we will cover creating the Walk animation, rotating the bug towards and walking to a point clicked with the mouse.

Creating the Walk Animation
Blend makes creating new Storyboards for animations very simple, in the Objects Panel click the “+” button, provide a name and you’re in record mode. Creating a walk cycle for a six-legged creature is not so easy. Not until the final step of this project did I go back and refine the Walk animation. If you download the source for this part you will see seem awkward six-legged limp action.
Regardless, I have a few tips on creating this type of animation:
- When dealing with short keyframe increments, use the Timeline Zoom (small slider below the storyboard editor) to make frame selection easier.
- Adjust the Center Point of the Transform to make rotations act more like joints rather than rotating from the default center.
- Hold the Ctrl key down while click and dragging a selection box to select multiple keyframes at a once.
- Edit with AutoReverse off, this way the when adding new keyframes the position will be held from the last keyframe rather than the first.

Moving the Bug towards the Destination
To make the leg-flopping animation worth it we need to move the bug across the screen to the point that the mouse is clicked. The following code was added to the Bug class providing a public method MoveTo to pass the mouse click point to the bug sprite and a new Storyboard moveTimer was added to ease the bug towards that new point.
Since this is a lengthy bit of code, I’ve added comments inline to explain what is going on.
public void MoveTo(Point pt)
{
//save the destination location
destX = pt.X;
destY = pt.Y;
//lower the acceleration because the bug is heading to a new location
curAcceleration = acceleration;
//start the moveTimer and walk cycle animation
moveTimer.Begin();
Walk1.Begin();
}
//this fires every 17 milliseconds
void moveTimer_Completed(object sender, EventArgs e)
{
//get the current position of the bug
curX = Canvas.GetLeft(this);
curY = Canvas.GetTop(this);
//check if the bug needs to move
if (curX != destX && curX != destY)
{
//determine the distance to the destination
deltaX = curX – destX;
deltaY = curY – destY;
dist = Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
//if the bug is close enough, snap to the destination
if (speed >= dist)
{
curAcceleration = acceleration;
Canvas.SetLeft(this, destX);
Canvas.SetTop(this, destY);
Walk1.Pause();
}
else
{
//ease the bug closer to its destination using walking speed and acceleration
curX -= speed * (deltaX / dist) * curAcceleration;
curY -= speed * (deltaY / dist) * curAcceleration;
Canvas.SetLeft(this, curX);
Canvas.SetTop(this, curY);
//increase acceleration
if (curAcceleration < 1)
curAcceleration += acceleration;
//begin the timer again to move closer to destination over time
moveTimer.Begin();
}
}
}

Rotating the Bug towards the Destination
With the movement in place, rotating towards the point was simple. The current bit of code was added right before the “//ease the bug closer to its destination…” code in the moveTimer_Completed method.
The Atan2 function is used to determine the angle using the delta Point and an angle offset. The offset of 90 degrees was used due to the original orientation of the bug artwork.
void moveTimer_Completed(object sender, EventArgs e)
{
[…]
if (speed >= dist)
{
[…]
}
else
{
//rotate towards destination
destAngle = (Math.Atan2(-deltaY, -deltaX) * radiansFactor / Math.PI) + angleOffset;
curAngle = rotation.Angle;
curAngle += (destAngle – curAngle) * curAcceleration;
rotation.Angle = curAngle;
[…]
}
}
Now the bug will crawl and rotate towards the point clicked with the mouse and still smashable with the rock from part 1.
The next part will cover empowering the bugs to choose their own destination
BugCamSmash Dissected part 1 – Smash a Bug
When beginning the project that became BugCamSmash, I knew I was going to try and interact with the UI using the new webcam feature in some way. My first step then was to find a good method for hit detection as well as a good target to hit.
Now normally, I’m a peaceful being who tries to “free” insects and creatures that find themselves in my oh-so-humanly claimed living space. But sometimes when finding a creature that looks dangerous or as if it might sting or bite, caveman instincts kick in and I choose to smash.
Therefore bugs were a naturally choice as the target to “hit”.
Creating the Bug

I chose to create a .png for the body or shell of the beetle because I knew I was going for a somewhat realistic look and it is simpler to do subtle bevel-like features rasterized rather than vectors. I also knew I wouldn’t be animating the shell in any way.
The legs and antennae would be animated though, so those were drawn in Blend as Paths. I drew one set of three legs first, grouped them into a Canvas and copied another and flipped it horizontally. The antennae were then drawn in and I created a Twitch Storyboard to show them quickly moving inwards. This was done by animating the individual points on each antenna Path over a very short period of time.
Then I added a simple Smash Storyboard rotating and repositioning the leg and antenna parts to be played after a hit detection is made.
Now to hook up the Storyboards in the class file, I created EventHandler for the Loaded event of the Bug, another handler for the time completed event, a Smash method and a Smashed property:
public bool Smashed { get; set; }
void Bug_Loaded(object sender, RoutedEventArgs e)
{
r = new Random();
timer = new Storyboard();
timer.Duration = TimeSpan.FromMilliseconds(1000);
timer.Completed += new EventHandler(timer_Completed);
timer.Begin();
}
void timer_Completed(object sender, EventArgs e)
{
Twitch.Begin();
timer.Duration = TimeSpan.FromMilliseconds(r.Next(1000, 10000));
timer.Begin();
}
public void Smash()
{
Smashed = true;
timer.Stop();
SmashAnim1.Begin();
}
On load, the timer Storyboard is instantiated to randomly call the Twitch animation repeatedly. And Smash is a public method used to stop the random twitching and play the Smash animation to break the legs of the bug.
Placing the Bug on the Screen
Now that I have my bug, I wanted to randomly place it on the screen. This was accomplished by adding the following code to the MainPage:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
r = new Random();
}
void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (firstSizeChanged)
AddBug();
}
void AddBug()
{
Bug b = new Bug();
Canvas.SetLeft(b, r.NextDouble() * LayoutRoot.ActualWidth – bugWidth);
Canvas.SetTop(b, r.NextDouble() * LayoutRoot.ActualHeight – bugHeight);
LayoutRoot.Children.Add(b);
}

On Load of MainPage, I create a new Random object. Then, the first time MainPage changes size I run the AddBug method. No specific Height and Width is set to LayoutRoot, the main Canvas, so that it will span the full size of the application host (determined by the size of the object tag in the html). This results in Width and Height always returning 0, and not being useful when attempting to randomly place the bug.
To learn the width and height of the LayoutRoot Canvas, we must wait until Silverlight’s layout system has completed the measure and arrange process which fires the SizeChanged event. At this point we can use the ActualWidth and ActualHeight properties to randomly position the bug within the bounds of LayoutRoot.
Then we add the bug as a child of LayoutRoot and we’re ready. All we need is a rock to smash it.
Adding the Smashing Rock
The rock is simply a bunch of Paths grouped into a Canvas with two important features. First the rock’s ZIndex is set to 999, so when the bug is added dynamically it will be behind the rock. Second the interactivity of dragging the rock with a mouse and smashing the bug is handled with a custom behavior.
The behavior appropriately called BugSmashDrag is very similar to the default MouseDrag behavior with two added features: bug locating on mouse down and bug smashing on mousemove.
private void findBugs()
{
Panel parent = AssociatedObject.Parent as Panel;
Bug b = null;
bugs.Clear();
foreach (UIElement uie in parent.Children)
{
if (uie is Bug)
{
b = uie as Bug;
if (!b.Smashed)
bugs.Add(b);
}
}
}
private void AssociatedObjectMouseMove(object sender, MouseEventArgs e)
{
[…mouse move code…]
foreach (Bug b in bugs)
{
if (checkCollision(AssociatedObject, b))
{
b.Smash();
findBugs();
break;
}
}
}

On MouseLeftButtonDown of the object that the behavior is attached to (in this case the rock), mouse dragging begins and an inventory is taken and stored of how many bugs there are in the parent Canvas LayoutRoot.
Then when the Mouse is moved the checkCollosion1 method is called comparing the bounds of the rock and the bug. When the bounds intersect, the Smash method is called on the instance of bug and we have success!
A smashed bug.
The next step will cover making the bugs “crawl” based on where the mouse is clicked
1 Using Andy Beaulieu’s posted Silverlight HitTest method
BugCamSmash – Motion Detection with Silverlight 4 Beta
At PDC09, we released Silverlight 4 Beta and announced one of the availability of, one of the most requested features, Web Cam Support.
Wanting to have fun with the new feature, I thought of a fun sample to create – smashing bugs with motion detection. First step was to get bugs to crawl across the screen. Next I added the WebCam with frame diff calculation, which was intensive so took advantage of the multiple thread support. And finally I added a little Mantis Boy avatar to visualize the smashing of the bugs.
Over the next few days I will post about how the code works and improvements made for performance. You can check out a video to see Mantis Boy in action, run the demo or download the source.
- Watch the video
- Run the Demo*
- Download the Source
- Learn about more new features in Silverlight 4 Beta
- View a few Screenshots
Learn how it was written:
- Dissected part 1 – Smash a Bug
- Dissected part 2 – Make the Bugs Crawl
- Dissected part 3 – Give the Bugs Brains
- Dissected part 4 – WebCam and HitTest on a different thread
*(warning this is Silverlight 4 Beta code, if you’re not currently setup to run the beta stick with the video)
CompositeTransform simplifies transforms in Silverlight 4 Beta
One of the features you may have missed that was added to the Silverlight 4 beta is the new CompositeTransform class. The new class provides a simpler way to transform an element, by simply offering a single object to instantiate rather than a group of transforms made for specific transforms. To animate properties, you will no longer need to name multiple Transforms or access them by index (hoping they were added in the expected order).
Not only is the code easier to write and less characters, but property access is clearer. To rotate an object you change the Rotation property rather than the RotationTransform.Angle property. I think the simplicity of property access is demonstrated best by the C# example below.
XAML example
C# example

You will notice that the new Expression Blend for .NET 4 Preview still defaults to the verbose TransformGroup, but it will render the CompositeTransform without complaints.
For more information on the Silverlight 4 Beta, check out the Technical Feature Overview for Silverlight 4.



















RSS - Posts

