Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Friday, April 26, 2013

Exploring Riak with F# and CorrugatedIron

Many thanks to David and OJ for recommending CorrugatedIron .Net Riak client library. The following blog entry is to document my experiments with Riak CRUD operations using CorrugatedIron.

Pinging RIAK

I tested CorrugatedIron with F# script and here is the setup code along with testing ping capability:

// Needed to load the following libraries to get F# script to work
#r @"c:\dev\FsRiak\packages\CorrugatedIron.1.3.0\lib\net40\CorrugatedIron.dll"
#r @"c:\dev\FsRiak\packages\protobuf-net.2.0.0.621\lib\net40\protobuf-net.dll"
#r @"c:\dev\FsRiak\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll"

open CorrugatedIron
open CorrugatedIron.Models
open Newtonsoft.Json
open System

// Setup connections
let cluster = RiakCluster.FromConfig("riakConfig", @"c:\dev\FsRiak\App.config");
let client = cluster.CreateClient();

// Ping the Riak Cluster
client.Ping()

Here is my App.config file used by CorrugatedIron:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="riakConfig" type="CorrugatedIron.Config.RiakClusterConfiguration, CorrugatedIron" />
  </configSections>
  <riakConfig nodePollTime="5000" defaultRetryWaitTime="200" defaultRetryCount="3">
    <nodes>
      <node name="dev1"  hostAddress="mydevhost-a" pbcPort="8087" restScheme="http" restPort="8098" poolSize="10" />
      <node name="dev2" hostAddress="mydevhost-b" pbcPort="8087" restScheme="http" restPort="8098" poolSize="10" />
      <node name="dev3" hostAddress="mydevhost-c" pbcPort="8087" restScheme="http" restPort="8098" poolSize="10" />
    </nodes>
  </riakConfig>
</configuration>

Here's the result from running ping:

val it : RiakResult = CorrugatedIron.RiakResult {ErrorMessage = null;
                                                 IsSuccess = true;
                                                 ResultCode = Success;}

Get List of Buckets

The following method call gets you the list of buckets along with metadata for the call status:

client.ListBuckets()

This method returns the following RiakResult object:

val it : RiakResult<seq<string>> =
  CorrugatedIron.RiakResult`1[System.Collections.Generic.IEnumerable`1[System.String]]
    {ErrorMessage = null;
     IsSuccess = true;
     ResultCode = Success;
     Value = seq ["photos"; "favs"; "animals"; "cages"; ...];}

Get Bucket Keys

Getting a list of keys for a bucket is also simple:

client.ListKeys("animals")

For the novice, this library warns you to not to do this in production environments....

*** [CI] -> ListKeys is an expensive operation and should not be used in Production scenarios. ***
val it : RiakResult<seq<string>> =
  CorrugatedIron.RiakResult`1[System.Collections.Generic.IEnumerable`1[System.String]]
    {ErrorMessage = null;
     IsSuccess = true;
     ResultCode = Success;
     Value = seq ["ace"; "polly"];}

Retrieve Content from Riak

Getting a value from Riak is pretty easy with this library:

client.Get("animals","ace")

A dump of the return object shows the actual data plus metadata about the Get operation:

val it : RiakResult<Models.RiakObject> =
  CorrugatedIron.RiakResult`1[CorrugatedIron.Models.RiakObject]
    {ErrorMessage = null;
     IsSuccess = true;
     ResultCode = Success;
     Value = CorrugatedIron.Models.RiakObject;}

A deeper dive into the Value field of RiakResult object gives the following:

val it : Models.RiakObject =
  CorrugatedIron.Models.RiakObject
    {BinIndexes = dict [];
     Bucket = "animals";
     CharSet = null;
     ContentEncoding = null;
     ContentType = "application/json";
     HasChanged = false;
     IntIndexes = dict [];
     Key = "ace";
     LastModified = 1359744019u;
     LastModifiedUsec = 788127u;
     Links = seq [];
     Siblings = seq [];
     UserMetaData = dict [];
     VTag = "7aPFusRQHlQ36ZP6G6GSyE";
     VTags = seq ["7aPFusRQHlQ36ZP6G6GSyE"];
     Value = [|123uy; 32uy; 34uy; 110uy; 105uy; 99uy; 107uy; 110uy; 97uy;
               109uy; 101uy; 34uy; 32uy; 58uy; 32uy; 34uy; 84uy; 104uy; 101uy;
               32uy; 87uy; 111uy; 110uy; 100uy; 101uy; 114uy; 32uy; 68uy;
               111uy; 103uy; 34uy; 32uy; 44uy; 32uy; 34uy; 98uy; 114uy; 101uy;
               101uy; 100uy; 34uy; 32uy; 58uy; 32uy; 34uy; 71uy; 101uy; 114uy;
               109uy; 97uy; 110uy; 32uy; 83uy; 104uy; 101uy; 112uy; 104uy;
               101uy; 114uy; 100uy; 34uy; 32uy; 125uy|];
     VectorClock = [|107uy; 206uy; 97uy; 96uy; 96uy; 96uy; 204uy; 96uy; 202uy;
                     5uy; 82uy; 28uy; 172uy; 90uy; 225uy; 175uy; 2uy; 57uy;
                     59uy; 156uy; 51uy; 152uy; 18uy; 25uy; 243uy; 88uy; 25uy;
                     132uy; 59uy; 26uy; 78uy; 241uy; 101uy; 1uy; 0uy|];}

The data I really wanted is embedded in another Value field where it is represented as an array of bytes, which is not the final format I want. I wanted to get back the JSON representation of the data I put in. In my previous blog, I had rolled my own JSON serializer/deserializer, but now I wanted to leverage the other pieces of library bundle by CorrugateIron, namely Json.NET. To do so,I define the Animal type and use Json.NET serializer/deserializer to convert between the objects and it's corresponding JSON representation

type Animal =
    { nickname: string; breed: string}

// Getting ace from animals bucket 
client.Get("animals","ace").Value.GetObject<Animal>() 

Adding Content to Riak

Adding content to Riak is pretty easy also, after you define a specific type for Json.NET to serialize the fields of that type:

new RiakObject("animals","delta",{nickname="Snoopy"; breed="Beagle"}) 
|> client.Put

If you dump the RiakResult object and the Value field of RiakResult you get the following:


val it : RiakResult =
  CorrugatedIron.RiakResult`1[CorrugatedIron.Models.RiakObject]
    {ErrorMessage = null;
     IsSuccess = true;
     ResultCode = Success;
     Value = CorrugatedIron.Models.RiakObject;}
  
