Book review: Deadline
Mon, Feb 8 2010 18:43

In this last weekend I was a little burnt out, so I decided it was time to relax. And that’s why I’ve decided to have a go at Tom DeMarco’s Deadline: a Novel About Project Management. I guess this is an interesting (and different) way of presenting several important aspects associated with project management: the author tells us the stories of Mr. Thompkins as he is put in charge of Morovia’s sfotware development. Overall, I guess this is really an funny reading, though I’m not sure if this book is for someone that is getting started with project management. I’m giving it an 8/10.

by luisabreu | with no comments
Filed under:
The new auto-start feature
Fri, Jan 29 2010 14:52

Version 4.0 of ASP.NET introduces a new feature called auto-start. The idea is simple: to improve the performance of the web app by allowing apps to run some expensive code before the first request comes. I must say that this is really an interesting concept (and no, I won’t be going into details here because the white paper already explains most of what you should know).

I’m only mentioning this here because this will only work from windows 7 and windows 2008 server R2 onwards. This is something which makes me really sad because people running windows 2008 server won’t be able to use this feature. I really believe that it’s time for MS to change the interaction between IIS and the OS…I mean, am I the only one that is fed with having the IIS version tied up with the OS version???

by luisabreu | with no comments
Filed under:
Routed events in Silverlight
Fri, Jan 29 2010 14:28

Routed events were introduced by WPF and they’re responsible for enabling several advanced scenarios in that platform:

  • tunneling: in this case, the event is first raised in the root and goes “down the tree” until the source element that generated the event is reached;
  • bubbling: in this case, the event bubbles from the source element to the root element;
  • Direct: the event is only raised in the source element.

Once again, the use of routed events in Silverlight is limited. By default, it only exposes a couple of routed events and it only supports bubbling (ie, there’s no tunneling for routed events in Silverlight).In order to illustrate the bubbling feature, we’ll start running the following example:

<UserControl x:Class="Tests.test"
    x:Name="uc"
    xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:Tests"> <Canvas Width="150" Height="200" x:Name="cv"> <StackPanel x:Name="sp"> <TextBlock Text="Click me" x:Name="bt" /> </StackPanel> </Canvas> </UserControl>

And here’s the code-behind:

public partial class test : UserControl {
    public test() {
        InitializeComponent();
        bt.MouseLeftButtonDown += PrintInfo;
        sp.MouseLeftButtonDown += PrintInfo;
        cv.MouseLeftButtonDown += PrintInfo;
        MouseLeftButtonDown += PrintInfo; 
    }
    private void PrintInfo(
Object sender, MouseButtonEventArgs e) { var info = String.Format(
"elemento original: {0} - elemento actual: {1}\n", ((FrameworkElement)e.OriginalSource).Name, ((FrameworkElement)sender).Name); MessageBox.Show(info); } }

If you run the previous sample, you’ll notice that the event bubbles from the button until it reaches the root user control. The MouseButtonEventArgs class ends up inheriting from the RoutedEventArgs class. Due to that, we can access the OriginalSource property and find out which object is responsible for the event that is bubbling. Notice that the MouseButtonEventArgs ends up adding the read/write Handled property: when you set it to true, the event won’t be propagated beyond the current element that is responsible for the event that is being fired.

Unfortunately, you can’t really create custom routed events in Siverlight. The reason is simple: there isn’t a public API for letting you do that (if you dig into the code of the MouseLeftButtonDown event instantiation, you’ll notice that routed events are created through the RoutedEvent constructor which is internal). What this means is that you’re limited to creating “normal” events in your custom classes. I’m not sure if this limitation will ever be removed from Silverlight. And I guess this sums it up quite nicely. Stay tuned for more on Siverlight.

by luisabreu | with no comments
Filed under:
Vacations vs work time
Thu, Jan 28 2010 18:32

I’ve just finished reading an excellent post by Scott Berkun on this topic. I couldn’t agree more, but unfortunately, things don’t work like that (and the problem is not limited to America only!)

by luisabreu | with no comments
Filed under:
Book review: Confessions of a public speaker
Wed, Jan 27 2010 10:35

I’ve just finished reading Scott Berkun’s latest book. Scott is a really good communicator and you can say that I’ve been a fan of his work since his first best seller (Making things happen), which, btw, I’ve reviewed here a long time ago.

