Nimble Coder

Adventures in Nimble Coding
posts - 74, comments - 19, trackbacks - 0

Friday, January 30, 2009

Using a delegate and Custom Appender with log4net to display live log text

log4netAppender sample Recently I needed to display the text that was sent to log4net in a TextBox in a Form. It turns out this is very easy to do using a custom appender and the AppenderSkeleton. The custom appender uses a delegate to allow the host program to define a callback function to handle the log text as necessary.

1. Create a new custom appender class

I named my appender DelegateAppender because it needed to use a delegate to pass the text to the Form.

using log4net.Core;

namespace log4net.Appender
{
    public delegate void LogTextAppend(string text);

    public class DelegateAppender : log4net.Appender.AppenderSkeleton
    {
        private LogTextAppend logTextAppend;

        public LogTextAppend LogTextMethod
        {
            get { return logTextAppend; }
            set { logTextAppend = value; }
        }

        public DelegateAppender()
        {
            logTextAppend = EmptyAppend;
        }

        private void EmptyAppend(string text)
        {
            // Do nothing
        }

        protected override void Append(LoggingEvent loggingEvent)
        {
            if (logTextAppend != null)
                logTextAppend(RenderLoggingEvent(loggingEvent));
        }
    }
}

2. Create and assign the delegate to the appender

As far as I could tell, there was no easy way to specify the delegate to use in the configuration of the DelegateAppender. Therefore I added a simple method to assign the delegate in the Form to the DelegateAppender.

public void AddStatus(string message)
{
    textBoxStatus.AppendText(message);
}

private void InitializeLogging()
{
    bool initialized = false;

    if (!log.Logger.Repository.Configured)
    {
        log4net.Config.XmlConfigurator.Configure();
        textBoxStatus.AppendText("WARNING: log4net not automatically configured. " +
            "Check AssemblyInfo.cs for - " +
            "[assembly: log4net.Config.XmlConfigurator(Watch=true)]\r\n");
    }

    foreach (log4net.Appender.IAppender appender in log.Logger.Repository.GetAppenders())
    {
        if (appender.GetType() == typeof(log4net.Appender.DelegateAppender))
        {
            log4net.Appender.DelegateAppender delegateAppender = (log4net.Appender.DelegateAppender) appender;
            // .NET 2.0+
            delegateAppender.LogTextMethod = this.AddStatus;
            // .NET 1.1
            //delegateAppender.LogTextMethod = new log4net.Appender.LogTextAppend(this.AddStatus);
            initialized = true;
        }
    }

    if (!initialized)
    {
        textBoxStatus.AppendText("ERROR: Unable to add DelegateAppender to logging!\r\n");
    }
}

3. Add the log4net configuration to app.config and AssemblyInfo.cs

The code for AssemblyInfo.cs just tells log4net to configure itself and also watch for changes.

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

The app.config is as follows: 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <configSections>
  <section
   name="log4net"
   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"
  />
 </configSections>

 <log4net>
  <logger name="log4netAppender.LogTestForm">
   <level value="ALL"/>
  </logger>
  <root>
   <level value="ALL" />
   <appender-ref ref="DelegateAppender" />
  </root>
  <appender
    name="DelegateAppender"
    type="log4net.Appender.DelegateAppender" >
   <layout type="log4net.Layout.PatternLayout">
    <param
     name="ConversionPattern"
     value="%m%n"
    />
   </layout>
  </appender>
 </log4net>
</configuration>

And there is a simple example of how to create a custom appender with log4net and hook it into an application.

Technorati tags: ,