val it : RiakObject =
  CorrugatedIron.Models.RiakObject
    {BinIndexes = dict [];
     Bucket = "animals";
     CharSet = null;
     ContentEncoding = null;
     ContentType = "application/json";
     HasChanged = false;
     IntIndexes = dict [];
     Key = "delta";
     LastModified = 1366930771u;
     LastModifiedUsec = 271921u;
     Links = seq [];
     Siblings = seq [];
     UserMetaData = dict [];
     VTag = "OvZlH7bsYKdO8zL76QdDY";
     VTags = seq ["OvZlH7bsYKdO8zL76QdDY"];
     Value = [|123uy; 34uy; 110uy; 105uy; 99uy; 107uy; 110uy; 97uy; 109uy;
               101uy; 34uy; 58uy; 34uy; 83uy; 110uy; 111uy; 111uy; 112uy;
               121uy; 34uy; 44uy; 34uy; 98uy; 114uy; 101uy; 101uy; 100uy; 34uy;
               58uy; 34uy; 66uy; 101uy; 97uy; 103uy; 108uy; 101uy; 34uy; 125uy|];
     VectorClock = [|107uy; 206uy; 97uy; 96uy; 96uy; 96uy; 204uy; 96uy; 202uy;
                     5uy; 82uy; 28uy; 169uy; 111uy; 239uy; 241uy; 7uy; 114uy;
                     230uy; 184uy; 103uy; 48uy; 37uy; 50uy; 230uy; 177uy; 50uy;
                     4uy; 27uy; 190uy; 59uy; 197uy; 151uy; 5uy; 0uy|];}

To verify interoperability, I would check the newly added data with curl:

$ curl -X GET http://192.168.56.1:8098/riak/animals/delta
$ {"nickname":"Snoopy","breed":"Beagle"}

Delete Riak Contents

Delete content by calling the intuitively named Delete method:

client.Delete("animals","delta")

One thing that I wasn't sure is how CorrugatedIron talks to the Riak clusters. In my simple REST API example, I know exactly which host I'm talking to since I explicitly specified the url. For CorrugatedIron, I configure a pool of connections in the app.config file. I wasn't sure which of the nodes CorrugatedIron was talking to. I fire up Wireshark and notice that I'm connected to the Riak cluster via port 8087, which is through the Protocol Buffers Client (PBC) interface...which explains the need to load the PBC libraries. This Protocol Buffers client is something new to me and the bundled protobuf-net library seemed to be the code developed by Google (Many thanks to OJ for correcting me on this, this is NOT a Google library but a library written by Marc Gravell). This, in turn led me to look at Google Protocol Buffers . This little side jaunt into CorrugatedIron library led to the discovery (for me) of a whole new set of network communication protocols. In any case, after checking Wireshark output, it seems that the requests are spread out to the different nodes and not restricted to a single node. I'm guessing that there are some builtin load balancer code in CorrugatedIron that sends my request to different nodes in the Riak cluster.

For the basic CRUD operations on Riak, CorrugatedIron has made it easier to work with Riak then having to come up with my own helper functions. This has been a good start and I hope work through more of the Riak examples from the book Seven Databases in Seven Weeks with CorrugatedIron in future blog posts.

Tuesday, February 21, 2012

Coding for reuse versus coding for specific use

One day, a C# developer came to me asked me to troubleshoot their application, which involves some data transformation code. In the course of troubleshooting this particular application's runtime issue, I saw this particular code implementation:

private string[] SplitTextwithSpecialCharacter(string lineFromGUI, int splitLength) 
{

    List<string> lines = new List<string>();
    int start = 0;


    while (start < lineFromGUI.Length)
    {
        string temp = string.Empty;
      
        //if length is longer it will throw exception so size the last segment appropriately
        string line = lineFromGUI.Substring(start, Math.Min(splitLength, lineFromGUI.Length - start));
        
        //temp = line.Replace(SpecialCharacter, string.Empty);

        temp = line.Replace("^", ""); //New 6/30
        if (temp.Length > 0) 
        {
            //lines.Add(line.Replace(SpecialCharacter, string.Empty));
            lines.Add(temp);
        }
        //lines.Add(line);
        start += splitLength;
    }
    return lines.ToArray();
}

When I saw this code, I inwardly cringed due to the very narrow scope in the code implementation to solve a seemingly generic problem. This code screams for refactoring to me. From the commented out section of the code, I could see that one of the developers tried to implement some reuse before reverting back to the specific use.

I see a couple of issues with this particular implementation. The first issue being that this method is trying to do two very different things; one is trying to split the text into lines and the second is removing all the caret characters from the text. In my opinion, these 2 different operations should be separated out into 2 different methods. The second issue is that the caret character removal function should be generalized such that you should be able to remove any character or perhaps even a set of characters beyond just the caret symbol. In the specific implementation, what would happen if they needed code to remove an asterisk instead of caret? What would happen if they need to remove more than one special character? Do they add additional methods? Do they modify the existing method? If they modify the existing method to take parameters, then they would have to change all the existing client code that calls this method. So it would seem to be easier for future maintenance to go ahead and make these 2 functions reusable.

Here's how I would refactor this particular method into some utilities namespace and use extension methods to add capability to the string object. Here's how that code would look like:

public static class Extensions
{
    public static string FilterOut(this string line, ISet<char> filter)
    {

        if (line == null ||  filter == null || filter.Count == 0) return line;


        return new String(line.Where(c => !filter.Contains(c)).ToArray());
    }


    public static IList<string> SplitIntoLines(this string data, int splitLength) 
    {

        // Check preconditions
        if (data == null) throw new NullReferenceException();

        if (splitLength <= 0) throw new IndexOutOfRangeException("Must be greater than 0!");

        IList<string> lines = new List<string>();

        while (data.Length > splitLength)
        {
            string line = data.Substring(0,splitLength);
            data = data.Substring(splitLength, data.Length-splitLength);
            lines.Add(line);
        }
        lines.Add(data);
        return lines;
    }
}

With this extension method, you can now use this utility method as follows:

int linesize = 30;
ISet<char> filter = new HashSet<char> { '^', '*', '&', '$' };
string[] results = data.SplitIntoLines(linesize)
                       .Select(line => line.FilterOut(filter))
                       .ToArray();

Wednesday, April 01, 2009

Silverlight with F#: Animation via XAML (revisited)

