Thursday, January 29, 2009

Monday, January 26, 2009

[Silverlight 2, C#] Data Binding and Event Handlers

So, right to the point, it seems that you cannot data bind event handlers.

What I wanted to do was be able to bind a name and delegate function to a custom menu item.
[ListBox x:Name="ItemList" Width="Auto" Height="Auto"]
[ListBox.ItemTemplate]
[DataTemplate]
[StackPanel Orientation="Horizontal"]
[TextBlock Text="{Binding itemname}"
FontFamily="Arial" Font Foreground="Black"
MouseLeftButtonDown="{Binding itemaction}"/]
[/StackPanel]
[/DataTemplate]
[/ListBox.ItemTemplate]
[/ListBox]

But I was getting a compiler error:
Error 5 The "ValidateXaml" task failed unexpectedly.
System.InvalidOperationException: Stack empty.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Stack`1.Pop()...

After a quick trip to the Silverlight forums I found out that you cannot databind to an event handler - which made some sense after I found this on the MSDN page for DataBinding:

The binding engine gets information from the Binding object about the following:



My Solution: Sneak the function delegate into the tag property
Since I couldn't bind the event directly I decided to sneak the delegate into the tag property of the textbox, and then setup a generic mouseLeftButtonDown handler that would read out the tag and cast it to my delegate, and then invoke it. So far it seems to work pretty well.

[ListBox x:Name="ItemList" Width="Auto" Height="Auto"]
[ListBox.ItemTemplate]
[DataTemplate]
[StackPanel Orientation="Horizontal"]
[TextBlock Text="{Binding itemname}"
FontFamily="Arial" Font Foreground="Black"
Tag="{Binding itemaction}"
MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" /]
[/StackPanel]
[/DataTemplate]
[/ListBox.ItemTemplate]
[/ListBox]

and then in the code behind:

private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Get the tag info and run it.
MenuActionDelegate func = ((FrameworkElement) sender).Tag as MenuActionDelegate;
func.Invoke();
}

If anyone else has a more elegant solution, please let me know!!!

.

Friday, January 23, 2009

Shameless Picture Post - MS Tech Days

Over the past two days many of the people on my team attended Microsoft 2008 Tech Days - the main reason for me at least being that they had a few Silverlight presentations. Much of the content I had seen before from MIX webcasts, but I was able to pickup on some tips/classes that I just wasn't aware of before.

I left my notes at home today, so these are just off the top of my head:
- HtmlPage class : Allows access to the browser DOM, so you can actually pop open other HTML windows when you need them. I think this may come in very handy when trying to debug issues.
- I really need to start looking into binding more. I don't use it at all in my application and I'm not sure if that's because it just doesn't "fit" into my model, or because I haven't been smart enough to figure out "how" to use it.
- ... well ... I just can't remember at the moment - but I promise I'll update this when I get home and get my notebook ^^


Shameless picture... this is a large majority of the women that attended the conference, I think that Qixing [the "Women in Technology" leader] told us that only 10% of the registered attendees were female. We all had breakfast together, and it was a great way to meet new people! I'm in the front on the right side of the pic :)

















.

Thursday, January 22, 2009

Silveright Deep Zoom + LOLCats = Best Use of Cutting Edge Tech EVAR

So, this is a little side post and isn't related to any coding issues at all - BUT - it made my day and since it is related to Silverlight I figure I'm allowed to post it here ;)

This amazingly brilliant person took the new[ish] Deep Zoom technology and applied it to one of my most favourite things: LOLCats. Check it out... zoom in, waaaaaaaaay in!




http://robburke.net/2008/08/08/fractlol/

.

Tuesday, January 20, 2009

[Silverlight 2, C#] Fun with Namespaces

Hi everybody!

Alright - so if you've read my other posts, you'll know that I'm working on a WYSIWYG-type graphics editor - and I've been dealing with naming issues with regards to having to name and clone thousands of elements on a canvas. Also in my application, when I drag and stretch, I create a ghost of the base element. This also required cloning, and up until now, namespace checks.

I was aware that a user control actually creates it's own namespace, such that you can have the same x:name is multiple controls. This is obviously a very, very handy thing to have. I wanted to be able to separate some content from the rest of my application easily, so that I could reduce the number of name checks I need to do as a result of cloning elements based on hardcoded strings.

Try 1: Creating an essentially empty UserControl
Originally, I had tried to create a helper UserControl called "SafeNamespace" which was essentially an empty control with a Canvas root.

[UserControl x:Class="Graphics.SafeNamespace"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"]
[Canvas x:Name="LayoutRoot"]

[/Canvas]
[/UserControl]


This was mildly annoying because I could not easily treat this like a canvas [to my knowledge] and I wrote small helper functions in the xaml.cs to allow for simplier setting and getting of the LayoutRoot content. It was just a little ugly - it worked, it was just icky.


Better Method: Extending the Canvas Class
After a little searching I came across this forum post which talked about extending the Canvas class itself, instead of extending the UserControl class. This also allows you to implement custom functionality onto the Canvas if you desired, but for me I was really only looking for the ability to create a seperate namespace.

xaml:
[Canvas x:Class="Graphics.SafeNamespaceCanvas"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"]
[/Canvas]


and

xaml.cs
public partial class SafeNamespaceCanvas : Canvas
{ ... }



In short, creating an extention of a class was a nice way for me to achieve some namespace independance... and was extremely handy given the large number of named elements I was dealing with! Just thought I'd pass along the idea :)


.

Friday, January 16, 2009

[Silverlight 2, C#] Performance of doing many many FindName calls...

Today I was looking into an issue I was having regarding having to do many [up to thousands] of FindName checks in my WYSIWYG graphics editor. This is due to the fact that most [if not all] of my elements are named, and when adding a new palette item I need to check and make sure that the names of the new item do not conflict with any existing items on my canvas. I stress test using palette items that contain roughly 3k elements, all with their own names. In practice, this may never be the case, but I always like to stress the crap out of things to see where they can break down the line... and honestly I can see a user ending up with complex palette items that may contain many many elements.

Aaaaaaaaaaaaanyways. Before I was going through my new item and checking all names against the canvas [using FindName] that the item was to be placed in. I found when stress testing that this comparison could take a long long time.

The solution we came up with was to create a Dictionary of all names on the canvas and then do my checks against THAT [Dictionary.ContainsKey("nameOfItem")] instead of using FindName. I chose to use a Dictionary since it is implemented on a hash, whereas a List is not.

In my tests I found that the time to do my naming checks was cut roughly in half by doing this. Obviously more memory is required to house the Dictionary of names, but the time savings more then makes up for it in my case.

In summary - it may be quicker to generate a Dictionary of names and then check against that, instead of using FindName.

I haven't tested the single case [ie only doing ONE FindName], but when doing thousands and hundreds of thousands, my performance was doubled.

.

Thursday, January 15, 2009

[Silverlight 2, C#] Testing Performance, Memory Usage

So after some code reviews and the like, I had decided to try and implement some of my core functionality a little different in order to *hopefully* decrease the memory allocation of my application.

Since Silverlight 2 does not appear to support the System.Diagnostics.Process class, I believe the only way to get similar information is via [Garbage Collector] System.GC.GetTotalMemory

System.GC.GetTotalMemory
public static long GetTotalMemory(
bool forceFullCollection
)

* Set forceFullCollection to true if you can wait for garbage collection to occur before doing the check.

* Returns the estimated number of bytes the application has allocated.

Difference Between GetTotalMemory() vs Windows Task Manager Memory Estimation
I have noticed QUITE a difference between the bytes returned from this function, vs. the Windows Task Manager estimation of the memory used by iexplorer while my app is running.

Siverlight Plugin Memory
One reason that I know for sure, is that the Task Manager takes into account the memory it takes to run the Silverlight plugin. I created an empty Silverlight project and when running it, it appeared to take up between 38,000kb to 40,624kb. Not sure why there was ever a difference, but every time I ran it I got a slightly different value. GetTotalMemory does not appear to include this cost and only counts the memory the app itself allocates.

Unmanaged Memory
GetTotalMemory only counts managed memory allocated by your application. If there is a memory leak for whatever reason, then that cost will not be included in the total.

There may be other reasons that the two memory estimations are different, but those are the two that I have come across so far.

.

Tuesday, December 30, 2008

[Silverlight 2] Unit Testing

This is more for my own reference, but here are some really good links I found to information about using the Silverlight Testing framework available to us.

Unit testing Basics [Jeff Wilcox]
Excellent Step by Step [Jeff Wilcox]
MSDN Download and Info
Basic Asynchronous Step by Step

I am probably abusing the framework with the way I have setup my test scripts, but I was looking to store state between each test so that I would not have to setup my application state every time I moved onto a new test.

I followed the main steps listed by Jeff Wilcox, however, I made a few alterations that would probably make him cringe ;)
  1. In each test cs file, I store an instance of the class I'm testing so that the state can be saved.
  2. In the PreparePage() function for each TestClass I check if that instance has been initialized. If it has, I do nothing, else I set it up. Since PreparePage is called before each TestMethod I want to make sure that my instance remains with the state of it's previous test.
  3. I name my tests, in order, alphabetically... often prefixed with "aa_[DoThis]", "ab_[ThenThis]". Since the tests appear to be ran in alphabetical order I want to keep a very scrict execution order so that my state should be known after every test.
  4. I have made all my Test Classes partial, and have created a seperate file "TestSetup.cs" that acts as a central location for me to decide which scipts I want to run and when. Making the class partial allows me to stick the [TestClass] assmbly directive in another file, which means I can comment out scripts as I see fit.
Example:
GraphicCanvas_test.cs


public partial class GraphicCanvas_test : SilverlightTest
{
private GraphicCanvas myCanvas;

[TestInitialize]
public void PreparePage()
{
if (myCanvas != null) { return; }
myCanvas = new GraphicCanvas();
}

...
}

TestSetup.cs

[TestClass] public partial class GraphicCanvas_test {} // Test script run
//[TestClass] public partial class PaletteManager_test {} // <-- Not run


I'm still playing around with unit testing framework, and I'm probably bending it how it wasn't meant to be bent - but I have yet to see something that would work better for me :)




.

Thursday, December 18, 2008

[Silverlight] Silverlight Spy - Awsome Visual Tool

While googling some random problem I was having, I bumped into this amazing [and free!] tool built by firstfloorsoftware which allows you to inspect any Silverlight application embedded in a given page.
The Explorer presents XAP Package, Isolated Storage, Application Styles, the UI Automation tree and the UI element structure of a Silverlight application. Explore the structure and view and edit the details of the selected UI element in the Details pane. Silverlight Spy works with any web page hosting Silverlight 2 content, just point the browser to the page and let the Spy figure it out.
Already this has saved me tons of heartache, as it allows me to easily traverse the visual tree of my application - which is really handy when I do so many dynamic interactions [adding/removing elements etc...]. And I haven't even begun to use the isolated storage inspection! Check it out :)

http://firstfloorsoftware.com/silverlightspy/introduction/



.

Thursday, December 11, 2008

[C#] Creating Custom Dependency Properties

Oh! I'm so excited... I think I actually got this to work for me :)
Please note that this is for creating simple DependencyProperties... I am not creating an attached property here.

I have a custom user control called GraphicGrid which consists of multiple line elements that draw up a grid. I also have a custom user control called PropertyEditor which allows for easy changes to specific DependencyProperties of a given object. I wanted to be able to change the grid color and grid spacing via the editor, so I decided this was the perfect chance to try and implement custom dependency properties.

Here are the basic steps to setting one up:

Step 1:
Register the custom dependency property. Here I create a new dependency propery and give it a name, what the property type is, what the owning object type is, and then in my case, I register a callback to be ran when the value is changed. Note that you do not need to setup a callback function [use null instead], unless you need specific things to happen when the value is changed:
public static readonly DependencyProperty GridLineStrokeProperty =
DependencyProperty.Register("GridLineStroke",
typeof(Brush),
typeof(GraphicGrid),
new PropertyMetadata(GridLineStrokeChanged));

Step 2 [if you setup a callback]:
If you have setup a callback if the value has been changed, then you need to create that function.
private static void GridLineStrokeChanged(DependencyObject o,
DependencyPropertyChangedEventArgs e)

{
GraphicGrid grid = o as GraphicGrid;

// Color lines.
foreach (UIElement line in grid.LayoutRoot.Children)
{
line.SetValue(Shape.StrokeProperty, e.NewValue);
}
}

Here, I cast the sender to a GraphicGrid, which I believe is acceptable since I have registered the property to GraphicGrid. Then I perform some actions with the new value... in my case I update all the lines in the grid with the new color.

Step 3:
Then, if you wish, you can create a local variable which gets and sets this dependency property.
public Brush GridLineStroke
{
get { return (Brush)GetValue(GridLineStrokeProperty); }
set { SetValue(GridLineStrokeProperty, value); }
}
Step 4:
Update the property at your will and whenever the value is changed, the line color will also be changed!


Update directly via the DependencyProperty:
GraphicGrid newGrid = new GraphicGrid ();
newGrid.SetValue(GraphicGrid.GridLineStrokeProperty,
new SolidColorBrush(Colors.Red));



Update via the local variable:
newGrid.GridLineStroke = new SolidColorBrush(Colors.Red);



BAM! Auto updating lines!!!
Special thanks to bryant on the Silverlight forums :)
.

Wednesday, December 10, 2008

[C#] Loading embedded XAML files into a project

I was looking for a way to load in a XAML file into my project; I wanted to be able to create a nice looking element without having to build it up dynamically in the C# code, and without having to download the XAML file from a server as I have been doing in some other places.

Turns out you can embed a file as a resource in a Visual Studio project and then open the resource and stream it out!
Step 1: Right click on your project folder and add the new or existing resource to your project.

Step 2: Right click the newly added file in your solution explorer, and select "Properties"

Step 3: Change the "Build Action" to "Embedded Resource". Now the file will be built in to your project as a resource and accessible as such.

Step 4: Open up a stream to the resource, read it out into a string and then use XAMLReader.Load to load up the element. I found this code on a forum, so there may be an easier way to do it... but this worked for me.

Stream s = this.GetType().Assembly.GetManifestResourceStream ("myNamespace.myFile.xaml");
string propertyStr = new StreamReader(s).ReadToEnd();
Panel myGrid = (Panel)XamlReader.Load(propertyStr);

And BAM... loaded xaml! Note that your XAML file must contain the namespace information in order for [System.Windows.Markup.]XAMLReader.Load to load correctly.

Example myFile.xaml:
<. Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<. /Grid .>


Have fun :)
.

Monday, December 8, 2008

[Silverlight 2, C#] Make a dashed border "move" [animate]

I was looking to make my newly dashed border on my rectangle look like it was "moving" [as you see commonly in some applications when selecting an item].

To do this I created a doubleanimation on the "StrokeDashOffset" property of the Rectangle.

<. UserControl.Resources .>
<. Storyboard x:Name="LassoAnimation" .>
<. DoubleAnimation
Storyboard.TargetName="lasso"
Storyboard.TargetProperty="StrokeDashOffset"
By="1"
To="8"
RepeatBehavior="Forever"
Duration="0:0:3"
SpeedRatio="3" .>
<. /DoubleAnimation .>
<. /Storyboard .>
<. /UserControl.Resources .>

...

<. Rectangle x:Name="lasso"
Stroke="Blue" StrokeThickness="1" StrokeDashArray="6,2"
StrokeDashOffset="0" / .>

In order for the animation to be smooth you need to set the "To" value to be the size of the dash plus the gap values. So in my example, 8.

Then, when I want the animation to start in my C# code, I set the correct width/height/top/left values for the rectangle and then call the LassoAnimation.Begin function and BAM! Moving dashed border!


.

[Silverlight, C#] Create a simple dashed border

It is simple to set a dashed border of any shape [in my case I was setting a Rectangle border] ... simply set the StrokeDashArray property.

StrokeDashArray = "[Length of dash],[Length of gap], ..."
You can repeat the dash/gap pairs to create different patterns on the same stroke.
XAML:
<. Rectangle ... StrokeDashArray="5.0, 2.0" ./>

C#:
Rectangle lasso = new Rectangle();
...
lasso.StrokeDashArray = new DoubleCollection { 5.0, 2.0 };


.

Tuesday, November 18, 2008

[Silverlight 2] Unable to start debugging...

A co-worker of mine all of the sudden started getting the following error when she was trying to run/debug her Silverlight 2 application [web application with the plug-in being loaded via the auto generated html page]:
Unable to start debugging on the web server. The COM+ registry database detected a system error.
For whatever reason it was the enabled ASP.NET debugger that seemed to be causing this error. Once she unchecked the ASP.NET debugger checkbox found under the properties of the "Web" project [i.e only the "Silverlight" checkbox was checked] then everything started up and debugged smoothly.



.

Wednesday, October 29, 2008

[VS2008] Free Code Metrics Plugin

A few days ago, I was looking around to see if I could find out how to run some basic code metric analysis on my projects. It seems like a few editions of VS2008 [the IDE we're using at work] DOES have some built in code metric evaluation, but only in specific versions of the software. We have a the Professional Edition not the Team Edition... so no go.

But! I found a free VS plugin [thanks to the fine folks at Exact Magic Software] that will add similar functionality!

http://www.exactmagic.com/products/studiotools/index.html

Now, currently the numbers don't mean a whole lot to me since I have nothing to compare them with, but I'm going to start tracking them just to see :)


.

Tuesday, October 28, 2008

[Silverlight] Toolkit Released!

Neat, a new Silverlight toolkit has been released by the MS devs which will add some more components for developers to use and give feedback on.


http://www.codeplex.com/Silverlight

The Silverlight Toolkit is a collection of Silverlight controls, components and utilities made available outside the normal Silverlight release cycle. It adds new functionality quickly for designers and developers, and provides the community an efficient way to help shape product development by contributing ideas and bug reports. This first release includes full source code, unit tests, samples and documentation for 12 new controls covering charting, styling, layout, and user input.



.

Friday, October 24, 2008

[C#] "var" ... Implicitly Typed Variables - When to use?

Alrighty, so during a code review it was brought to my attention that as of C# 3.0 programmers can now use implicit declaration of variables, which was completely contrary to my previous understanding of the language - in that I thought it was solely strongly typed much like C/C++. That is not the case.
Explicit Declaration: int myCount;
Implicit Declaration: var myCount;
Implicit declarations rely on the compiler to chose the best type for you. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

Now while I can see this being handy for many reasons [from what I've read LINQ requires this type of functionality - but I haven't used LINQ yet]... it also troubles me - mostly due to readibility issues if overused. I've done some quick searches and I am not alone in my concerns. I'm just figured I'd list here when *I* think that the use of var can and should be applied for inferring a type.

*** Implicit Usage [My Thoughts] ***
Case 1: If it's required.
Duh... such as with LINQ examples... sometimes you just can't get around it ^^

Case 2: If you are dealing with a very, very, very long type name.
Example:
OhHaiThisIsMyLongClassName myLongClass;
Would become:
var myLongClass;

Case 3: If you Initialize the object on the same line.
Canvas myObj = new Canvas();
Would become:
var myObj = new Canvas(); // <-- We know in the same line what this variable's type is.

Now granted... if the name of your variable does not indicate what it is actually representing, then perhaps there is a programming issue with the naming convention used. I've seen this as an arguement in favor of using "var" - it forces descriptive naming conventions which would in the end actually increase the readibility of a programming.

Really in the end I believe it comes down to personal style - but it's good to keep in mind the pros and cons of using both explicit/implicit typing of variables.


MSDN Documentation on Implicit Typed Variables
Another discussion about when to use "var"

.

Tuesday, October 21, 2008

[Silverlight, C#] Adventures in Accessing Path Data

So I've been stumped for awhile on this, and it seems I was simply misunderstanding something about the Path Syntax used to describe path data, and as I discovered shortly after, there is a limitation in what Silverlight can parse.

Let's start at the beginning. I had a path object, that I took from an example, that looked like this:

[Path Name="shape_path"
Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000"
Width="92.5" Height="57.617"
Data="M137,122 C227,161 168.5,204.5 228.5,159.5" /]

I wanted, in my code behind, to access the Data property so that I could serialize the object into string whenever I wanted to. The problem I was having was that when I tried to access the Data by casting, I was getting an empty collection back.

Essentially PathGeometry g = (PathGeometry)path.Data was giving me an empty collection [Figures] and I had no way to get access to the data. I poked around the Silverlight forums and it seemed like other people were having this issue, and this used to work pre-Beta2, so there was some confusion.

Problem 1: My Misunderstanding of the Types of Path Markup Syntax

As it turns out though, MS never intended a PathGeometry to be accessed in that manner. And here's why [and what I had overlooked]. With Path Markup Syntax, there are actually 2 different types of paths:
StreamGeometry : You use the StreamGeometry mini-language when setting a property of type Geometry, such as the Clip property of a UIElement or the Data property of a Path element. The following example uses attribute syntax to create a StreamGeometry.
[Path Stroke="Black" Fill="Gray"
Data="M 10,100 C 10,300 300,-200 300,100" /]

PathFigureCollection : You use the PathFigureCollection mini-language when setting the Figures property of a PathGeometry. The following example uses a attribute syntax to create a PathFigureCollection for a PathGeometry.
[Path Stroke="Black" Fill="Gray"]
[Path.Data]
[PathGeometry Figures="M 10,100 C 10,300 300,-200 300,100" />]
[/Path.Data]
[/Path]
As you can see from the preceding examples, the two mini-languages are very similar. It's always possible to use a PathGeometry in any situation where you could use a StreamGeometry; so which one should you use? Use a StreamGeometry when you don't need to modify the path after creating it; use a PathGeometry if you do need to modify the path.
In my case, I actually needed to access the Figures collection, so I needed to use the longer notation. In my case, my error was that I had taken an example from somewhere, but it was not the correct syntax for what I ultimately wanted to do.

Now I'm not certain why there is a difference between these two types of paths since they seem so similar, although I imagine a little deeper reading into Geometries would tell me that.

Note: The following link is to documentation for WPF, which is where part of my confusion lay... since support in WPF is different then in Silverlight.
MSDN Documentation on Path Markup Syntax
The correct link is contained in the section "A Good Explanation" at the end of this post.


Problem 2: In Silverlight, Path.Figures Cannot be Parsed using the Mini-Lanugage Syntax

So yay right?!? This should be all fine and dandy! I change my XAML to use the correct Mini-Language as indicated in Problem 1, I go to build/run my application and BAM!

"Invalid attribute value M 10,100 C 10,300 300,-200 300,100 for property Figures. [Line: 5 Position: 27]".

With a little more searching I find a post indicating that:

The PathGeometry.Figures property does not support the path "mini-language" syntax in Silverlight. You have to use the verbose explicit markup to describe those figures in your XAML.

Now I just want to scream... after all that, Silverlight can't even PARSE the mini method of syntax and I need to make sure that the path I'm getting is using the long verbose method :(

Something like this:

[PathGeometry]
[PathGeometry.Figures]
[PathFigure]
[PathFigure.Segments]
[LineSegment Point="150,0"/]
[/PathFigure.Segments]
[/PathFigure]
[/PathGeometry.Figures]
[/PathGeometry]

Blech. How irritating, especially when many examples are given on MSDN in the mini syntax, and from what I've heard the WPF XAMLWriter also outputs the mini syntax.

Anyways, just a heads up, this seems to be the way it is.

Long story short: YOU HAVE TO BE VERBOSE WITH PATHGEOMETRY



A Good Explanation: What is actually supported in Silverlight, and how it works in WPF as well...

First, my hats off to all the people in the Silverlight community that help dummies like me out with issues on forums ^^. Big thanks to Wolf Schmidt (MSFT) who gave me this excellent explanation of what is going on:
PathGeometry.Figures does not support the Path minilanguage/syntax in Silverlight. However, Path.Data DOES support the Path minilanguage/syntax in Silverlight.

In Silverlight, if you use the minilanguage and set Path.Data, you get your intended path and its various parts rendered, but you do NOT get a run-time object tree representation of how that minilanguage was parsed such that you could walk into Figures, Segments, etc. You have to use the verbose form of markup by putting various PathFigure-type object elements under PathGeometry.Figures IF you want discrete run-time "parts" (and for best results, put some "Name" attributes on there so that you don't even need to walk, you can just use FindName).

BTW, in WPF, you also do not get object-tree representation of a path created via the mini-language. The only delta is that Silverlight only supports parsing/processing of the minilanguage on Path.Data whereas WPF supports it for either Path.Data OR PathGeometry.Figures.

PS: the MSDN article you linked two posts above is specifically the WPF version of the Path Markup Syntax information. You need to look at http://msdn.microsoft.com/en-us/library/cc189041(VS.95).aspx which is the Silverlight version. In general, you do have to keep an eye on whether you are looking at a WPF topic or a Silverlight topic when you look at MSDN, because many cases the TOC organization/titling etc. is similar between WPF and Silverlight but the information on the specific pages is often quite different because of the inherent technology differences.

My Silverlight Forum Post

.

Friday, October 10, 2008

[C#] Object Creation with Property Initialization

So a colleague of mine showed me a nice simple way in C# to both create and initialize an object in one step. I thought this was really neat syntax since it both saves lines of code and also saves some execution as the object is initialized with a value instead of a default which is THEN changed.

So something like this:
Rectangle myRec = new Rectangle();
myRec.Width = 50;
myRec.Height = 50;
Can become:
Rectangle myRec = New Rectangle() { Width=50, Height=50 };


There are some restrictions though:
  • Can only initialize properties or fields accessible by the object being initialized.
  • This means that you cannot set attached properties in this manner [ie. Canvas.Top], as these properties can only be set with the SetValue function.
  • The assignments in the initializer is treated the same as assignments to members of the field/property.

See here for a little more
And this msdn page

.

Wednesday, October 1, 2008

[Silverlight] Silverlight Beta 2 RC0 Released

Applications built using this release will work off of the Silverlight 2 RC0 Developer Runtime only. This is not intended for public deployment, as end users will not have a way to install a suitable plug-in to view the application. No existing public versions (released or beta) of Silverlight 1.0 or 2 Beta 2 will be auto-upgraded to this runtime. This is only for developers.

See http://silverlight.net/GetStarted/sl2rc0.aspx
and http://weblogs.asp.net/scottgu/archive/2008/09/25/silverlight-2-release-candidate-now-available.aspx

for more including downloads and breaking changes / new features.

Problems?
After I did the update, when I ran my application in IE I was prompted with the "Install Microsoft Silverlight" button... but how could that be? I just installed the new runtime?

With a little searching I came across this:

A quick fix when updating apps to RC0...if all you get is the "Install Silverlight" button, make sure your object type in your page is changed to
application/x-silverlight-2 instead of applicatiion/x-silverlight-2-b2

And poof! Works!


.