posted @ Friday, January 30, 2009 12:42 PM | Feedback (1) | Filed Under [ C# ]

Thursday, November 06, 2008

Spinning Wait Symbol in Silverlight, Part4

SpinningCursor4-TestPage

Series History

 

Introduction

The goal of these posts is to build a spinning cursor similar to the Mac OS X wait cursor through programmatic means in Silverlight. The cursor is still very rough and will undergo improvements progrressively. One of the reasons to build the cursor programmatically is to have more control over the output such as changing the number of slices or rotation or other parameters.

For this post, I added an animation to the rotation angle of the canvas which causes the slices to spin. I also added a simple navigation to the previous examples.

Step 1: Adding the Animation

In the previous post, I had one canvas for the background image as well as the slices. This time I realized I needed two canvases: one for the background and one for the slices. I needed separate canvases so that I could apply a rotation transform animation to the slices without affecting the background image. I used Expression Blend 2.0 sp1 and selected the "SpinningCanvas" and added an Storyboard named "SpinStoryboard". I then changed the Angle of the RotateTransform from 0 - 360° for the time range 0.0 - 2.0 sec.

SpinningCursor4-BlendAnimation

This resulted in the following XAML:

<UserControl.Resources>
    <Storyboard x:Name="SpinStoryboard" RepeatBehavior="Forever">
        <DoubleAnimationUsingKeyFrames
            BeginTime="00:00:00"
            Storyboard.TargetName="SpinningCanvas"
            Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)">
            <SplineDoubleKeyFrame KeyTime="00:00:02" Value="360"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</UserControl.Resources>

Step 2: Starting the Animation

When the control is created or updated, the Update() method is called. I modified the method as follows:

void Update()
{
    SpinStoryboard.Stop();
    CursorCanvas.Children.Clear();
    SpinningCanvas.Children.Clear();
    CreateOutlineGuides(CursorCanvas);
    CreateBackground(CursorCanvas);
    CreateSlicePaths(SpinningCanvas);
    SpinStoryboard.Begin();
}

Step 3: Adding the Sample Navigation

I wanted to support future samples, so I used reflection to find all of the UserControls not including App or Page. I used a Dictionary<string, Type> to map the Type.Name with the Type in case I need it for future samples. I then dynamically created a button for each sample.

void Page_Loaded(object sender, RoutedEventArgs e)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    Type[] exportedTypes = assembly.GetExportedTypes();
    foreach (Type t in exportedTypes)
    {
        // Testing various inheritance detection methods
        bool isNotApp = (t != typeof(App));
        bool isNotSelf = (t != this.GetType());
        bool isUserControl = t.IsSubclassOf(typeof(UserControl));

        if (isNotApp && isNotSelf && isUserControl)
        {
            _implementedTypes.Add(t.Name, t);
        }
    }

    Button lastButton = null;

    // Sort the names of the UserControls to make more sense
    List<string> sortedKeys = new List<string>(_implementedTypes.Keys);
    sortedKeys.Sort();

    for (int index = 0; index < _implementedTypes.Count; ++index)
    {
        string key = sortedKeys[index];
        Type t = _implementedTypes[key];
        lastButton = AddButton(t, index);
    }

    // Use the last UserControl for the initial display
    if (lastButton != null)
    {
        Button_Click(lastButton, null);
    }
}

To make it simple, I used name of the UserControl for the Button.Content and in the Button_Click event I used System.Activator to create an instance of the class.

private void Button_Click(object sender, RoutedEventArgs e)
{
    UIElement control = null;

    try
    {
        Button button = sender as Button;
        string typeName = button.Content as string;
        Type type = _implementedTypes[typeName];
        object instance = System.Activator.CreateInstance(type);
        control = instance as UIElement;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.ToString());
    }

    WorkArea.Children.Clear();
    if (control != null)
        WorkArea.Children.Add(control);
}

Conclusion

The animation looks nice and adds a lot to the overall effect. For the next part, I plan to dynamically create the animation instead of using Blend and perhaps improve the background shape to more closely resemble the Mac OS X spinning cursor.

kick it on DotNetKicks.com
Technorati tags: ,