I should have took the time to read Matthew MacDonald’s book Pro Silverlight 2 in C# 2008 before I started tackling recipe 2.11 in the book Silverlight 2 Recipes.  The code I created in the last blog post was made more complex due to my poor workaround to extracting the Storyboard object from XAML.  After reading chapter 2 of the book Pro Silverlight 2 in C# 2008, it was obvious that in order to extract the Storyboard object from XAML, all I had to do was add the Key attribute to the Storyboard markup and add the Storyboard markup to the Grid.Resources property. 

In addition, I’m reading through Chapter 13 of Don Syme’s book Expert F# trying to understand more how concurrency works with F#.  I decided to try to replicate the Iterative Worker example in the book, replacing the simple BackgroundWorker example in recipe 2.11.

Here is the revised code with Storyboard as part of the resources of the Grid object and the reworked background worker code.


#light
namespace SilverLightFSharp

open System
open System.ComponentModel
open System.ServiceModel
open System.Windows
open System.Windows.Browser
open System.Windows.Controls
open System.Windows.Markup
open System.Windows.Media
open System.Windows.Media.Animation
open System.Windows.Shapes
open List

// SimulateBackgroundWorker modelled after
// IterativeBackgroundWorker example from Chapter 13 of Expert F#
type SimulateBackgroundWorker<'a>(delay:int, numIterations:int) =
let worker = new BackgroundWorker(WorkerReportsProgress=true,
WorkerSupportsCancellation=true)
let triggerCompleted,completed = Event.create()
let triggerError ,error = Event.create()
let triggerCancelled,cancelled = Event.create()
let triggerProgress ,progress = Event.create()

do worker.DoWork.Add(fun args ->
let rec iterate i =
if worker.CancellationPending then
args.Cancel <- true
elif i < numIterations then
System.Threading.Thread.Sleep(delay)

// Report the percentage computation
let percent = int((float (i+1)/float numIterations) * 100.0)
do worker.ReportProgress(percent)
iterate (i+1)
else ()
iterate 0)

do worker.RunWorkerCompleted.Add(fun args ->
if args.Cancelled then triggerCancelled()
elif args.Error<> null then triggerError args.Error
else triggerCompleted())

do worker.ProgressChanged.Add(fun args ->
triggerProgress(args.ProgressPercentage))

member x.WorkerCompleted = completed
member x.WorkerCancelled = cancelled
member x.WorkerError = error
member x.ProgressChanged = progress

// Delegate the remaining memebers to the underlying worker
member x.RunWorkerAsync() = worker.RunWorkerAsync()
member x.CancelAsync() = worker.CancelAsync()
member x.IsBusy = worker.IsBusy




// Recipe 2-11 from Silverlight 2 Recipes book
// Using XAML to configure the animation
type MyPage() = class
inherit UserControl()

do
// added x:Key='AnimateStatusEllipse' to Storyboard
let xamlControls =
"<Grid
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
x:Name='LayoutRoot' Background='#FFFFFFFF'>
<Grid.Resources>
<Storyboard x:Name='AnimateStatusEllipse' x:Key='AnimateStatusEllipse'>
<ColorAnimationUsingKeyFrames BeginTime='00:00:00' Storyboard.TargetName='StatusEllipse'
Storyboard.TargetProperty='(Shape.Fill).(SolidColorBrush.Color)'>
<SplineColorKeyFrame KeyTime='00:00:00' Value='#FF008000'/>
<SplineColorKeyFrame KeyTime='00:00:01.5000000' Value='#FFFFFF00'/>
<SplineColorKeyFrame KeyTime='00:00:03' Value='#FF008000'/>
<SplineColorKeyFrame KeyTime='00:00:04.5000000' Value='#FF008000'/>
<SplineColorKeyFrame KeyTime='00:00:06' Value='#FFFFFF00'/>
<SplineColorKeyFrame KeyTime='00:00:07.5000000' Value='#FF008000'/>
</ColorAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime='00:00:00' Storyboard.TargetName='StatusEllipse'
Storyboard.TargetProperty='(UIElement.Opacity)'>
<SplineDoubleKeyFrame KeyTime='00:00:00' Value='0.7'/>
<SplineDoubleKeyFrame KeyTime='00:00:01.5000000' Value='0.5'/>
<SplineDoubleKeyFrame KeyTime='00:00:03' Value='0.5'/>
<SplineDoubleKeyFrame KeyTime='00:00:04.5000000' Value='0.7'/>
<SplineDoubleKeyFrame KeyTime='00:00:06' Value='0.5'/>
<SplineDoubleKeyFrame KeyTime='00:00:07.5000000' Value='0.5'/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime='00:00:00' Storyboard.TargetName='StatusEllipse'
Storyboard.TargetProperty='(UIElement.RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleX)'>
<SplineDoubleKeyFrame KeyTime='00:00:00' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:01.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:03' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:04.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:06' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:07.5000000' Value='0'/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime='00:00:00' Storyboard.TargetName='StatusEllipse'
Storyboard.TargetProperty='(UIElement.RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)'>
<SplineDoubleKeyFrame KeyTime='00:00:00' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:01.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:03' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:04.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:06' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:07.5000000' Value='0'/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='0.068*'/>
<ColumnDefinition Width='0.438*'/>
<ColumnDefinition Width='0.495*'/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='0.08*'/>
<RowDefinition Height='0.217*'/>
<RowDefinition Height='0.61*'/>
<RowDefinition Height='0.093*'/>
</Grid.RowDefinitions>
<Button HorizontalAlignment='Stretch' Margin='5,8,5,8' VerticalAlignment='Stretch'
Grid.Column='1' Grid.Row='1' Content='Save Form Data'/>
<StackPanel HorizontalAlignment='Stretch' Margin='4.8270001411438,8,6.19799995422363,8'
Grid.Column='1' Grid.Row='2'>
<TextBlock Height='Auto' Width='Auto' Text='Work Results Appear Below' TextWrapping='Wrap' Margin='4,4,4,4'/>
<TextBox Height='103' Width='Auto' Text='' TextWrapping='Wrap' Margin='4,4,4,4' x:Name='WorkResultsTextData'/>
</StackPanel>
<Button HorizontalAlignment='Stretch' Margin='12,8,8,8' VerticalAlignment='Stretch' Grid.Column='2' Grid.Row='1' Content='Load Form Data'/>
<Button HorizontalAlignment='Stretch' Margin='10,2,8,6' VerticalAlignment='Stretch' Grid.Column='1' Grid.Row='3' Content='Kick Off Work' x:Name='DoWorkButton'/>
<Border Grid.Column='2' Grid.Row='2' Grid.RowSpan='2' CornerRadius='10,10,10,10' Margin='1.80200004577637,2,2,2'>
<Border.Background>
<LinearGradientBrush EndPoint='0.560000002384186,0.00300000002607703' StartPoint='0.439999997615814,0.996999979019165'>
<GradientStop Color='#FF586C57'/>
<GradientStop Color='#FFA3BDA3' Offset='0.536'/>
<GradientStop Color='#FF586C57' Offset='0.968999981880188'/>
</LinearGradientBrush>
</Border.Background>
<StackPanel Margin='4,4,4,4' x:Name='FormData'>
<TextBlock Height='Auto' Width='Auto' Text='First Name:' TextWrapping='Wrap' Margin='2,2,2,0'/>
<TextBox Height='Auto' Width='Auto' Text='' TextWrapping='Wrap' x:Name='Field1' Margin='2,0,2,4'/>
<TextBlock Height='Auto' Width='Auto' Text='Last Name:' TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='Auto' x:Name='Field2' Width='Auto' Text='' TextWrapping='Wrap' Margin='2,0,2,4'/>
<TextBlock Height='Auto' Width='Auto' Text='Company:' TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='Auto' x:Name='Field3' Width='Auto' Text='' TextWrapping='Wrap' Margin='2,0,2,2'/>
<TextBlock Height='22.537' Width='182' Text='Title:' TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='20.772' x:Name='Field4' Width='182' Text='' TextWrapping='Wrap' Margin='2,0,2,2'/>
</StackPanel>
</Border>
<Ellipse x:Name='StatusEllipse' Margin='4,2,2,2' Grid.Row='3' Stroke='#FF000000' Fill='#FF2D4DE0' RenderTransformOrigin='0.5,0.5' >
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
<ToolTipService.ToolTip>
<ToolTip Content='Click button to start work.' />
</ToolTipService.ToolTip>
</Ellipse>
<Canvas HorizontalAlignment='Stretch' Margin='0,0,2,8' Grid.RowSpan='4' Grid.ColumnSpan='3' x:Name='PromptCancelCanvas' Visibility='Collapsed'>
<Rectangle Height='300' Width='400' Fill='#FF808080' Stroke='#FF000000' Stretch='Fill' Opacity='0.6'/>
<Canvas Height='106' Width='289' Canvas.Left='46' Canvas.Top='85'>
<Rectangle Height='106' Width='289' Fill='#FFFFFFFF' Stroke='#FF000000' RadiusX='23' RadiusY='23' Opacity='0.85'/>
<Button Height='34' x:Name='ButtonConfirmCancelYes' Width='100' Canvas.Left='15' Canvas.Top='49' Content='Yes'/>
<Button Height='34' x:Name='ButtonConfirmCancelNo' Width='100' Canvas.Left='164' Canvas.Top='49' Content='No'/>
<TextBlock Width='134.835' Canvas.Left='75' Canvas.Top='12.463' Text='Cancel Operation?' TextWrapping='Wrap'/>
</Canvas>
</Canvas>
<TextBlock Margin='67.8270034790039,0,-88.802001953125,0' Grid.Column='1' Grid.ColumnSpan='1' Text='BackgroundWorker Thread' TextWrapping='Wrap'/>
</Grid>"