You’ll be able to find several interesting topics in Confessions of a public speaker. Besides tips on how to improve your skills, you’ll also find some advice on how to handle several problems which you’ll eventually face when doing public speaking in front of lots of people. I’m really convinced that if you’re a public speaker, then you’ll learn a couple of things by reading this book. I know that the presentations I’ve done in the past would have been better if I had this book at the time. Anyway, it’s never late and I’m really under the impression that by using Scott’s tips, I’ll be doing a better job when I need to talk in public in future gigs.

I must confess that I did really enjoyed the chapter on confessions where you can find a collection of short essays on things that have gone wrong during presentations (of professional speakers). Overall, I found this a pleasing and easy reading book with lots of good advices. Note: 9/10.

by luisabreu | 2 comment(s)
Filed under:
Creating attached properties
Wed, Jan 27 2010 10:20

Now that you understand what attached properties are, we’re in the position to look at what is needed for creating attached properties. Since we’re building custom code, we do really need to rely in the RegisterAttached method (of the DependencyProperty class). Creating a new attached properties means doing the following:

  1. adding a static DependencyProperty field to the class;
  2. using the RegisterAttached method for creating the field which is used as a store for the dependency property;
  3. add a couple of static methods named GetXXX/SetXXX (where XXX is the name of the property) used as shortcuts for getting and setting the attached property from code.

Let’s suppose that we were creating a new look-a-like Canvas class. Here’s the code you’re expected to add to your class for the Left property:

public class MyCanvas: Panel {
    public static DependencyProperty LeftProperty;
    static MyCanvas() {
        LeftProperty = DependencyProperty.RegisterAttached(
            "Left",
            typeof (Double),
            typeof (MyCanvas),
            new PropertyMetadata(null));
    }
    public static Double GetLeft(UIElement element) {
        return (Double) element.GetValue(LeftProperty);
    }
    public static void SetLeft(
UIElement element, Double value) { element.SetValue(LeftProperty,value); } }

As you can see, we need to start by registering the attached property through the RegisterAttached method. The method expects four parameters: the name of the property, the type of the property, the type of the “owner” of this property (generally, this will be the class that exposes the attached prop) and the associated metadata (notice that if you’re not interesting in setting a default value or in associating a callback method with the property, then you can simply pass null to the PropertyMetadata constructor like I did in the previous snippet).

After registering the property, you’re supposed to add a setter and a getter: in this case, I’ve called them GetLeft and SetLeft in order to comply with the recommendations. Once again, these methods are there as helpers and you can bypass them when writing you code (though I do recommend using them whenever possible).

And that’s really it…you don’t need anything extra for exposing an attached property. Stay tuned for more on Silverlight (there’s still a long road to go!)

by luisabreu | with no comments
Filed under:
Attached properties
Mon, Jan 25 2010 14:22

An attached property is an interesting concept. The docs define it as:

An attached property is intended to be used as a type of global property that is settable on any object

An attached property lets you define properties in an object which are only defined by its parent element. Once again, if you have any experience with WPF, you should take into account that the number of attached properties is much smaller than what you have in WPF (for instance, TextElement.FontStyle is implemented as an attached property in WPF, but it’s a simple dependency property in SL).

There is also another interesting gotcha (when compared with WPF): it seems like the XAML parser “knows” about several predefined attached properties (registered as core dependency properties) and lets you use them without registering them through the RegisterAttached method (ex.: Canvas.Left is an attached property, but it’s not registered through the RegisteredAttached method). I guess this is just another of those quirks which make Silverlight a much less “predictable” framework than WPF.

The simplest way to understand these type of properties is to look at an example: we’ll simply take a look at how you can use the Canvas.Left/Canvas.Top attached properties to position an element.

<Canvas Width="500" Height="500">
    <Rectangle Canvas.Left="10" 
Width="100" Height="20" x:Name="rect1"> <Rectangle.Fill> <SolidColorBrush Color="Blue" /> </Rectangle.Fill> </Rectangle> <Rectangle Canvas.Left="200" Width="100" Height="20"> <Rectangle.Fill> <SolidColorBrush Color="Red" /> </Rectangle.Fill> </Rectangle> </Canvas>

The Left and Top properties are exposed by the Canvas class. If you take a quick peek at the class, you’ll notice that each attached property is backed up by a dependency property (notice the TopProperty and LeftProperty fields). Attached properties can also be accessed from code through a pair of static methods on the form GetXXX/SetXXX, where XXX is the name of the property (in these case, you’ll have GetLeft and SetLeft for setting the Left attached property). Do notice that both GetXXX and SetXXX expect a reference to an object (the type of the object depends on the types of objects you’re extending with the attached properties). The SetXXX method expects a second parameter, generally of type Object, which is used for setting the value of the attached property.