posted @ Thursday, November 06, 2008 2:03 AM | Feedback (1) | Filed Under [ C# SilverLight ]

Wednesday, October 29, 2008

Spinning Wait Symbol in Silverlight, Part3

SpinningCursor3-TestPage

Series History

In this post, I add curvature to the slices and refactor the code to support upcoming features. The goal of these posts is to build a spinning cursor similar to the Mac OS X wait cursor through programmatic means in Silverlight. One of the reasons to build the cursor programmatically is to create it will different number of slices or rotation or other parameters. At this point, the cursor is still very rough and just beginning to resemble the final result. In upcoming posts, I will animate the cursor and adjust the appearance to more closely resemble the desired cursor.

Step 1: Adjust the cursor properties

I added AlternateSlices and Origin properties, and also DefaultSliceCount and DefaultRotationAngle to the class.

public static readonly int DefaultSliceCount = 10;
public static readonly double DefaultSliceRotationAngle = 360.0 / DefaultSliceCount;

/// <summary>
/// Show alternating slices (true) or all slices (false)        
/// </summary> 
public bool AlternateSlices { get; set; }

/// <summary>        
/// The origin of the ellipse for the spinning cursor 
/// </summary> 
public Point Origin { get; private set; }

Step 2: Set the default parameter values

I specified the default slice count and the radius and origin of the cursor.

void Page_Loaded(object sender, RoutedEventArgs e)
{
    txtVersion.Text = this.GetType().Name;
    AlternateSlices = true;
    SliceCount = DefaultSliceCount;
    txtSliceCount.Text = Convert.ToString(SliceCount);

    SliceRotationAngle = DefaultSliceRotationAngle;
    txtRotation.Text = Convert.ToString(SliceRotationAngle);

    RadiusX = SpinningCanvas.Width / 2.0;
    RadiusY = SpinningCanvas.Height / 2.0;
    Origin = new Point(RadiusX, RadiusY);

    Update();
}

Step 3: Create a background circle (ellipse)

I used a simple linear gradient for now because the final gradient looks much more complicated and will take more time.

void CreateBackground(Canvas cursorCanvas)
{
    GradientBrush brush = new LinearGradientBrush();
    GradientStop stop1 = new GradientStop();
    stop1.Color = Color.FromArgb(255, 255, 0, 0);
    stop1.Offset = 0.25;
    brush.GradientStops.Add(stop1);

    GradientStop stop2 = new GradientStop();
    stop2.Color = Color.FromArgb(255, 0, 255, 0);
    stop2.Offset = 0.5; // cursorCanvas.Width / 2.0;
    brush.GradientStops.Add(stop2);

    GradientStop stop3 = new GradientStop();
    stop3.Color = Color.FromArgb(255, 0, 0, 255);
    stop3.Offset = 0.75; // cursorCanvas.Width;
    brush.GradientStops.Add(stop3);

    Ellipse ellipse = new Ellipse();
    ellipse.Height = cursorCanvas.Height;
    ellipse.Width = cursorCanvas.Width;
    ellipse.Fill = brush;
    cursorCanvas.Children.Add(ellipse);
}

Step 4: Implement the alternating slices

Implementing the alternating slices was simple:

/// <summary>
/// Create an ellipse using rotated slices to build the ellipse
/// </summary>
void CreateSlicePaths(Canvas cursorCanvas)
{
    // Create Slices
    for (int index = 0; index < SliceCount; ++index)
    {
        PathFigure pathFigure = CreateSliceFigure();

        PathGeometry pathGeometry = new PathGeometry();
        pathGeometry.Figures.Add(pathFigure);

        Path path = new Path();
        path.Stroke = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0));
        path.StrokeThickness = 1.0;
        path.Fill = new SolidColorBrush(Color.FromArgb(192, 128, 128, 128));
        path.Data = pathGeometry;

        // Rotate the slice for all slices after the first slice
        if (index > 0)
        {
            RotateTransform t1 = new RotateTransform();
            t1.CenterX = RadiusX;
            t1.CenterY = RadiusY;
            t1.Angle = SliceCenterAngle * index;

            TransformGroup transformGroup = new TransformGroup();
            transformGroup.Children.Add(t1);
            path.RenderTransform = transformGroup;
        }

        cursorCanvas.Children.Add(path);

        if (AlternateSlices)
            ++index;
    }
}

Step 5: Add the curvature to the slices

The curvature isn't perfect, but it looks fine with the default settings (10 slices and 36° rotation). I used a Bezier curve, but perhaps the standard arc would work better in the future.

// Curve control weighting
double curveWeight = 0.75;