// Load xaml dynamically
let grid = XamlReader.Load(xamlControls) :?> Grid

// Find the controls...
let statusEllipse = grid.FindName("StatusEllipse") :?> Ellipse
let textarea = grid.FindName("WorkResultsTextData") :?> TextBox
let doWorkButton = grid.FindName("DoWorkButton") :?> Button
let cancelNoButton = grid.FindName("ButtonConfirmCancelNo") :?> Button
let cancelYesButton = grid.FindName("ButtonConfirmCancelYes") :?> Button
let cancelCanvas = grid.FindName("PromptCancelCanvas") :?> Canvas

// Grab storyboard from grid resources with the extra key specified..
let storyboard = grid.Resources.["AnimateStatusEllipse"] :?> Storyboard

// Remove code to add storyboard children objects...

// SimulateBackgroundWorker modelled after Don Syme's Iterative Background worker
let worker = new SimulateBackgroundWorker<_>(1000,30)

doWorkButton.Click.Add(fun e ->
worker.RunWorkerAsync()
textarea.Text <- sprintf "(2) Started : %s" (DateTime.Now.ToString())
storyboard.AutoReverse <- true
storyboard.RepeatBehavior <- RepeatBehavior.Forever
storyboard.Begin())

cancelYesButton.Click.Add(fun e ->
worker.CancelAsync()
cancelCanvas.Visibility <- Visibility.Collapsed)

cancelNoButton.Click.Add(fun e ->
cancelCanvas.Visibility <- Visibility.Collapsed)

statusEllipse.MouseLeftButtonDown.Add(fun e ->
if worker.IsBusy = true then
cancelCanvas.Visibility <- Visibility.Visible)

worker.WorkerCompleted.Add(fun () ->
statusEllipse.Fill <- new SolidColorBrush(Color.FromArgb(255uy,0uy,255uy,0uy))
let msg = sprintf "\nCompleted : %s" (DateTime.Now.ToString())
textarea.Text <- textarea.Text + msg
ToolTipService.SetToolTip(statusEllipse, "Work Complete.")
)

worker.ProgressChanged.Add(fun (progressPercentage) ->
if cancelCanvas.Visibility = Visibility.Collapsed then
let msg = sprintf "%i Percent Complete. Click to cancel..." progressPercentage
ToolTipService.SetToolTip(statusEllipse, msg))

worker.WorkerCancelled.Add(fun () ->
statusEllipse.Fill <- new SolidColorBrush(Color.FromArgb(255uy,255uy,255uy,0uy))
let msg = sprintf "%s \nCanceled@: %s" textarea.Text <| DateTime.Now.ToString()
textarea.Text <- msg
ToolTipService.SetToolTip(statusEllipse, msg))

base.Width <- 400.0
base.Height <- 300.0
base.Content <- grid
end

type ErrorPage = class
inherit UserControl

new (msg:string ) as this = {} then

let textarea = new TextBlock(Text=msg,
TextWrapping=TextWrapping.Wrap,
Margin=new Thickness(4.0,4.0,4.0,4.0))

let sp = new StackPanel(HorizontalAlignment = HorizontalAlignment.Stretch,
Margin=new Thickness(8.0,8.0,10.0,8.0))
sp.Children.Add(textarea)

base.Width <- 600.0
base.Height <- 1000.0
base.Content <- sp
end


type MyApp = class
inherit Application