Typically, custom attached properties need to be registered through the DepedencyProperty.RegisterAttached method (something which is done from within the static constructor). However, in the case of predefined Silverlight control’s attached properties, they’re simply registered with predefined IDs which (I think?) are used internally by the platform to identify the type of behavior which is associated with that specific property.

I was thinking about showing you how to create a custom attached property, but I’ll leave that for a future post. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under:
Clearing values of dependency properties
Fri, Jan 22 2010 10:28

In the previous posts, we’ve met several interesting features associated with dependency properties. I’m not sure if you’ve really had the time to understand the implications of having multiple “providers” (or if my writing was good enough for making you take into account those implications – which probably is true!), so I’ve though about writing a post on how to correctly clear the value of a dependency property. Suppose we’ve got the following XAML:

<UserControl x:Class="Tests.MainPage"
    xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" FontSize="30"> <UserControl.Resources> <Style TargetType="TextBlock"> <Setter Property="Foreground" Value="Blue" /> <Setter Property="Height" Value="100" /> </Style> </UserControl.Resources> <TextBlock Text="Hello, world!" x:Name="info" /> </UserControl>

And that we’ve used the following C# code for handling mouse enter/leave events:

public MainPage() {
  InitializeComponent();
  info.MouseEnter += (sender, e) =>
  {
    info.Foreground = new SolidColorBrush(Colors.Red);
  };
  info.MouseLeave += (sender, e) =>
  {
    info.Foreground = new SolidColorBrush(Colors.Blue);
  };
}

And yes, you’re right: we don’t need the { } to delimiter the instructions in the previous lambdas. Now that we’ve moved that out of the way, it’s time to remember what we’ve discussed in the previous post: the order by which you can influence the value of a dependency property. As we’ve seen, the value of a dependency property can be influenced by several “providers” where each “provider” might end up overriding the value set by another “provider” (it all depends on the priority of each provider!).

If you pay attention to the code (XAML), you’ll notice that the initial Foreground color of the TextBlock is set from a style setter. However, the code used to handle the MouseEnter/MouseLeave ends up setting the *local* value of the dependency property. In this case, there really isn’t any problem because we’re setting the local value of the dependency property to the same value as the one we had in the style setter. However, that is probably not what the author intended…He probably would really love to be able to just change the color to red on enter and go back to the previous existing color (whatever that color is) when the mouse exits the area delimited by the TextBlock.

This feature is known as “cleaning the value of a dependency property” and there’s a method for doing that: ClearValue. Take a look at the rewritten MouseLeave event handler:

info.MouseLeave += (sender, e) => 
info.ClearValue(TextBlock.ForegroundProperty);

As you can see, the ClearValue method expects a reference to an existing DependencyProperty object (in this example, that would be the ForegroundProperty field of the TextBlock class) which ends up being cleared. Whenever you need to do something like this (clear a value which has been temporarily set), you should always use the ClearValue method. Notice that using this method lets you change styles dynamically and you’ll always get the correct color when the mouse leaves the element.

And I guess that is all for now. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under:
Setting the value of a dependency property
Thu, Jan 21 2010 10:23

One of the things I’ve mentioned in the previous posts is that the value of a dependency property at runtime can be influenced by several “providers”. That means that there needs to be some sort of order which governs the way providers affect the final value of a dependency property (this order is known as precedence list). The final value of a dependency property at runtime is obtained after all the items in the following list have been evaluated by the presented order:

  1. Default value;
  2. Style setters;
  3. Templated properties;
  4. Local value;
  5. Animations.

The default value of a dependency property depends on whether  you’ve passed a default value through the property metadata or not. When you pass a value through the PropertyMetada object during the dependency property registration (my preferred method for defining a default value), that value is used as the default one. If you don’t set the default value through metadata, then the default value depends on the type used for storing the dependency property (reference types use null, value types use the default constructor and primitive types default to the default primitive values – another extra note: the docs say that the default value for a string-type dependency property is the empty string; however, my tests always return null as the default value when string is used as the type of the dependency property. are my tests wrong? or are the docs wrong?).

Style setters will overwrite any style value that has been defined through the default value of a dependency property (you’ll need to look at the docs to see which style values you can define for each control).

