Path Data Parser
In this post I built a control that allows manipulation of a Path control. Unfortunately, it only works if you do not use the mini-language described here and include all the path segment elements in your XAML. When the mini language is used silverlight does not expose all the PathSegment objects that are used to draw the vector graphics. I’ve been using Blend on a project a lot lately (and even Illustrator a little) and anyone who has built up a lot of XAML vector assets knows that these tools all generate xaml that uses the Path mini language. I still wanted to be able to use my PathGeometryEditor control with these more complex vector assets. So, I used the documentation here and built a parser for the mini language. It reads in the path mini language and builds up the required tree of elements. The only thing I was working from was that documentation so, although it has been successful with every path I’ve given it, no guarantees it will work with every possible path data.
You can download the source here.
The path parser is implemented in the PathDataParser class in the PathUtils project. In order to use it use the PathDataParser.PathData attached property instead of the Data property on a Path control. You can see an example of this in PathUtilsTest\Page.xaml. The parser code itself is pretty straight forward. It reads through the path data and builds up all the required PathSegment objects. I haven’t tested this extensively, so if anyone finds any bugs please send them my way. (I haven’t actually tried this with WPF, but I believe it should also work as-is with WPF. I used Kaxaml to verify path rendering when I was testing).
You can see this sample running here. Grab the blue circles and move the path points around.
BTW, I had always assumed that code released on blogs with no license was released into the public domain, but then I read this post (which is a great read for anyone using or releasing shared source). Apparently, code released with no license is actually some of the most restricted. I’m releasing this sample (and all foreseeable future samples) under the MIT License. I’ll be going back into the previous samples I’ve posting and adding the license into that source as well when I have some extra time.
Much improved Silverlight 2 Custom Cursors
In this post I built a sample using attached properties to display custom cursors in Silverlight. While that sample was a good illustration of using attached properties and fairly useful it was not a solution that I think could scale to a production silverlight app. So, while porting the sample forward to RC0 I decided to extend it into something I think people could use in real apps. The API has actually gotten simpler while getting much more powerful.
Here is what the XAML looks like for using a custom cursor:
<Border Name="border1" BorderBrush="Black" Background="AntiqueWhite" BorderThickness="2" Width="100" Height="100" cc:CustomCursorAdorner.CursorId="RedSquare"/>
That’s all that’s needed on an element which should display a custom cursor on mouse over. So, what does "RedSquare" in this case refer to? The cursors themselves are defined as a property on the CustomCursorAdorner, via a style that will be applied to the element that is created as the cursor. The XAML for the CustomCursorAdorner and the cursors looks like this:
<cc:CustomCursorAdorner x:Name="cursorAdorner" IsGlobalCursorAdorner="True"> <cc:CustomCursorAdorner.Cursors> <cc:CustomCursorInfo Id="RedSquare"> <cc:CustomCursorInfo.CursorStyle> <Style TargetType="ContentControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Rectangle Fill="Red" Width="10" Height="10" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </cc:CustomCursorInfo.CursorStyle> </cc:CustomCursorInfo> <cc:CustomCursorInfo Id="GreenCircle"> <cc:CustomCursorInfo.CursorStyle> <Style TargetType="ContentControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Ellipse Fill="Green" Width="10" Height="10" /> </ControlTemplate> </Setter.Value> </Setter> </Style> </cc:CustomCursorInfo.CursorStyle> </cc:CustomCursorInfo> </cc:CustomCursorAdorner.Cursors> </cc:CustomCursorAdorner>
Here you can see that each cursor is defined by using a CustomCursorInfo object that is added to the CustomCursorAdorner’s Cursors collection. The Id value is what is used on elements where the cursor should be used, as shown in the first XAML snippet. It’s extremely easy now to reuse cursors across elements. The IsGlobalCursorAdorner property indicates that this CustomCursorAdorner should be used for all custom cursors. I think this is probably what people would want in most cases, but the ActiveAdorner attached property is still available as in the sample from the previous post if multiple custom cursor adorners are need.
In addition to allowing static content for the cursors you can bind dynamic content into the cursor using the CustomCursorAdorner.CursorContent property. Given a cursor defined like this:
<cc:CustomCursorInfo Id="TextSnapshot"> <cc:CustomCursorInfo.CursorStyle> <Style TargetType="ContentControl"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Grid> <TextBlock Text="{Binding}"> <TextBlock.RenderTransform> <ScaleTransform ScaleX="0.75" ScaleY="0.75" /> </TextBlock.RenderTransform> </TextBlock> </Grid> </DataTemplate> </Setter.Value> </Setter> </Style> </cc:CustomCursorInfo.CursorStyle> </cc:CustomCursorInfo>
You can bind in content to this cursor like this:
<Border Name="border3" BorderBrush="Black" Background="AntiqueWhite" BorderThickness="2" Width="100" Height="100" cc:CustomCursorAdorner.CursorId="TextSnapshot" cc:CustomCursorAdorner.CursorContent="{Binding TextValue}"> <Grid> <TextBox Text="{Binding TextValue, Mode=TwoWay}" Width="75" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> </Border>
In this case there is a DataContext with a TextValue property. Now when the content of the TextBox changes and updates the underlying property the content of the cursor will also update.
Click here to see the sample silverlight app (RC0 required) and here to download the source.
Please send me any questions or suggestions.
Tracking ItemsControl Container Elements
Silverlight ItemsControls do not provide an easy way to retrieve the generated item containers for the items within the ItemsControl. In WPF the ItemContainerGenerator provides the item generation for the ItemsControl as well as nice helper methods to interact with those containers. I needed this functionality for some silverlight controls that I was working on so I wrote a small class to make this easier. If item container generation is a totally new concept to you check out Dr. WPF’s great overview here. The ItemContainerHelper class provides four helper methods: ContainerFromIndex, ContainerFromItem, IndexFromContainer, and ItemFromContainer. The functionality provided by these methods is pretty straight forward.
In order to use these methods within a custom ItemsControl you just need to do two things which are illustrated in the ContainerTrackingListBox class in the sample linked below. In PrepareContainerForItemOverride you need to call the AddContainer method on an instance of ItemContainerHelper within your ItemsControl. PrepareContainerForItemOverride is called by Silverlight when the container has been created. You also need to tell ItemContainerHelper about any changes to the items in the ItemsControl. To do this call IncorporateItemChange from within the OnItemsChanged override of the ItemsControl.
That’s all there is to it and now you can easily access the item containers generated by an ItemsControl.
You can download the sample code using this class here.
Manipulating Silverlight Path Data
I’ve been playing with Paths in Silverlight. Silverlight provides basically the same functionality as WPF for vector graphics using Paths, at least as far as I can tell so far. Despite having worked with WPF for almost 4 years I’ve actually spent almost no time working directly with Paths. So, I decided to build a control that would allow you to easily manipulate the points associated with Paths so I could understand the nitty gritty of Paths in Silverlight. I’m not sure how useful this is, but I can think of a few good scenarios and hopefully someone finds it useful.
The control I came up with I called PathEditor. It is a ContentControl that a Path control can be placed inside of and it will provide the ability to grab the points within the path and move them around. Click on the below image of the the square path to play with the control:
You can get the source here.
The xaml for the above app looks like this:
<edit:PathEditor Margin="100"> <Path Stroke="Black" StrokeThickness="2"> <Path.Data> <PathGeometry> <PathFigure StartPoint="0,0" IsClosed="True"> <QuadraticBezierSegment Point2="40,0" Point1="10,0" /> <LineSegment Point="40,40" /> <LineSegment Point="0,40" /> </PathFigure> </PathGeometry> </Path.Data> </Path> </edit:PathEditor>
I won’t go into crazy detail about the code in this sample, but here’s a quick overview. The control derives from ContentControl so that it can contain a Path control. In WPF I would have derived from FrameworkElement and manually added and removed the child from the VisualTree so that I could force the child to be of type Path. Unfortunately, Silverlight doesn’t provide the methods needed to do this. So, ContentControl will have to do. :-) In PathEditor.OnContentChanged you can see the code that makes sure the content is a Path and then calls PrepareEdit. PrepareEdit enumerates through the figures in the Path’s Geometry (assuming it is a Path geometry as that’s the only type that works with this control) and adds all the associated segment’s points to private _points dictionary. The value that is keyed off the Point is a PointInfo object that contains two things. It contains the current Segment and the PropertyInfo object representing the property. The PropertyInfo objects are static members. If you are unfamiliar with PropertyInfo and .Net Reflection check out the msdn docs here. I’m using PropertyInfo in this way to make it very easy to set the property with new values later. Note that the control currently only works with LineSegment, ArcSegment, BezierSegment, and QuadraticBezierSegment.
Now that the control has a list of the points within the path and the associated properties, it is concerned with three mouse events; MouseMove, MouseLeftButtonDown, and MouseLeftButtonUp. In OnMouseLeftButtonDown the control determines if the mouse is “close enough” to one of the points within the path and if it is then it captures the mouse and stores that point for later calculations. In OnMouseMove the control then calculates the movement of the mouse and updates the associated property with the new value. OnMouseLeftButtonUp simply cleans everything up.
There are a couple other “helper” controls in the project. PointAdorner is a custom ContentControl that is used as the point “handles”. I created this control for a couple reasons. First, I tried using ItemContainerStyle as I would in WPF, but for some unknown reason this is not supported on ItemsControl. It is built into ListBox. This makes no sense to me. ItemContainerStyle should be supported at the lowest ItemsControl level in the inheritance hierarchy. I really hope this changes prior to release. It was fairly easy to build the ItemContainerStyle functionality myself though, so I tried that. The next problem I ran into was using Bindings in the Style itself. When I did that I got one of the standard unhelpful silverlight exceptions. So, I finally built PointAdorner so that it could explicitly set the Canvas Top and Left to the Y and X values of the contained Point. PointAdornerItemsControl is a custom ItemsControl that is used for displaying the point handles. It simply returns a PointAdorner as the item container from GetContainerForItemOverride. It also manually sets the Content and ContentTemplate of the PointAdorner in PrepareContainerForItemOverride. Again, I think this should be pushed down into ItemsControl. Apparently ItemsControl only wires things up properly if the item container is a ContentPresenter. I don’t see any reason why it couldn’t also work with ContentControls.
You can see these controls in use in the default style for PathEditor in generic.xaml. In the default style the PointAdornerItemsControl’s ItemsSource is bound to the Points property on the PathEditor. Btw, this property is of type IEnumerable because of what is apparently a known bug: http://silverlight.net/forums/p/21263/74504.aspx
I’m sure there are several bugs in this code and probably perf issues with any large path data. If anyone finds any bugs or have any questions please send them my way.
Creating a Silverlight FrameworkTemplate in code
When I tried to create a ItemsPanelTemplate in code it didn’t appear that there was a way to do this. Unless I’m missing something there must be some magic happening with the Silverlight XAML parser to create FrameworkTemplates (ItemsPanelTemplate for ItemsControls and DataTemplate in lots of cases). If I’m missing something I’d love for someone to let me know.
You might ask why I’d even want to do that. Sometimes in WPF I will create controls that derive from ItemsControl but have some fairly specialized behavior that depends on a ItemsHost panel of a certain type. The ItemsControl and Panel will work together with the ItemsControl providing item generation (usually returning a custom container from GetContainerForItemOverride) and the Panel providing the layout (of course). If you’re new to ItemsControls check out Dr. WPF’s great series on ItemsControls starting here. I came upon this issue while looking at ways in Silverlight to enforce that ItemsHost panel’s type (I’ve never really found a great way that I really like to do this in WPF either).
Anyhow, the way I eventually did this was using XamlReader.Load, like this:
private ItemsPanelTemplate GetItemsPanelTemplate() { StringBuilder itemsPanelTemplateXaml = new StringBuilder(); itemsPanelTemplateXaml.Append("<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">"); itemsPanelTemplateXaml.Append("<StackPanel />"); itemsPanelTemplateXaml.Append("</ItemsPanelTemplate>"); return (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml.ToString()); }
This way the parser does it’s magic and we get back an ItemsPanelTemplate. This method can be used to create any type from XAML, but this is the first time I’ve run into a scenario where it seems to be required. This works, but feels a little hacky. Of course, I’ve had that feeling several times while learning Silverlight.
Inking with a Silverlight Custom Cursor
Nate mentioned in his post about editing the custom cursor in Blend that he wanted to get the InkPresenter wired up. With a quick skim of this great article it was trivial. WPF has a full blown InkCanvas control that handles adding all the strokes in response to the mouse events, but in SL you have to add the strokes yourself. In a simple case it only takes a few lines of code. Check out Page.xaml.cs in this ink enabled version of the sample and source.
Silverlight 2 Custom Cursors
UPDATE: This code has been extended and improved upon in this post.
When I first started playing with Silverlight 2 one thing I noticed was there was no way to use a custom cursor in a Silverlight app like you could in a WPF app. I’ve put together a sample of how you could create custom cursor like behavior in a Silverlight app.
This is the same way I’d do something like this in WPF app (although WPF supports using custom .cur cursors which can be used in many scenarios). A Canvas is used to host the element that is acting as the cursor and it is positioned at the mouse cursor location. When a custom cursor is being displayed the actual cursor is set to None.
The CustomCursorAdorner class in the sample code derives from Canvas and adds a couple attached properties. The fist attached property is CustomCursor. This property can be set to any UIElement and this element will be used as the cursor when the mouse is over the element. The second attached property is ActiveAdorner and it is set to the actual CustomCursorAdorner where the cursor element should be hosted. For those not coming from a WPF background or entirely new to XAML, attached properties are an awesome way to add behavior to elements as is done here. So, the XAML to use this control looks like this:
<Grid> <Rectangle Fill="Red" Width="100" Height="100" cc:CustomCursorAdorner.ActiveAdorner="{Binding ActiveAdorner}"> <cc:CustomCursorAdorner.CustomCursor> <TextBlock Text="My Cursor" /> </cc:CustomCursorAdorner.CustomCursor> </Rectangle> <cc:CustomCursorAdorner x:Name="cursorAdorner" /> </Grid>
The above code would show a red rectangle and when the mouse is over the rectangle the cursor would change to the TextBlock “My Cursor”.
In the sample code the ActiveAdorner property is on an object that is set as the DataContext of the parent Grid. That property is set to the cursorAdorner CustomCursorAdorner. This is a workaround for the lack of ElementName bindings in Silverlight 2 Beta 2. This is done in the sample in Page.xaml.cs.
Click on the below screenshot of the sample to see it in action and download the source here.
BTW, the pad and pencil vector graphics both came from openclipart.org and were exported to xaml from InkScape (the latest builds support xaml).
Django is Dawesome, Part 1 of N
A few months back I decided I wanted to learn some new technologies. For my entire professional career I have been working with Microsoft technologies. For the last four I have been working entirely on rich client applications (mostly using WPF). So, I decided to do something I thought I’d never do. I bought a mac; specifically a macbook pro (which I mostly love, but that’s another post). That started me down a windy path that eventually brought me to Django and Python. I plan to do several posts about django as I learn and discover more about the framework. Given that I come from an MS technology background this series could probably be subtitled “Django and Python for .Net and C# Devs”. Hopefully this will be helpful to others coming from an MS background. OK, enough of the background let’s get to the substance.
Django is a web framework built on python. It provides a ton of functionality that I’ve found extremely cool. In this first post I’ll discuss one of my favorite features: url dispatching. The complete documentation for django’s url framework can be found here.
URL Dispatching
Django provides a very nice system for defining the urls within an application. To be honest, this was the first thing that drew me to django. I can’t stand cryptic, nonsense urls like most web apps use. Plus, why should I care if you used classic asp (.asp), asp.net (.aspx), php, etc. You should be able to look at a url and at least have some idea what it represents. Django’s url mapping framework allows you to map any url to any view function within your django application. Here’s an example of what the url config code looks like:
from django.conf.urls.defaults import *
urlpatterns = patterns(”,
(r‘^test/path/$’, myapp.views.testview),
)
The first line in the above code imports everything (*) from the django.conf.urls.defaults module. This is similar to a using statement in C# except that django.conf.urls.defaults is not a namespace it is an object itself (in this case a module object). By importing it in this way we can access all members of the module, including functions on the module such as patterns(). The next bit of code calls patterns() to set the urlpatterns variable. The first argument to the patterns function is the view prefix. The view prefix can be used to cut down on the amount of repetitive code if your view functions have the same prefix. The next argument s a python tuple that contains a regular expression and the callback function that should be called when a url that matches that regular expression is requested. There is no exact equal in C# for a python tuple, but it would be the same as an immutable .Net array. The regular expression can be as complicated as your url scheme requires and you can capture arguments out of the regex (maybe more on that in a future post). Another thing to note is the ‘r’ that precedes the regular expression string. The ‘r’ indicates that the string is a raw string, this is equivalent to ‘@’ in C#.
That’s all there is to mapping a url to a view function. There’s a lot more functionality available here, but this is a simple example. (See here for more details of this API). I love how simple and flexible this is. You can define your url scheme and independently define the view functions in whatever manner you like. I’m not aware of any equivalent functionality in .Net that is nearly as powerful as this feature (although I have been away from .Net web technologies for several years).
Let’s also look at a quick example of a view function. The view function takes a single argument. The argument is an HttpRequest object that contains all the information about the request that initiated the call to the view function. This object is just like the asp.net Request object. Here is code for a very simple view function:
from django.shortcuts import render_to_response
def testview(request):
return render_to_response(‘index.html’,
{“key”: my_value},
context_instance=RequestContext(request))
A view function can do whatever it wants as long as it returns an HttpResponse object. In the above code the render_to_response function is used to create the HttpResponse object. The only required argument to render_to_response is the name of the template to use. (Django contains a great templating model for generating html that I’ll post about soon). In the above code ‘index.html’ is the name of the template file. Above two additional optional arguments are passed. The second argument is a dictionary of values that will be available within the template. Values in the dictionary can be accessed in the template via the key. For those new to python, dictionaries are “built-in” to the python language. They are created using the following syntax: {“key”: value, “key2”: value2}. This takes some getting used to for those of us that are used to “new Dictionary()”, but is very cool.
The third argument is the context instance that the template will use when rendering. By default the context only contains values set via the dictionary discussed early, but if you need values from the request itself you can create a RequestContext as above.
That’s all it takes to map a url to application logic. Given the above code in a django application you could navigate to the logic in the testview function via http://www.myapp.com/test/path/. It’s very straightforward and a very elegant design from the creators of django. You could very easily point this url to an entirely different view function.
Well, that’s a quick overview of django’s url dispatching. It’s pretty sweet. ![]()
Not sure what to think of this…
I spend a lot of time thinking about the world economy. Much more than I should I’m sure since it’s not related at all to my day job, but I find it fascinating. I read this article today on cnn.com and I was blown away by the way they talk about the changing labor market in China:
A tough new Chinese labor law went into effect on Jan. 1, requiring employers to offer employment contracts, a social security program and overtime pay.
…
“We were running two, 12-hour shifts every day, but the new labor law restricted how long the temp workers could be on the job,” says Hornbein. “It was difficult to find enough workers to cover six, four-hour shifts. Now I have a machine to do the work, which has increased my capital expenditure.”
Could you imagine anyone writing this about a worker or labor policy in the US? Not in the last 100 years or so I’m sure. This reminds me of the “bad old days” you learn about in high school. The times before labor unions when workers were forced to work huge amounts of hours with low pay and little benefits. Is this person really complaining about not being able to make a chinese worker work 12 hour shifts?