new () as this = {} then
this.Startup.Add(fun _ ->
let rootPanel = new StackPanel()
try
this.RootVisual <- rootPanel
rootPanel.Children.Add(new MyPage())
with _ as e ->
let msg = e.Message + e.StackTrace
rootPanel.Children.Clear()
rootPanel.Children.Add(new ErrorPage(msg)))

this.UnhandledException.Add(fun args ->
args.Handled <- true
try
let msg = args.ExceptionObject.Message + args.ExceptionObject.StackTrace
let errmsg = msg.Replace('"','\'').Replace("\r\n",@"\n")
"throw new Error(\"Unhandled error in Silverlight 2 Application " + msg + "\");"
|> HtmlPage.Window.Eval |> ignore
with _ -> HtmlPage.Window.Eval("throw new Error(\"Custom Error!\");") |> ignore)
end

Sunday, March 22, 2009

Silverlight with F#: Animation via XAML

In my previous blog, I was unable to fully implement recipe 2.11 of the book Silverlight 2 Recipes with F# code due to problems with getting PropertyPath to work as shown in various Silverlight books.  Just to make sure that this is not just a Silverlight issue, I tried the code with WPF and still had the same problem.  I decided to approach this differently and implement the animation in XAML instead and got it to work.  Here’s the code:


#light
namespace SilverLightFSharp

open System
open System.ComponentModel
open System.IO
open System.IO.IsolatedStorage
open System.ServiceModel
open System.Windows
open System.Windows.Browser
open System.Windows.Controls
open System.Windows.Markup
open System.Windows.Media
open System.Windows.Media.Animation
open System.Windows.Shapes
open List

// Recipe 2-11 from Silverlight 2 Recipes book
// Using XAML to configure the animation
type MyPage() = class
inherit UserControl()

do
let xamlControls =
"<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='0.068*'/>
<ColumnDefinition Width='0.438*'/>
<ColumnDefinition Width='0.495*'/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='0.08*'/>
<RowDefinition Height='0.217*'/>
<RowDefinition Height='0.61*'/>
<RowDefinition Height='0.093*'/>
</Grid.RowDefinitions>
<Button HorizontalAlignment='Stretch' Margin='5,8,5,8'
VerticalAlignment='Stretch' Grid.Column='1' Grid.Row='1'
Content='Save Form Data'/>
<StackPanel HorizontalAlignment='Stretch'
Margin='5,8,6,8' Grid.Column='1' Grid.Row='2'>
<TextBlock Height='Auto' Width='Auto' Text='Work Results Appear Below'
TextWrapping='Wrap' Margin='4,4,4,4'/>
<TextBox Height='103' Width='Auto' Text='' TextWrapping='Wrap'
Margin='4,4,4,4' x:Name='WorkResultsTextData'/>
</StackPanel>
<Button HorizontalAlignment='Stretch' Margin='12,8,8,8'
VerticalAlignment='Stretch'
Grid.Column='2' Grid.Row='1' Content='Load Form Data' />
<Button HorizontalAlignment='Stretch' Margin='10,2,8,6'
VerticalAlignment='Stretch'
Grid.Column='1' Grid.Row='3' Content='Kick Off Work' x:Name='DoWorkButton'/>
<Border Grid.Column='2' Grid.Row='2' Grid.RowSpan='2' CornerRadius='10,10,10,10'
Margin='1.80200004577637,2,2,2'>
<Border.Background>
<LinearGradientBrush EndPoint='0.560000002384186,0.00300000002607703'
StartPoint='0.439999997615814,0.996999979019165'>
<GradientStop Color='#FF586C57'/>
<GradientStop Color='#FFA3BDA3' Offset='0.536'/>
<GradientStop Color='#FF586C57' Offset='0.968999981880188'/>
</LinearGradientBrush>
</Border.Background>
<StackPanel Margin='4,4,4,4' x:Name='FormData'>
<TextBlock Height='Auto' Width='Auto' Text='First Name:' TextWrapping='Wrap'
Margin='2,2,2,0'/>
<TextBox Height='Auto' Width='Auto' Text='' TextWrapping='Wrap'
x:Name='Field1' Margin='2,0,2,4'/>
<TextBlock Height='Auto' Width='Auto' Text='Last Name:'
TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='Auto' x:Name='Field2' Width='Auto' Text=''
TextWrapping='Wrap' Margin='2,0,2,4'/>
<TextBlock Height='Auto' Width='Auto' Text='Company:'
TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='Auto' x:Name='Field3' Width='Auto' Text=''
TextWrapping='Wrap' Margin='2,0,2,2'/>
<TextBlock Height='22.537' Width='182' Text='Title:'
TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='20.772' x:Name='Field4' Width='182' Text=''
TextWrapping='Wrap' Margin='2,0,2,2'/>
</StackPanel>
</Border>
<Ellipse x:Name='StatusEllipse' Margin='4,2,2,2' Grid.Row='3' Stroke='#FF000000'
Fill='#FF2D4DE0' RenderTransformOrigin='0.5,0.5' >
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
<ToolTipService.ToolTip>
<ToolTip Content='Click button to start work.' />
</ToolTipService.ToolTip>
</Ellipse>
<Canvas HorizontalAlignment='Stretch' Margin='0,0,2,8' Grid.RowSpan='4'
Grid.ColumnSpan='3' x:Name='PromptCancelCanvas' Visibility='Collapsed'>
<Rectangle Height='300' Width='400' Fill='#FF808080' Stroke='#FF000000'
Stretch='Fill' Opacity='0.6'/>
<Canvas Height='106' Width='289' Canvas.Left='46' Canvas.Top='85'>
<Rectangle Height='106' Width='289' Fill='#FFFFFFFF' Stroke='#FF000000'
RadiusX='23' RadiusY='23' Opacity='0.85'/>
<Button Height='34' x:Name='ButtonConfirmCancelYes' Width='100'
Canvas.Left='15' Canvas.Top='49' Content='Yes'/>
<Button Height='34' x:Name='ButtonConfirmCancelNo' Width='100'
Canvas.Left='164' Canvas.Top='49' Content='No' />
<TextBlock Width='134.835' Canvas.Left='75' Canvas.Top='12.463'
Text='Cancel Operation?' TextWrapping='Wrap'/>
</Canvas>
</Canvas>
<TextBlock Margin='67.8270034790039,0,-88.802001953125,0' Grid.Column='1'
Grid.ColumnSpan='1' Text='BackgroundWorker Thread' TextWrapping='Wrap'/>
</Grid>"


// Load xaml dynamically
let grid = XamlReader.Load(xamlControls) :?> Grid