Template properties will only be used for objects that are built dynamically from templates. Typically, you’ll end up using TemplateBinding reference for setting the values of the dependency properties. However, you can also define the value of a property directly (without using a TemplateBinding), making that the value of that dependency value in all objects generated from the template.

Local values are set through direct property access or by using the SetValue method inherited from the DependencyObject class. Finally, animation values will always “override” the value of a dependency property. If that was not the case, then the value of the property wouldn’t change and there simply wouldn’t be any animation.

And I guess this sums it up quite nicely…Stay tuned for more on Silverlight.

by luisabreu | 2 comment(s)
Filed under:
Dependency properties and XAML gotchas
Wed, Jan 20 2010 14:31

As I’ve said before, dependency properties introduce several advantages over the traditional CLR properties. However, there might some gotchas associated with their use from XAML. As we’ve seen, dependency properties are defined through static fields and exposed through .NET properties for easy consume from C#/VB code (as we’ve seen, getting and setting the value of the property is achieved through the GetValue/SetValue methods inherited from the DependencyObject class). If you’re coming to Silverlight from WPF, you already know that getters and setters of the property wrappers are “bypassed” at runtime when you set the properties from XAML and that’s probably what’s going to happen in Silverlight too. Is it? Are you sure? The docs say that is the correct behavior, but I’m not seeing that in my Silverlight 4.0 tests…

Take a look at the following (dumb) custom control:

public class MyTextBox:TextBox {
 public static readonly DependencyProperty DurationProperty;
 static MyTextBox() {
        DurationProperty = DependencyProperty.Register( 
                  "Duration", 
                  typeof(Int32),
                  typeof(MyTextBox),
                  new PropertyMetadata( 0, 
                  (sender, e) =>{} )
        );
 }
 public Int32 Duration {
    get { return (Int32)GetValue(DurationProperty); }
    set {
          if (value <= 0) {
            throw new ArgumentOutOfRangeException();
          }
          SetValue( DurationProperty, value ); 
} } }

Now, check the following XAML:

<my:MyTextBox Duration="-1" /> 

If you’re expecting to see an exception during loading, then you’re correct. If you’re thinking that the code will run without any problems, then you’re wrong. This is another interesting gotcha that might bite you if you’re coming to Silverlight from WPF (btw, the docs *do* say that the behavior is the same as the one we get in WPF, but the truth is that I’ve run the previous code and the setter is always hit when setting the value from XAML – is this a changed when compared with SL 3?). 

So, how can you build a control which works in both platforms with minimum work? For instance, in the previous example,  I wanted to make sure that you can only pass positive values to the Duration property. The correct way of doing that type of check is by relying on the metadata that is passed during the property registration. Take a look at the revised code:

static MyTextBox() {
    DurationProperty = DependencyProperty.Register( 
                "Duration", 
                typeof(Int32),
                typeof(MyTextBox),
                new PropertyMetadata( 0,
                (sender, e) =>
                {
                  if ((Int32)e.NewValue <= 0) {
                   throw new ArgumentOutOfRangeException();
                  }
                })
    );
}
public Int32 Duration {
    get { return (Int32)GetValue(DurationProperty); }
    set { SetValue( DurationProperty, value ); }
}

As you can see, we’re passing a lambda to the property changed callback method. Whenever you try to set a new value, this method ends up being called. The NewValue property gives you access to the new value that is being passed to the dependency property and that’s why we’re using it to see if we’re getting a positive number.

Besides getting the new value, you can also get a reference to the current existing value (OldValue property) and a reference to the dependency property that is being changed (Property property). And I guess that is all for now. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under:
Dependency property and value inheritance
Mon, Jan 18 2010 12:36

In the previous post, I’ve talked a little bit about dependency properties and on how they’re defined. One of the advantages of using those properties is value inheritance. Take a look at the following snippet:

<UserControl x:Class="Tests.MainPage"
    xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" FontSize="30"> <StackPanel> <TextBlock FontSize="20">Hello there!</TextBlock> <ListBox> <ListBoxItem FontSize="12" Content=" Item 1" /> <ListBoxItem Content="Item 2" /> </ListBox> <Button Content="Say Hi!!!" /> <Button Content="Say Hi2!!!" FontSize="50" /> </StackPanel> </UserControl>

If you run the previous sample, you’ll notice that the elements that don’t override the FontSize dependency property end up inheriting the value of its parent’s property value. This is one of the advantages of using this kind of property in Silverlight and WPF. Do notice that unlike WPF, where you can opt in to value inheritance by passing FrameworkPropertyMetadataOptions.Inherits to the metadata info you use during the dependency property definition (register method call), in Silverlight there’s not way to influence this behavior.