// Create the first line
BezierSegment seg1 = new BezierSegment();
seg1.Point1 = point0;
seg1.Point2 = CalculatePointOnEllipse(0.0, RadiusX * curveWeight, RadiusY * curveWeight, Origin);
seg1.Point3 = point1;
pathFigure.Segments.Add(seg1);

// Use an arc for the circular side
ArcSegment seg2 = new ArcSegment();
seg2.Point = point2;
seg2.Size = new Size(RadiusX, RadiusY);
seg2.RotationAngle = SliceCenterAngle;
seg2.IsLargeArc = (SliceCenterAngle > 180.0);
seg2.SweepDirection = SweepDirection.Counterclockwise;
pathFigure.Segments.Add(seg2);

// Close shape by going back to the starting point
BezierSegment seg3 = new BezierSegment();
seg3.Point1 = point2;
seg3.Point2 = CalculatePointOnEllipse(SliceCenterAngle, RadiusX * curveWeight, RadiusY * curveWeight, Origin);
seg3.Point3 = point0;
pathFigure.Segments.Add(seg3);

Conclusion

The spinning cursor now has a dynamic number of slices and rotation angle, and it is starting to look more like the desired result. In the next post, I will animate the cursor to give it the spinning effect.

Technorati tags: ,
kick it on DotNetKicks.com