// Find the controls...
let statusEllipse = grid.FindName("StatusEllipse") :?> Ellipse
let textarea = grid.FindName("WorkResultsTextData") :?> TextBox
let doWorkButton = grid.FindName("DoWorkButton") :?> Button
let cancelNoButton = grid.FindName("ButtonConfirmCancelNo") :?> Button
let cancelYesButton = grid.FindName("ButtonConfirmCancelYes") :?> Button
let cancelCanvas = grid.FindName("PromptCancelCanvas") :?> Canvas

let storyboard = new Storyboard()

(let xaml =
"<ColorAnimationUsingKeyFrames
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
BeginTime='00:00:00'
Storyboard.TargetProperty='(Shape.Fill).(SolidColorBrush.Color)'>
<SplineColorKeyFrame KeyTime='00:00:00' Value='#FF008000'/>
<SplineColorKeyFrame KeyTime='00:00:01.5000000' Value='#FFFFFF00'/>
<SplineColorKeyFrame KeyTime='00:00:03' Value='#FF008000'/>
<SplineColorKeyFrame KeyTime='00:00:04.5000000' Value='#FF008000'/>
<SplineColorKeyFrame KeyTime='00:00:06' Value='#FFFFFF00'/>
<SplineColorKeyFrame KeyTime='00:00:07.5000000' Value='#FF008000'/>
</ColorAnimationUsingKeyFrames>"
let animation = XamlReader.Load(xaml) :?> ColorAnimationUsingKeyFrames
Storyboard.SetTarget(animation,statusEllipse)
animation
) |> storyboard.Children.Add

(let xaml =
"<DoubleAnimationUsingKeyFrames
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
BeginTime='00:00:00' Storyboard.TargetProperty='(UIElement.Opacity)'>
<SplineDoubleKeyFrame KeyTime='00:00:00' Value='0.7'/>
<SplineDoubleKeyFrame KeyTime='00:00:01.5000000' Value='0.5'/>
<SplineDoubleKeyFrame KeyTime='00:00:03' Value='0.5'/>
<SplineDoubleKeyFrame KeyTime='00:00:04.5000000' Value='0.7'/>
<SplineDoubleKeyFrame KeyTime='00:00:06' Value='0.5'/>
<SplineDoubleKeyFrame KeyTime='00:00:07.5000000' Value='0.5'/>
</DoubleAnimationUsingKeyFrames>"
let animation = XamlReader.Load(xaml) :?> DoubleAnimationUsingKeyFrames
Storyboard.SetTarget(animation,statusEllipse)
animation
) |> storyboard.Children.Add

(let xaml =
"<DoubleAnimationUsingKeyFrames
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
BeginTime='00:00:00'
Storyboard.TargetProperty='(UIElement.RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleX)'>
<SplineDoubleKeyFrame KeyTime='00:00:00' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:01.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:03' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:04.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:06' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:07.5000000' Value='0'/>
</DoubleAnimationUsingKeyFrames>"
let animation = XamlReader.Load(xaml) :?> DoubleAnimationUsingKeyFrames
Storyboard.SetTarget(animation,statusEllipse)
animation
) |> storyboard.Children.Add

(let xaml =
"<DoubleAnimationUsingKeyFrames
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
BeginTime='00:00:00'
Storyboard.TargetProperty='(UIElement.RenderTransform).(TransformGroup.Children)[1].(SkewTransform.AngleY)'>
<SplineDoubleKeyFrame KeyTime='00:00:00' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:01.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:03' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:04.5000000' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:06' Value='0'/>
<SplineDoubleKeyFrame KeyTime='00:00:07.5000000' Value='0'/>
</DoubleAnimationUsingKeyFrames>"
let animation = XamlReader.Load(xaml) :?> DoubleAnimationUsingKeyFrames
Storyboard.SetTarget(animation,statusEllipse)
animation
) |> storyboard.Children.Add

let worker = new BackgroundWorker(WorkerReportsProgress = true,
WorkerSupportsCancellation = true)


// Implent DoWorkButton_Click
doWorkButton.Click.Add(fun e ->
if worker.IsBusy = false then
textarea.Text <- sprintf "Started : %s" (DateTime.Now.ToString())
worker.RunWorkerAsync(textarea.Text)
storyboard.AutoReverse <- true
storyboard.RepeatBehavior <- RepeatBehavior.Forever
storyboard.Begin()
)

// Implement ButtonConfirmCancelYes_Click
cancelYesButton.Click.Add(fun e ->
worker.CancelAsync()
cancelCanvas.Visibility <- Visibility.Collapsed)

// Implement ButtonConfirmCancelNo_Click
cancelNoButton.Click.Add(fun e ->
cancelCanvas.Visibility <- Visibility.Collapsed)

// Implement StatusEllipse_MouseLeftButtonDown
statusEllipse.MouseLeftButtonDown.Add(fun e ->
if worker.IsBusy = true then
cancelCanvas.Visibility <- Visibility.Visible)

// Implement DoWork
worker.DoWork.Add(fun e ->
[1..30] |> iter (fun i ->
if worker.CancellationPending = true then
e.Cancel <- false
else
System.Threading.Thread.Sleep(1000);
(int (floor (float i)*100.0/30.0))
|> worker.ReportProgress)
e.Result <- sprintf "\nCompleted : %s" (DateTime.Now.ToString()))

// Implement RunWorkerCompleted
worker.RunWorkerCompleted.Add(fun e ->
storyboard.Stop()
if e.Cancelled = false then
statusEllipse.Fill <- new SolidColorBrush(Color.FromArgb(255uy,0uy,255uy,0uy))
textarea.Text <- textarea.Text + e.Result.ToString()
ToolTipService.SetToolTip(statusEllipse, "Work Complete.")
else
statusEllipse.Fill <- new SolidColorBrush(Color.FromArgb(255uy,255uy,255uy,0uy))
let msg = sprintf "%s \nCanceled@: %s" textarea.Text <| DateTime.Now.ToString()
ToolTipService.SetToolTip(statusEllipse, msg))

// Implement ProgressChanged
worker.ProgressChanged.Add(fun e ->
if cancelCanvas.Visibility = Visibility.Collapsed then
let msg = sprintf "%s Percent Complete. Click to cancel..." (e.ProgressPercentage.ToString())
ToolTipService.SetToolTip(statusEllipse, msg))

base.Width <- 400.0
base.Height <- 300.0
base.Content <- grid
//base.Content <- testerror
end

type ErrorPage = class
inherit UserControl

new (msg:string ) as this = {} then

let textarea = new TextBlock(Text=msg,
TextWrapping=TextWrapping.Wrap,
Margin=new Thickness(4.0,4.0,4.0,4.0))

let sp = new StackPanel(HorizontalAlignment = HorizontalAlignment.Stretch,
Margin=new Thickness(8.0,8.0,10.0,8.0))
sp.Children.Add(textarea)

base.Width <- 600.0
base.Height <- 1000.0
base.Content <- sp
end


type MyApp = class
inherit Application

new () as this = {} then
this.Startup.Add(fun _ ->
let rootPanel = new StackPanel()
try
this.RootVisual <- rootPanel
rootPanel.Children.Add(new MyPage())
with _ as e ->
let msg = e.Message + e.StackTrace
rootPanel.Children.Clear()
rootPanel.Children.Add(new ErrorPage(msg)))

this.UnhandledException.Add(fun args ->
args.Handled <- true
try
let msg = args.ExceptionObject.Message + args.ExceptionObject.StackTrace
let errmsg = msg.Replace('"','\'').Replace("\r\n",@"\n")
"throw new Error(\"Unhandled error in Silverlight 2 Application " + msg + "\");"
|> HtmlPage.Window.Eval |> ignore
with _ -> HtmlPage.Window.Eval("throw new Error(\"Custom Error!\");") |> ignore)
end

Tuesday, March 17, 2009

Silverlight with F#: Background Thread and Animation

I am working through recipe 2.11 in the book Silverlight 2 Recipes, which introduce concepts of background threads and animation in Silverlight.  In developing recipe 2.11 in F#, I ran into problems getting animation to work. I managed to narrow the problem down to use of PropertyPath in my code.  If I use the following line of code, the Silverlight application would work.

Storyboard.SetTargetProperty(animation,new PropertyPath(UIElement.OpacityProperty))

But if I use the following line of code:

Storyboard.SetTargetProperty(animation,new PropertyPath("(UIElement.Opacity)"))

it would fail with the following message:

proppatherr

Matthew MacDonald seemed to support the second usage of PropertyPath in chapter 9 of his book Pro Silverlight 2 in C# 2008.  I’m not sure right now what’s causing it to break when using that code form with F#.  Due to problems I’ve encountered with PropertyPath, I’m not able to implement recipe 2.11 completely.  I did managed to implement a stripped down version of recipe 2.11 that demonstrates background threads with animation.  Here’s the code that did work for me:


#light
namespace SilverLightFSharp

open System
open System.ComponentModel
open System.IO
open System.IO.IsolatedStorage
open System.ServiceModel
open System.Windows
open System.Windows.Browser
open System.Windows.Controls
open System.Windows.Markup
open System.Windows.Media
open System.Windows.Media.Animation
open System.Windows.Shapes
open List

// Recipe 2-11 from Silverlight 2 Recipes book
// Executing work on a background thread with updates
// Simplified due to problems with Storyboard.SetTargetProperty and PropertyPath
// Added error page for debugging purposes
type MyPage() = class
inherit UserControl()

do
let xamlControls =
"<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
>
<Grid.ColumnDefinitions>
<ColumnDefinition Width='0.068*'/>
<ColumnDefinition Width='0.438*'/>
<ColumnDefinition Width='0.495*'/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height='0.08*'/>
<RowDefinition Height='0.217*'/>
<RowDefinition Height='0.61*'/>
<RowDefinition Height='0.093*'/>
</Grid.RowDefinitions>
<Button HorizontalAlignment='Stretch' Margin='5,8,5,8'
VerticalAlignment='Stretch' Grid.Column='1' Grid.Row='1'
Content='Save Form Data'/>
<StackPanel HorizontalAlignment='Stretch'
Margin='5,8,6,8' Grid.Column='1' Grid.Row='2'>
<TextBlock Height='Auto' Width='Auto' Text='Work Results Appear Below'
TextWrapping='Wrap' Margin='4,4,4,4'/>
<TextBox Height='103' Width='Auto' Text='' TextWrapping='Wrap'
Margin='4,4,4,4' x:Name='WorkResultsTextData'/>
</StackPanel>
<Button HorizontalAlignment='Stretch' Margin='12,8,8,8'
VerticalAlignment='Stretch'
Grid.Column='2' Grid.Row='1' Content='Load Form Data' />
<Button HorizontalAlignment='Stretch' Margin='10,2,8,6'
VerticalAlignment='Stretch'
Grid.Column='1' Grid.Row='3' Content='Kick Off Work' x:Name='DoWorkButton'/>
<Border Grid.Column='2' Grid.Row='2' Grid.RowSpan='2' CornerRadius='10,10,10,10'
Margin='1.80200004577637,2,2,2'>
<Border.Background>
<LinearGradientBrush EndPoint='0.560000002384186,0.00300000002607703'
StartPoint='0.439999997615814,0.996999979019165'>
<GradientStop Color='#FF586C57'/>
<GradientStop Color='#FFA3BDA3' Offset='0.536'/>
<GradientStop Color='#FF586C57' Offset='0.968999981880188'/>
</LinearGradientBrush>
</Border.Background>
<StackPanel Margin='4,4,4,4' x:Name='FormData'>
<TextBlock Height='Auto' Width='Auto' Text='First Name:' TextWrapping='Wrap'
Margin='2,2,2,0'/>
<TextBox Height='Auto' Width='Auto' Text='' TextWrapping='Wrap'
x:Name='Field1' Margin='2,0,2,4'/>
<TextBlock Height='Auto' Width='Auto' Text='Last Name:'
TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='Auto' x:Name='Field2' Width='Auto' Text=''
TextWrapping='Wrap' Margin='2,0,2,4'/>
<TextBlock Height='Auto' Width='Auto' Text='Company:'
TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='Auto' x:Name='Field3' Width='Auto' Text=''
TextWrapping='Wrap' Margin='2,0,2,2'/>
<TextBlock Height='22.537' Width='182' Text='Title:'
TextWrapping='Wrap' Margin='2,4,2,0'/>
<TextBox Height='20.772' x:Name='Field4' Width='182' Text=''
TextWrapping='Wrap' Margin='2,0,2,2'/>
</StackPanel>
</Border>
<Ellipse x:Name='StatusEllipse' Margin='4,2,2,2' Grid.Row='3' Stroke='#FF000000'
Fill='#FF2D4DE0' RenderTransformOrigin='0.5,0.5' >
<Ellipse.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Ellipse.RenderTransform>
<ToolTipService.ToolTip>
<ToolTip Content='Click button to start work.' />
</ToolTipService.ToolTip>
</Ellipse>
<Canvas HorizontalAlignment='Stretch' Margin='0,0,2,8' Grid.RowSpan='4'
Grid.ColumnSpan='3' x:Name='PromptCancelCanvas' Visibility='Collapsed'>
<Rectangle Height='300' Width='400' Fill='#FF808080' Stroke='#FF000000'
Stretch='Fill' Opacity='0.6'/>
<Canvas Height='106' Width='289' Canvas.Left='46' Canvas.Top='85'>
<Rectangle Height='106' Width='289' Fill='#FFFFFFFF' Stroke='#FF000000'
RadiusX='23' RadiusY='23' Opacity='0.85'/>
<Button Height='34' x:Name='ButtonConfirmCancelYes' Width='100'
Canvas.Left='15' Canvas.Top='49' Content='Yes'/>
<Button Height='34' x:Name='ButtonConfirmCancelNo' Width='100'
Canvas.Left='164' Canvas.Top='49' Content='No' />
<TextBlock Width='134.835' Canvas.Left='75' Canvas.Top='12.463'
Text='Cancel Operation?' TextWrapping='Wrap'/>
</Canvas>
</Canvas>
<TextBlock Margin='67.8270034790039,0,-88.802001953125,0' Grid.Column='1'
Grid.ColumnSpan='1' Text='BackgroundWorker Thread' TextWrapping='Wrap'/>
</Grid>"