And that’s it for now. Stay tuned for more about Silverlight.

by luisabreu | with no comments
Filed under:
Getting started with dependency properties
Mon, Jan 18 2010 10:31

The dependency property concept was introduced by WPF 1.0 for exposing rich functionality from XAML. Dependency properties support several features exposed by Silverlight (styling, animation and data binding, for instance). Unfortunately, they also increase the complexity associated with property definition. Dependency properties values at runtime depend on several things. For instance, it could depend on an animation which continuously changes the value of a property or it could depend on the value of its parent property (ie, it could inherit the value from its parent if the value isn’t explicitly set). When compared with the basic CLR properties, dependency property introduces the following advantages:

  • change notifications;
  • property value inheritance;
  • support for multiple “providers” which can set its value.

Now that I’ve presented some of the ideas behind the concept, lets see how dependency properties are implemented. Dependency properties are exposed through “normal” CLR properties which wrap access to a field created through the DependencyProperty.register method. Take a look at the following snippet (from the ButtonBase class):

 

public abstract class ButtonBase : ContentControl {
    public static readonly DependencyProperty ClickModeProperty;
    static ButtonBase() {
        ClickModeProperty = DependencyProperty.Register(
        "ClickMode", 
        typeof(ClickMode), 
        typeof(ButtonBase), 
        new PropertyMetadata(
new PropertyChangedCallback(
ButtonBase.OnClickModePropertyChanged))); //removed } public ClickMode ClickMode { get { return (ClickMode)base.GetValue(ClickModeProperty); } set { base.SetValue(ClickModeProperty, (Enum)value); } } private static void OnClickModePropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e) { ClickMode newValue = (ClickMode)e.NewValue; if (((newValue != ClickMode.Release) &&
(newValue != ClickMode.Press)) &&
(newValue != ClickMode.Hover)) { throw new ArgumentException(…); } } }

ClickMode is a dependency property. The ClickModeProperty is the real dependency property which is wrapped through the ClickMode property. By convention, all dependency properties are stored through public static fields and their names ends with the Property suffix. Another conclusion which can be taken from the previous snippet is that dependency properties are always created through the DependencyProperty.Register method. This method expects the following parameters:

  • name: sets the name of the dependency property. This name is the same as the one that is used for the CLR property which wraps the dependency property field;
  • type: identifies the type of the dependency property that is registered;
  • owner: identifies the type of the object that “owns” the current dependency property;
  • metadata: object of type PropertyMetadata which lets you set the default value and/or a notification callback method.

After introducing the dependency property field and creating the dependency property through the register method, convention (and easy of use) makes us add a new property which wraps the dependency property field. As you can see from the previous snippet, the ClickMode property is a read/write property which uses the GetValue/SetValue methods inherited from the DependencyObject base class.

Do notice that unlike WPF, where everything is managed, in Silverlight dependency properties values depend on unmanaged code. Besides that, you should also keep in mind that Silverlight’s dependency properties don’t expose the same amount of functionality you have in WPF. And I guess this is more than enough for getting started with dependency properties. We’ll keep looking at them in the next posts. Stay tuned!

by luisabreu | 2 comment(s)
Filed under:
Object trees in Silverlight
Fri, Jan 15 2010 12:15

Whenever you use XAML to build an interface, you’ll end up generating Silverlight objects (obtained from the XAML parsing at runtime). In practice, you’ll end up with an object tree (this is really obvious when you look at the XAML – and yes, I’m assuming you’re using indentation in you XAML files) based on the relationships established between those objects (after all, objects have properties which can hold other objects or collection of objects). In Silverlight, most of this object tree structure is treated as an implementation detail, though you can still interact with it from code (ex.: many elements inherit from FrameworkElement which exposes the Parent property that lets you navigate from the “current” element to its parent).

WPF has two interesting concepts: logical and visual trees. Both views apply “filters” to the object tree and will only return specific elements (which depend on the filter). The best way to understand these concepts is to look at a simple example. Take a look at the following XAML:

<UserControl x:Class="Tests.MainPage" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <TextBlock>This is the title</TextBlock> <ListBox> <ListBoxItem Content="Item 1" /> <ListBoxItem Content="Item 2" /> </ListBox> <Button Content="Click me!" /> </StackPanel> </UserControl>

The logical tree associated with the previous snippet would look like this:

* UserControl
    * StackPanel
         * TextBlock
            * This is the title
         * ListBox
            * ListBoxItem
                 * Item 1

As you can see, the logical tree will have all the objects (and their properties/events) which have been set up in the code (XAML or procedural code). In WPF, you can effectively access this logical tree and navigate through it (though the LogicalTreeHelper class). In Silverlight, that is not possible (since there is no LogicalTreeHelper class). You might be wondering why it’s important to care about logical trees since it’s only used internally by Siverlight. It happens that several important behaviors available are tied to this logical tree. For instance, property values are (sometimes) propagated from parent to children (more about this in future posts) and this only happens because Silverlight is able to build a logical tree. Unfortunately, the logical tree used by Silverlight only supports a subset of the WPF available behaviors (but that should be enough for most scenarios).

The visual tree is another tree which is built from the original object tree. In practice, the visual tree breaks down the objects maintained in the object tree into their core *visual* components. For instance, here’s the visual tree for the previous XAML:

*START* 0---Tests.MainPage
*START* 1---System.Windows.Controls.StackPanel
*START* 2---System.Windows.Controls.TextBlock
*END* System.Windows.Controls.TextBlock
*START* 2---System.Windows.Controls.ListBox
*START* 3---System.Windows.Controls.Grid
*START* 4---System.Windows.Controls.Border
*START* 5---System.Windows.Controls.ScrollViewer
*START* 6---System.Windows.Controls.Border
*START* 7---System.Windows.Controls.Grid
*START* 8---System.Windows.Controls.ScrollContentPresenter
*START* 9---System.Windows.Controls.ItemsPresenter
*START* 10---System.Windows.Controls.VirtualizingStackPanel
*START* 11---System.Windows.Controls.ListBoxItem
*START* 12---System.Windows.Controls.Grid
*START* 13---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*START* 13---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*START* 13---System.Windows.Controls.ContentPresenter
*START* 14---System.Windows.Controls.Grid
*START* 15---System.Windows.Controls.TextBlock
*END* System.Windows.Controls.TextBlock
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.ContentPresenter
*START* 13---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.ListBoxItem
*START* 11---System.Windows.Controls.ListBoxItem
*START* 12---System.Windows.Controls.Grid
*START* 13---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*START* 13---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*START* 13---System.Windows.Controls.ContentPresenter
*START* 14---System.Windows.Controls.Grid
*START* 15---System.Windows.Controls.TextBlock
*END* System.Windows.Controls.TextBlock
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.ContentPresenter
*START* 13---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.ListBoxItem
*END* System.Windows.Controls.VirtualizingStackPanel
*END* System.Windows.Controls.ItemsPresenter
*END* System.Windows.Controls.ScrollContentPresenter
*START* 8---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*START* 8---System.Windows.Controls.Primitives.ScrollBar Minimum:0 Maximum:0 Value:0
*END* System.Windows.Controls.Primitives.ScrollBar Minimum:0 Maximum:0 Value:0
*START* 8---System.Windows.Controls.Primitives.ScrollBar Minimum:0 Maximum:0 Value:0
*END* System.Windows.Controls.Primitives.ScrollBar Minimum:0 Maximum:0 Value:0
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.Border
*END* System.Windows.Controls.ScrollViewer
*END* System.Windows.Controls.Border
*START* 4---System.Windows.Controls.Border
*START* 5---System.Windows.Controls.Grid
*START* 6---System.Windows.Shapes.Path
*END* System.Windows.Shapes.Path
*START* 6---System.Windows.Shapes.Path
*END* System.Windows.Shapes.Path
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.Border
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.ListBox
*START* 2---System.Windows.Controls.Button
*START* 3---System.Windows.Controls.Grid
*START* 4---System.Windows.Controls.Border
*START* 5---System.Windows.Controls.Grid
*START* 6---System.Windows.Controls.Border
*END* System.Windows.Controls.Border
*START* 6---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.Border
*START* 4---System.Windows.Controls.ContentPresenter
*START* 5---System.Windows.Controls.Grid
*START* 6---System.Windows.Controls.TextBlock
*END* System.Windows.Controls.TextBlock
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.ContentPresenter
*START* 4---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*START* 4---System.Windows.Shapes.Rectangle
*END* System.Windows.Shapes.Rectangle
*END* System.Windows.Controls.Grid
*END* System.Windows.Controls.Button
*END* System.Windows.Controls.StackPanel
*END* Tests.MainPage