posted @ Wednesday, October 29, 2008 11:16 AM | Feedback (3) | Filed Under [ C# SilverLight ]

Monday, October 20, 2008

Spinning Wait Symbol in Silverlight, Part 2

After my previous spinning wait symbol, I decided to see how difficult it would be to create a Silverlight version of the Mac OSX wait cursor that I referenced in the previous post. The Mac OSX cursor is commonly referred to as the "Spinning Pizza of Death" or the "Marble of Doom" and in fact there is a Marble of Doom web site dedicated to the amount of time spent waiting while watching the spinning cursor. The Marble of Doom web site has a very nice and large version of the cursor using Flash although it doesn't have any vector information but is using video frames (they probably just published the final product and did not include the vector/animation information). The purpose of this post is to programmatically build the cursor and then in later posts to animate it.

Step 1: Decide on the initial interface properties

I realized quickly that I would need a little geometry to programmatically build the cursor, but the first step was to build the interface requirements. The essential properties were:

public int SliceCount { get; set; }
public double SliceCenterAngle { get; private set; }
public double SliceRotationAngle { get; set; }
public double RadiusX { get; set; }
public double RadiusY { get; set; }

The SliceCount determines how many slices or divisions to create, and the SliceCenterAngle is simply 360° / SliceCount. The SliceRotationAngle is the angle to twist or bend the slice. I decided to have a RadiusX and RadiusY to support ellipses in the future as well.

Step 2: Manually create a slice

Manual slice in Blend Before I could programmatically create a slice, I needed to find out how to create a slice using XAML and Blend. The points on the slice would be in the center of the circle, and then two points on the circle determined by the SliceCenterAngle. The biggest question was how to create the arc and maintain the circular appearance. Fortunately, the Geometry Overview on MSDN was very helpful and got me started on the right track with the PathGeometry. I was able to create the simplest scenario with a single slice from a circle with four slices:

<Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigure StartPoint="50,50">
                    <PathFigure.Segments>
                        <LineSegment Point="0,50" />
                        <ArcSegment Size="50,50" IsLargeArc="False"
                            RotationAngle="90" SweepDirection="CounterClockwise" Point="50,100" />
                        <LineSegment Point="50,50" />
                    </PathFigure.Segments>
                </PathFigure>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

The next step was to create the same quarter-circle except with two slices:

<Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigure StartPoint="50,50">
                    <PathFigure.Segments>
                        <LineSegment Point="0,50" />
                        <ArcSegment
                            Size="50,50"
                            Point="14.645,85.355" 
                            RotationAngle="45" 
                            IsLargeArc="False"
                            SweepDirection="CounterClockwise" 
                        />
                        <LineSegment Point="50,50" />
                    </PathFigure.Segments>
                </PathFigure>
                
                <PathFigure StartPoint="50,50">
                    <PathFigure.Segments>
                        <LineSegment Point="14.645,85.355" />
                        <ArcSegment
                            Size="50,50"
                            Point="50, 100" 
                            RotationAngle="45" 
                            IsLargeArc="False"
                            SweepDirection="CounterClockwise" 
                        />
                        <LineSegment Point="50,50" />
                    </PathFigure.Segments>
                </PathFigure>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

Step 3: Create a slice programmatically

The general idea is to create one slice and then rotate the slice around the circle to create the complete circle.

/// <summary>
/// Create an ellipse using rotated slices to build the ellipse
/// </summary>
void CreateSlicePaths(Canvas cursorCanvas)
{
    SliceCenterAngle = 360.0 / SliceCount;

    // Create Slices
    for (int index = 0; index < SliceCount; ++index)
    {
        PathFigure pathFigure = CreateSliceFigure();

        PathGeometry pathGeometry = new PathGeometry();
        pathGeometry.Figures.Add(pathFigure);

        Path path = new Path();
        path.Stroke = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
        path.StrokeThickness = 1.0;
        path.Data = pathGeometry;

        // Rotate the slice for all slices after the first slice
        if (index > 0)
        {
            RotateTransform t1 = new RotateTransform();
            t1.CenterX = RadiusX;
            t1.CenterY = RadiusY;
            t1.Angle = SliceCenterAngle * index;

            TransformGroup transformGroup = new TransformGroup();
            transformGroup.Children.Add(t1);
            path.RenderTransform = transformGroup;
        }

        cursorCanvas.Children.Add(path);
    }
}

/// <summary>
/// Create the base shape for the slice
/// </summary>
private PathFigure CreateSliceFigure()
{
    // Start at the center of the ellipse
    Point point0 = new Point(RadiusX, RadiusY);

    // Next point is the left side of the ellipse
    //Point point1 = new Point(0.0, RadiusY); // if no rotation
    Point point1 = CalculatePointOnEllipse(SliceRotationAngle);

    // Calculate the bottom point on the ellipse
    Point point2 = CalculatePointOnEllipse(SliceRotationAngle + SliceCenterAngle);

    // Starting point
    PathFigure pathFigure = new PathFigure();
    pathFigure.StartPoint = point0;

    // Create the first line
    LineSegment seg1 = new LineSegment();
    seg1.Point = point1;
    pathFigure.Segments.Add(seg1);

    // Use an arc for the circular side
    ArcSegment seg2 = new ArcSegment();
    seg2.Point = point2;
    seg2.Size = new Size(RadiusX, RadiusY);
    seg2.RotationAngle = SliceCenterAngle;
    seg2.IsLargeArc = (SliceCenterAngle > 180.0);
    seg2.SweepDirection = SweepDirection.Counterclockwise;
    pathFigure.Segments.Add(seg2);

    // Close shape by going back to the starting point
    LineSegment seg3 = new LineSegment();
    seg3.Point = new Point(point0.X, point0.Y);
    pathFigure.Segments.Add(seg3);

    pathFigure.IsClosed = true;
    pathFigure.IsFilled = true;

    return pathFigure;
}

/// <summary>
/// Returns a point on the ellipse based on the rotationAngle, using
/// RadiusX/Y as the center (0, 0).
/// </summary>
private Point CalculatePointOnEllipse(double rotationAngle)
{
    double angleRadians = rotationAngle * Math.PI / 180.0;
    double x = Math.Cos(angleRadians);
    x = RadiusX * x;
    double y = Math.Sin(angleRadians);
    y = RadiusY * y;

    Point result = new Point(x, y);
    result.X = RadiusX - x;
    result.Y = RadiusY + y;
    return result;
}

Step 4: Going Forward

SpinningCursor1-TestPage Obviously this still needs a lot of improvement before it approaches the appeal of the Marble of Doom, which I will work on in the coming posts. However, the initial effort to create the "pizza" slices has been achieved and it is easier to build upon a base.

I added a grid in the background when I had some difficulty with the path geometry, but it is useful to I added two text boxes for the number of slices and rotation angle so that I could see the shape update dynamically.

Since I just used LineSegments to connect the slice points, the shape does not have the swirl or twist effect yet. Next time I will add the twist as well as rotation.

Technorati tags: ,

kick it on DotNetKicks.com

posted @ Monday, October 20, 2008 3:08 PM | Feedback (0) | Filed Under [ C# Programming SilverLight ]

Wednesday, October 08, 2008

Spinning Wait Symbol in Silverlight

My wife has a Treo with Windows Mobile and I when I was using it I noticed it had a cool rotating wait symbol, so I wondered how difficult it would be to build the symbol in Silverlight. The symbol is similar to the old BeOS wait cursor and has as well as the Mac OS X wait cursor which I've always thought looks nice. At one point in time I created a Windows cursor that duplicated the look of the BeOS cursor but I don't use it anymore. If I found a really nice looking 24-bit cursor then I might use it again.

Quadrant1The first step is to create the four quadrants. I used the path geometry to create each quadrant, for example the first quadrant is:

Data="M0,0 C0,0 100,0 100,100 L0,100 z"

For reference , the path markup syntax is documented at MSDN. The shape starts at (0,0) and creates a curve point with a control point at (100,0) and end point at (100,100). Then there is a LineTo (0,100) and finally the close ("z") marker to complete the shape. While this is fairly easy through a graphical editor such as Expression Blend (blog), I created this manually so that I could have more control over the exact coordinates rather than relying on the graphical editor.

I repeated the shape for each quadrant by adjusting the coordinates as necessary. It is also possible to simply apply a rotation to the shape so you have rotations of 90, 180, and 270 degrees, but remember to set the RenderTransformOrigin to the correct corner such as (0,1) to rotate by the bottom left corner.

Once the quadrants are built, then I placed a rotating quadrant named 'Spinner' over the combined shape. I used an alpha mask on the spinner to differentiate it from the other quadrants. Finally, I added a Storyboard to rotate the 'Spinner' 360 degrees every two seconds:

<Storyboard x:Name="SpinStoryboard" RepeatBehavior="Forever">
  <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="Spinner"
      Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)">
    <SplineDoubleKeyFrame KeyTime="00:00:02" Value="360"/>
  </DoubleAnimationUsingKeyFrames>
</Storyboard>

The end result is a nice looking animation that is fairly simple. I'm tempted to try to duplicate the Mac OS X wait cursor, but that will have to wait until I have more time.

Spinning Cursor in Blend

kick it on DotNetKicks.com
Technorati tags:

posted @ Wednesday, October 08, 2008 8:03 AM | Feedback (0) | Filed Under [ C# SilverLight ]

Sunday, September 14, 2008

Bouncing Balls in Silverlight Part 1

BounceTest

Recently I wanted to make a very simple sample in Silverlight that used a little code to animate bouncing balls. The overall effect is fairly simple, but getting the sample down to the basics took a little time. As part of my research, I looked at several old bouncing ball demos using JavaScript and it was an eye-opening reminder of the dark ages of browsers and JavaScript.

For the sample, I wanted to keep everything very simple. I started with a circle (ellipse with the same height and width) in a canvas. In order to move the ball, I chose to position the ball at (0, 0) and use a TranslateTransform to adjust the position. You could easily move the ball around with Left and Top, but I also plan to use RotateTransform in later samples so it makes sense to use a TransformGroup to manipulate the object.

The XAML for the base page is just a Canvas and a rectangle that acts as a border. The ball is placed on the canvas using the common TransformGroup that is created by Expression Blend when you add a transform to an object. Expression Blend also uses the same order for the transforms (ScaleTransform, SkewTransform, RotateTransform, TranslateTransform) and will reorder the transforms back to this order if you adjust any transform using Blend (at least as of Blend 2.5 June 2008 Preview). Here is the XAML for the page:

<UserControl x:Class="BounceTest.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot">
        <Rectangle x:Name="Boundary" Height="300" Width="400" 
            Canvas.Left="0" Canvas.Top="0"
            Fill="#FFFFFFFF" Stroke="#FF000000" />
        <Ellipse x:Name="Ball01" Height="25" Width="25"
            Canvas.Left="0" Canvas.Top="0"
            Fill="#FFEE3131" Stroke="#FF000000"
            RenderTransformOrigin="0.5,0.5">
            <Ellipse.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform X="50" Y="50"/>
                </TransformGroup>
            </Ellipse.RenderTransform>
        </Ellipse>
    </Canvas>
</UserControl>

I created a small class to manage the position and velocity of the ball. The constructor takes the source shape (the ball), the velocity, and the boundary shape. For this scenario, I assume that the ball already has the RotateTransform otherwise it throws an exception. The code could easily create a RotateTransform if it isn't present. The Update method takes the elapsed time since the previous method call. The boundary checking is extremely simple and just changes the direction of the motion when the ball hits a boundary edge. This obviously needs a lot of work for more complex scenarios, but it will do for this simple case.

public class ShapeVelocity
{
	public Shape shape;
	public Vector velocity;
	public TranslateTransform translate;
	public Size bounds;
	public Size container;

	public ShapeVelocity(Shape AShape, Vector AVelocity, Shape BoundsContainer)
	{
		this.shape = AShape;
		this.velocity = AVelocity;

		var renderTransform = this.shape.RenderTransform;
		if (renderTransform is TransformGroup)
		{
			TransformGroup transformGroup = (TransformGroup)renderTransform;
			foreach (Transform transform in transformGroup.Children)
				if (transform is TranslateTransform)
					this.translate = (TranslateTransform)transform;
		}
		if (this.translate == null)
			throw new ArgumentException("Shape must have a TranslateTransform in it");

		container = new Size(BoundsContainer.Width, BoundsContainer.Height);
		bounds = new Size(
			this.shape.ActualWidth + this.shape.StrokeThickness,
			this.shape.ActualHeight + this.shape.StrokeThickness);
	}

	public void Update(TimeSpan Interval)
	{
		Rect pos = new Rect(
			translate.X,
			translate.Y,
			bounds.Width,
			bounds.Height);

		if ((velocity.X < 0.0) && (pos.Left < 0.0))
			velocity.X = -velocity.X;
		else if ((velocity.X > 0.0) && (pos.Right > container.Width))
			velocity.X = -velocity.X;
		if ((velocity.Y < 0.0) && (pos.Top < 0.0))
			velocity.Y = -velocity.Y;
		else if ((velocity.Y > 0.0) && (pos.Bottom > container.Height))
			velocity.Y = -velocity.Y;

		translate.X += velocity.X * (double) Interval.Milliseconds / 1000.0;
		translate.Y += velocity.Y * (double) Interval.Milliseconds / 1000.0;
	}
}

In anticipation of future examples, I used a List<Shape> collection to store the ball shape to updae the position. For the motion, I used the StoryBoard instead of a DispatcherTimer based on the recommendation of Adam Kinney.

public partial class Page : UserControl
{
    private DateTime _lastTime = DateTime.MinValue;
    private double _initialSpeed = 50.0;
    private Storyboard _storyboard;
    private List<ShapeVelocity> _shapes;

    public Page()
    {
        InitializeComponent();
        _shapes = new List<ShapeVelocity>();
        _storyboard = new Storyboard();
        _storyboard.Duration = TimeSpan.FromMilliseconds(10);
        _storyboard.Completed += new EventHandler(storyboard_Tick);
        this.Loaded += new RoutedEventHandler(Page_Loaded);
    }

    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        _shapes.Add(new ShapeVelocity(Ball01, new Vector(_initialSpeed, _initialSpeed), Boundary));
        _lastTime = System.DateTime.Now;
        _storyboard.Begin();
    }

    void storyboard_Tick(object sender, EventArgs e)
    {
        DateTime now = System.DateTime.Now;
        TimeSpan interval = now - _lastTime;
        foreach (ShapeVelocity s in _shapes)
        {
            s.Update(interval);
        }
        _lastTime = now;
        _storyboard.Begin();
    }
}

So that is the very simple bouncing ball sample.

Get Microsoft Silverlight