// Load xaml dynamically
let grid = XamlReader.Load(xamlControls) :?> Grid

// Find the controls...
let statusEllipse = grid.FindName("StatusEllipse") :?> Ellipse
let textarea = grid.FindName("WorkResultsTextData") :?> TextBox
let doWorkButton = grid.FindName("DoWorkButton") :?> Button
let cancelNoButton = grid.FindName("ButtonConfirmCancelNo") :?> Button
let cancelYesButton = grid.FindName("ButtonConfirmCancelYes") :?> Button
let cancelCanvas = grid.FindName("PromptCancelCanvas") :?> Canvas

//let storyboard = Resources.createStoryBoard()
// Must preset opacity value
statusEllipse.Opacity <- 0.2
let storyboard = new Storyboard()
let animation = new DoubleAnimation(From=new Nullable<float>(0.2),
To=new Nullable<float>(1.0),
Duration= new Duration(TimeSpan.FromSeconds(5.0)))
Storyboard.SetTarget(animation,statusEllipse)
// This following line of code does not work - gives NullReference exception
//Storyboard.SetTargetProperty(animation,new PropertyPath("(UIElement.Opacity)"))
Storyboard.SetTargetProperty(animation,new PropertyPath(UIElement.OpacityProperty))
storyboard.Children.Add(animation)

let worker = new BackgroundWorker(WorkerReportsProgress = true,
WorkerSupportsCancellation = true)


// Implement DoWorkButton_Click
doWorkButton.Click.Add(fun e ->
if worker.IsBusy = false then
textarea.Text <- sprintf "Started : %s" (DateTime.Now.ToString())
worker.RunWorkerAsync(textarea.Text)
storyboard.AutoReverse <- true
storyboard.RepeatBehavior <- RepeatBehavior.Forever
storyboard.Begin()
)

// Implement ButtonConfirmCancelYes_Click
cancelYesButton.Click.Add(fun e ->
worker.CancelAsync()
cancelCanvas.Visibility <- Visibility.Collapsed)

// Implement ButtonConfirmCancelNo_Click
cancelNoButton.Click.Add(fun e ->
cancelCanvas.Visibility <- Visibility.Collapsed)

// Implement StatusEllipse_MouseLeftButtonDown
statusEllipse.MouseLeftButtonDown.Add(fun e ->
if worker.IsBusy = true then
cancelCanvas.Visibility <- Visibility.Visible)

// Implement DoWork
worker.DoWork.Add(fun e ->
[1..30] |> iter (fun i ->
if worker.CancellationPending = true then
e.Cancel <- false
else
System.Threading.Thread.Sleep(1000);
(int (floor (float i)*100.0/30.0))
|> worker.ReportProgress)
e.Result <- sprintf "\nCompleted : %s" (DateTime.Now.ToString()))

// Implement RunWorkerCompleted
worker.RunWorkerCompleted.Add(fun e ->
storyboard.Stop()
if e.Cancelled = false then
statusEllipse.Fill <- new SolidColorBrush(Color.FromArgb(255uy,0uy,255uy,0uy))
textarea.Text <- textarea.Text + e.Result.ToString()
ToolTipService.SetToolTip(statusEllipse, "Work Complete.")
else
statusEllipse.Fill <- new SolidColorBrush(Color.FromArgb(255uy,255uy,255uy,0uy))
let msg = sprintf "%s \nCanceled@: %s" textarea.Text <| DateTime.Now.ToString()
ToolTipService.SetToolTip(statusEllipse, msg))

// Implement ProgressChanged
worker.ProgressChanged.Add(fun e ->
if cancelCanvas.Visibility = Visibility.Collapsed then
let msg = sprintf "%s Percent Complete. Click to cancel..." (e.ProgressPercentage.ToString())
ToolTipService.SetToolTip(statusEllipse, msg))

base.Width <- 400.0
base.Height <- 300.0
base.Content <- grid
//base.Content <- testerror
end

type ErrorPage = class
inherit UserControl

new (msg:string ) as this = {} then

let textarea = new TextBlock(Text=msg,
TextWrapping=TextWrapping.Wrap,
Margin=new Thickness(4.0,4.0,4.0,4.0))

let sp = new StackPanel(HorizontalAlignment = HorizontalAlignment.Stretch,
Margin=new Thickness(8.0,8.0,10.0,8.0))
sp.Children.Add(textarea)

base.Width <- 600.0
base.Height <- 1000.0
base.Content <- sp
end


type MyApp = class
inherit Application

new () as this = {} then
this.Startup.Add(fun _ ->
let rootPanel = new StackPanel()
try
this.RootVisual <- rootPanel
rootPanel.Children.Add(new MyPage())
with _ as e ->
let msg = e.Message + e.StackTrace
rootPanel.Children.Clear()
rootPanel.Children.Add(new ErrorPage(msg)))

this.UnhandledException.Add(fun args ->
args.Handled <- true
try
let msg = args.ExceptionObject.Message + args.ExceptionObject.StackTrace
let errmsg = msg.Replace('"','\'').Replace("\r\n",@"\n")
"throw new Error(\"Unhandled error in Silverlight 2 Application " + msg + "\");"
|> HtmlPage.Window.Eval |> ignore
with _ -> HtmlPage.Window.Eval("throw new Error(\"Custom Error!\");") |> ignore)
end