As you can see, several of the controls used in the previous XAML end up using other elements for generating its appearance (in future posts, we’ll see how and why this works like this and how we can customize the looks of a control). Btw, here’s the code I’ve used for getting the visual tree:

public partial class MainPage : UserControl {
 public MainPage() {
   InitializeComponent();
   bt.Click += (sender, e) => { PrintVisualTree(this, 0); };
 }
 void PrintVisualTree(DependencyObject obj, Int32 depth) {            
   Debug.WriteLine(
String.Format("*START* {0}---{1}",depth, obj) ); var totalCount = VisualTreeHelper.GetChildrenCount(obj); for (var i = 0; i < totalCount; i++) { PrintVisualTree(
VisualTreeHelper.GetChild(obj, i), depth+1); } Debug.WriteLine(String.Format("*END* {0}", obj)); } }

So, now you know that the object tree we have can be “filtered” into two important trees: logical and visual trees. On the one hand, logical trees end up supporting several of the behaviors we’ve got in Silverlight. On the other hand, visual trees are used for rendering the controls at runtime. And that’s it for now. Stay tuned for more in Silverlight.

by luisabreu | with no comments
Filed under:
More on XAML and content properties
Fri, Jan 15 2010 10:50

In a previous post, I’ve introduced the concept of content properties. The idea behind a content property is simple: you use the ContentPropertyAttribute to specify the property which will be set with the contents declared inside that element when the property element syntax is not used. Here’s a quick example that should make this concept perfectly clear:

<Button x:Name="info">
    <TextBlock Text="Say hi!" />
</Button>

In the previous snippet, the info Button’s Content property will be set to the TextBlock specified inside the <Button> element (btw, that happens because Button ends up inheriting from ContentControl which is annotated with the ContentPropertyAttribute to indicate that inner XAML contents are supposed to be passed to the Content property).

I’m only mentioning this topic again because there’s (another) small problem you might encounter if you’re coming into Silverlight from the WPF world. Take a look at the following snippet:

<Button x:Name="info">
    Say hi
</Button>

Loading that XAML means getting this error:

errorcontent

Ok, so what’s going on here? Once again all boils down to the XAML parser which is used by Silverlight. The following doc says this:

With the exceptions of TextBlock and Run, object elements in Silverlight cannot contain XML text nodes as an implicit way to set their text-type content properties. For example, <Button> hello world </Button> is not allowed in Silverlight XAML, you would have to specify <Button Content="hello world".../>. Again, note that there are some syntaxes (such as for Color) that might resemble object element with inner text syntax, but they are technically an initialization text syntax, which supplies the string to type-convert for initialization as inner text.

Not something I enjoy, but that’s the way it works. And that’s it for now. Stay tuned for more.

by luisabreu | with no comments
Filed under:
ASP.NET 4.0: Customizing encoding/decoding
Wed, Jan 6 2010 8:54

In the previous post, I’ve said that you can customize the way request validation is performed by creating a RequestValidator derived class. ASP.NET 4.0 will also let you run your custom logic for encoding: to do that, you need to create a new HttpEncoder derived class and override the methods you want to customize.

If you look at the HttpEncoder’s members list, you’ll see that it introduces several virtual methods which you can override to perform different actions. For instance, the HtmlEncode method is used whenever you call the Server.HtmlEncode method in your page.

After creating your custom encoder, you need to make ASP.NET use it by setting the encoder type in the httpRuntime section. The easiest way to achieve that is by adding something like this to the web.config file:

<httpRuntime encoderType="Livro.MyHttpEncoder"/>

And that’s it for now. Stay tuned for more on ASP.NET 4.0.

by luisabreu | with no comments
Filed under:
Oh, gosh! Validating user input is extensible
Tue, Jan 5 2010 22:55

[Update: added the missing web.config changed required to make it work]

ASP.NET has been performing some sort of validation on user input for ages. For instance, I guess that most of us know that there is a list of chars which can’t be introduced in a textbox (ex.: <) in order to help protect our pages against vulnerabilities. Now, this validation is lazy and is performed against the data passed through the request (even though the user input validation is the most know validation, it’s also performed against query strings, cookies, etc). Until now, we could only turn this feature on and off by setting the @Page’s ValidateRequest attribute.

The good news is that from ASP.NET 4.0 onwards, this feature is *extensible*. What this means is that we can create our own “validators” for checking the input. If you want to build your own “validator”, you’ll only need to create a new class which extends the RequestValidator class. Then you can override the IsValidRequestString method and writer your own custom validation logic:

public class MyRequestValidatory : RequestValidator {
        protected override bool IsValidRequestString(
            HttpContext context, string value,
            RequestValidationSource requestValidationSource,
            string collectionKey,
            out int validationFailureIndex ) {
            //some code
         }
    }

As you can see, the method receives several parameters which you can use to perform your logic. As you can probably deduce from its name, the value parameter contains the string that needs to be checked. The RequestValidationSource parameter can be used to determine the kind of HTTP data that has been passed to be validated. The validationFailureIndex should only have a non-negative value when the string passed through value has forbidden chars and it should indicate the position of the string where that invalid char is used. Oh, and I almost forgot: the collectionKey parameter identifies the name of the key in the request collection that is being validated.

After building the “validator”, you need to make ASP.NET use it. The httpRuntime section exposes the requestValidationType attribute which can be used for doing that:

<httpRuntime requestValidationType=" MyRequestValidatory" />

This is another small and “sweet” update to the existing framework. And I guess that’s it for now. Stay tuned for more on ASP.NET.

by luisabreu | 4 comment(s)
Filed under:
More simple goodies: setting the meta keywords and description from the server side
Mon, Jan 4 2010 21:28

This is the first post of the year! I guess that means I’ll need to wish you all a fantastic New Year and I really hope that everything you wish comes true!

Now, this is really a short post about two simple new properties that have been added to the Page class: MetaDescription and MetaKeywords. In fact, these are really simple shortcuts for the Description and Keywords properties exposed by the HtmlHead class (oh, btw, you can get access the header by using the Header property exposed by the Page class and this will only return a valid reference when you have a <head> element annotated with a runat=”server” attribute). As you’ve probably guessed, you can use the MetaDescription property to set the “description” <meta> element. On the other hand, you can use the MetaKeywords to set the keywords  <meta> tag.

As I’ve said before, these are really simple additions. But it’s also important to notice that adding simple features which make our lives easier end up contributing to improving the framework, right? And that’s it for today. Keep tuned for more on ASP.NET.

by luisabreu | with no comments
Filed under:
Merry Christmas and a Happy New Year
Thu, Dec 24 2009 17:08

See all next year!

by luisabreu | with no comments
Filed under:
Enabling session state programmatically
Fri, Dec 11 2009 15:18

“Finally!!!”, you say…I hear you man! With ASP.NET 4.0, we can enable/disable session state programmatically (like in C# code :) ). The new version of the framework adds a new method (SetSessionStateBehavior) to the HttpContext class. You’re supposed to pass it a value from the SessionStatebehavior to influence the use of session state. Currently, you can pass the following values:

  • Default: passing this means that everything works as before (ie, you control session through the @page directive or the <pages> entry in the web.config file);
  • Required: session state is enabled for read/write access;
  • ReadOnly: gives access to read only session state;
  • Disabled: turns off session state for the current request.

In practice, passing one of the last three methods means that eventual settings specified at the @Page directive or in the <pages> element of the config file are ignored. There’s a caveat: you can only use the new method influence the use of state until the AcquireRequestState event is fired. Doing it after means getting an exception.

And that’s it. Stay tuned for more on ASP.NET.

by luisabreu | with no comments
Filed under:
Another cool nudge: maintaining the selection of an element when using paging
Thu, Dec 10 2009 10:24

This is one of those simple things which really improves the use of controls like GridView and ListView. ASP.NET 4.0 adds the EnablePersistedSelection property to the GridView and ListView controls. To support this feature, the control ended up adding a new field (_persistedDataKey) which is saved in the control state of the control. Notice that what is persisted is the key that uniquely identifies the selected item (and not its position in the rows displayed by the grid.

When the grid needs to create its rows, it will update the SelectedIndex (and other associated props) by checking the data key of each item it is rendering against the value persisted in the _persisteDataKey field. What this means is that when you change the page and go to a new one that doesn’t have the previous selected item, you’ll end up getting –1 for the SelectedIndex property. I guess this isn’t really the behavior you’d expect, but I’m assuming that it wasn’t changed so that it was backward compatible with previous versions (or it might end up breaking existing code). To recover the current selected item you’ll have to use the new SelectedPersistedKey property (which returns a DataKey object associated with the item that has been selected).

And that’s it for now. Keep tuned for more  on ASP.NET.

by luisabreu | with no comments
Filed under:
More Posts Next page »

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover