Tag Archives: C#

Incorrect C++ compiler behavior in Visual Studio

[Note: Special credit for this post goes to my colleague Yuliy Gerchikov, who first discovered this issue]

As most C++ programmers know, an object that has been constructed via the new expression must be destroyed by calling delete. The delete-expression invokes the object’s destructor which in turn is responsible for clean up tasks. For instance, here’s some sample code that shows object creation, and then freeing it up via delete:

	Foo *pF = new Foo();
	// Do some work
	delete pF;

The C++ Specification for delete has this to say:

The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.

delete-expression:
::opt delete cast-expression
::opt delete [ ] cast-expression

The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void. (emphasis mine)

So, given that the delete expression has the return type void, what do you think the C++ compiler should do when it sees the following code:

	Foo *pF = new Foo();
	// Do some work
	delete delete pF;

But delete returns void, so it is reasonable to assume that the C++ compilers would throw a fit on the above code, right? Right? Unfortunately, that’s not always the case.

Let’s look at some C++ code. I have two user defined types Foo and Bar. The difference between the two types is that I declare and define an explicit destructor for Foo.

#include <iostream>
class Foo {
	public: ~Foo() { std::cout<<"In dtor"<<std::endl; }
};

class Bar {};

int main(){
	Foo *pf = new Foo();
    delete delete pf;

    Bar *pb = new Bar();
    delete delete pb;

    return 0;
}
Listing-1

When I compile this using Microsoft’s cl compiler as it ships with Visual Studio 2010 (Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64) here’s what I get:

test.cpp(13) : error C2541: 'delete' : cannot delete
 objects that are not pointers

And here’s the screen shot:

Screen shot-1

What is going on? Why doesn’t the compiler complain at both lines 10 and 13? It turns out, if a user-defined type has an explicit destructor, then the Visual Studio compiler happily compiles the double delete expression. It appears that in such a case the compiler violates the C++ specifications as the “delete ptr-to-type” returns a non-void pointer instead of void.

Suppose I get my code to compile by getting rid of the offending Bar object (code shown below). When I run my program, it is guaranteed to crash as we are calling delete on a ptr to unallocated space!

#include <iostream>
class Foo {
	public: ~Foo() { std::cout<<"In dtor"<<std::endl; }
};

int main(){
	Foo *pf = new Foo();
    delete delete pf;		//Uh Oh!

    std::cout<<"Hello world"<<std::endl;
    return 0;
}
Listing-2

And here’s the screen shot of the crash. Notice that as expected, the “Hello world” line never gets executed.

Screen shot-2

I tried out the same code in gcc (i686-apple-darwin10-gcc-4.2.1), and gcc behaves correctly, i.e. it errors out on both lines 10 and 13 in the listing-1 above.

I am not sure if this behavior of the Visual Studio compiler is intentional. What do you think? Have you encountered any weird C++ compiler behaviors? Please share your thoughts in the comments below.

1 Comment

Filed under Programming, Tools

Code Snippets in Visual Studio 2010

Visual Studio allows developers to save snippets of code which can be inserted at a later time. This saves on retyping blocks of code that are used often. I also find it very useful when I have to show code during presentations. Instead of typing everything live, I find it far easier to simply add the code block by block using code snippets.

VS 2010 improves the snippet functionality, and makes it easier to create code snippets. There’s two types of snippets:

- Expansion snippets are inserted at the cursor
- SurroundsWith snippets wraps around selected code

 

Creating a Custom Snippet:
Let’s go ahead and create a try-catch-finally Expansion snippet:

- Insert a new XML file to the project and call it TryCatchFinally.snippet. Make sure the file name ends with .snippet

- Right-click on the editor window and select Insert Snippet->Snippet. This creates a basic XML snippet template as shown below:

<CodeSnippet Format="1.0.0" 
             xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>title</Title>
    <Author>author</Author>
    <Shortcut>shortcut</Shortcut>
    <Description>description</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>name</ID>
        <Default>value</Default>
      </Literal>
    </Declarations>
    <Code Language="XML">
      <![CDATA[<test>
      <name>$name$</name>
      $selected$ $end$</test>]]>
    </Code>
  </Snippet>
</CodeSnippet>

- As you can see, by default the template contains both snippet types. Since I am creating an Expansion snippet, let's go ahead and get rid of the <SnippetType>SurroundsWith</SnippetType> tag.

- Update the Title to "Try Catch Finally", Shortcut to "trycf" and Description to "Adds a try-catch-finally block".

- Literal tag enables us to define editable values that are inserted into the snippet. In the try-catch-finally snippet, we want to allow the user to change the type of the Exception being caught. The ID tag is the name of the editable value so change it to "ExceptionName". The Default tag specifies the default value for our editable field. I want to catch all exceptions, so change the Default tag's value to "Exception".

- Finally, the code section contains what will be added when the snippet is inserted. Change the language to "CSharp", and the body to the following:

    <Code Language="CSharp">
      <![CDATA[
try
{

}
catch($ExceptionName$)
{

}
finally
{

}
      ]]>
    </Code>

- The final version of the TryCatchFinally.snippet file is shown below. For more details about the XML schema, take a look at the MSDN code snippets Schema Reference

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" 
             xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Try Catch Finally</Title>
    <Author>umair</Author>
    <Shortcut>trycf</Shortcut>
    <Description>Adds a try-catch-finally block</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>ExceptionName</ID>
        <Default>Exception</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[
try
{

}
catch($ExceptionName$)
{

}
finally
{

}
      ]]>
    </Code>
  </Snippet>
</CodeSnippet>

Loading the Snippet into Visual Studio:

There are two ways to insert the above snippet into Visual Studio.

The most straightforward way is to put the .snippet files in VS 2010's code snippets directory. The default location for it is C:\Users\<UserName>\Documents\Visual Studio 2010\Code Snippets\. This folder contains sub-directories based on the language of the snippet. For my example, the snippet goes under Visual C#. Once put here, VS 2010 automatically picks up the snippets without the need to restart.

 

The second option is to import the .snippet file into Visual Studio.

- Inside Visual studio, go to Tools->Code Snippets Manager (Ctrl+K,Ctrl+B). This brings up the Snippets Manager.

- Press Import button, and navigate to the location where the snippet was saved. Select the .snippet file.

- Press OK.

 

Using the Code Snippet:

Type the name of the snippet (the shortcut), and pressing tab expands it.

Intellisense after typing snippet name

You can also press Ctrl+K and Ctrl+X which brings up the "Insert Snippet" menu as shown below:

We can navigate to My Code Snippets, and select the TryCatchFinally that we've just added:

7 Comments

Filed under Visual Studio

XAML Resources

Every element in Silverlight contains a Resource property that maintains a dictionary of resources. This collection can hold any type, and a key is used to refer to each individual resource. Each element has access to its own resources as well as the resources in all its parents. For this reason, a common way to define resources is at the page level so that all elements within that page can re-use that resource. If a given resource will be used across the entire application (i.e. multiple pages), then it is put in the <Application.Resources> section of the App.xaml file.

To find a resource, Silverlight recursively searches up the element tree terminating at the <Application.Resources> section in App.xaml file.

As an example, suppose I re-use a custom brush on multiple elements on my page. I put it in the <UserControl.Resources> section where it can be accessed by all elements on my page. It is defined as:

    <UserControl.Resources>
        <LinearGradientBrush x:Key="CustomBrush">
            <GradientStop Offset="0.00" Color="Yellow" />
            <GradientStop Offset="1.00" Color="Orange" />
        </LinearGradientBrush>
    </UserControl.Resources>

Using a Resource in XAML:

Now that my CustomBrush has been defined, it can be re-used in XAML. A given element needs a way to refer to this resource in order to reuse it. This is accomplished by using a markup extension. Markup extensions are a specialized syntax to set a property in a non-standard way, and are recognized by curly braces. For example, let's say the Grid element needs to use the CustomBrush defined above:

	<Grid x:Name="outerGrid" Background="{StaticResource BackgroundBrush}"

In this example, we use a markup extension named StaticResource. Here's (MSDN) some more information about static and dynamic resources

Using a Resource in Code:

In order to use CustomBrush in my code (e.g. C#), I can access the Resources property as a dictionary by using the key to index and retrieve the specific resource.

            Grid outerGrid = new Grid();
            LinearGradientBrush customBrush = 
                (LinearGradientBrush) this.Resources["CustomBrush"];
            outerGrid.Background = customBrush;

I can even update my resource in code. If I wanted to change the color gradient of my CustomBrush, I would do so as follows:

            LinearGradientBrush customBrush = 
                (LinearGradientBrush) this.Resources["CustomBrush"];
            customBrush.GradientStops[0].Color = Colors.Brown;
            customBrush.GradientStops[1].Color = Colors.Red;

The really nifty bit is that every element that uses this customBrush will automatically update to use the new colors.

Silverlight does not support dynamic resources (but WPF does), and as a result it is not possible to update the resource reference with a new object. For example, the following code is not allowed in Silverlight:

            this.Resources["CustomBrush"] = new LinearGradientBrush();

Leave a comment

Filed under .NET, Programming

Custom Attached Properties in Silverlight

An attached property is a type of global property that is settable on any nested object. In Silverlight (and WPF), attached properties are usually defined as a specialized case of Dependency Properties, and like all dependency properties they are managed by the Silverlight property system. Attached properties differ in that they do not have the conventional "property wrapper".

Most commonly, attached properties are used in layout containers. Every control in XAML has its own set of internal properties. However, when this control is placed inside a container, it acquires additional features depending on the type of the container. For example, the Grid.Row property is created as an attached property because any control inside a Grid needs to specify the grid cell where it is positioned. For example:

<Grid x:Name="OuterGrid">
	<TextBox x:Name="innerBox" Grid.Row="1"/>
</Grid>

Since the TextBox is nested inside the Grid, it gains the Row property which "attaches" to the TextBox instance. In essence, attached properties allow different child elements to specify values for a property defined in a parent element. Attached properties always use a two-part name of the form: AttachedPropertyProvider.PropertyName (OR simply DefiningType.PropertyName)

 

Defining a Custom Attached Property:

Creating an attached property is similar to how we create a custom dependency property with a few subtle differences. Since I seem to love widgets so much, I will continue to use a custom WidgetControl as an example. In one of my previous posts we saw how to create a custom dependency property for WidgetControl. In this post, we will see how to create the WidgetStateProperty as an attached property.

1. The first step is to define a static readonly DependencyProperty object that represents the property, and register this attached property with Silverlight. This is done via the Dependency.RegisterAttached() method.

        public static readonly DependencyProperty WidgetStateProperty =
            DependencyProperty.RegisterAttached(
                "WidgetState",
                typeof(Boolean),
                typeof(WidgetControl),
                new PropertyMetadata(false));

Notice that when we were creating custom dependency properties, we used the DependencyProperty.Register() method. The parameters for both these methods are exactly the same: the property name (WidgetState in this example), the data type used by the property (bool), the type that owns this property (WidgetControl), and a PropertyMetadata object that provides additional information, such as default values.

2. Our attached property provider must also provide static GetXXX() and SetXXX() methods, where XXX is the name of our property (WidgetState).

        public static void SetWidgetState(UIElement element, Boolean value)
        {
            element.SetValue(WidgetControl.WidgetStateProperty, value);
        }

        public static Boolean GetWidgetState(UIElement element)
        {
            return (Boolean)element.GetValue(WidgetControl.WidgetStateProperty);
        }

We now have a fully functioning attached property which can be set using the DefiningType.PropertyName syntax. The complete code for this WidgetControl is shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Attached
{
    public partial class WidgetControl : UserControl
    {
        public WidgetControl()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty WidgetStateProperty =
            DependencyProperty.RegisterAttached(
                "WidgetState",
                typeof(Boolean),
                typeof(WidgetControl),
                new PropertyMetadata(false));


        public static void SetWidgetState(UIElement element, Boolean value)
        {
            element.SetValue(WidgetControl.WidgetStateProperty, value);
        }

        public static Boolean GetWidgetState(UIElement element)
        {
            return (Boolean)element.GetValue(WidgetControl.WidgetStateProperty);
        }
    }
}

Here's a very simple example where we use WidgetControl and its WidgetState property. The code is in XAML:

<UserControl x:Class="Attached.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Attached"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <local:WidgetControl>
            <TextBox x:Name="txtBox" local:WidgetControl.WidgetState="true">
            </TextBox>
        </local:WidgetControl>
    </Grid>
</UserControl>

Finally, a couple of good resources that talk more about dependecy and attached properties are here [msdn.microsoft.com] and here [www.silverlightshow.net]

Leave a comment

Filed under .NET, Programming

Resolution of Dependency Properties

As I mentioned in my previous blog post, dependency properties depend on any number of services (called property providers) for their values. The Silverlight runtime needs to follow strict rules of precedence to determine the value of a dependency property. This process is called dynamic value resolution.

Here’s a prioritized list of providers in their order of precedence:

1. Animation: If an animation is running and is changing the property value, Silverlight uses the animated value

2. Local Value: If the property value has been explicitly set through XAML or code (by using SetValue or the property wrapper), Silverlight uses the local value.

3. Templated Properties: Silverlight uses the template properties if the object has been built dynamically from templates (ControlTemplate or DataTemplate).

4. Styles Setters: If the page or the application resource defines a Style that applies to the given element, with a Setter for its dependency property, then Silverlight assigns the value from the Setter to the dependency property.

5. Default Value: If no other property setter is at work, Silverlight assigns the default value to the dependency property. If a value is passed in through the PropertyMetadata object during dependency property registration, it will be used as the default value. If no value has been passed in, then the default value depends on the type (reference or value) used for storing that dependency property.

1 Comment

Filed under .NET, Programming

Dependency Properties in Silverlight

Very simply, a property of an element that depends on a number of property-providers outside the element is called a "dependency property". Each of these providers has its own level of precedence. These properties can be either set directly by code, or by one of Silverlight’s services (i.e. property providers) such as animation, data binding, styles etc.

Dependency properties were originally introduced in WPF and are a key concept in both Silverlight and WPF. These dependency features are designed to be read and set in code just like normal properties. However, the internal implementation of dependency properties differs from the implementation of ordinary properties.

To better understand dependency properties, let’s consider an example (this example has been taken and modified from this excellent blog post ):

<UserControl x:Class="DependencyProperty.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <ItemsControl Foreground="Red">
            <TextBlock Foreground="Blue">
                1st line of text
            </TextBlock>
            <TextBlock>
                2nd line of text
            </TextBlock>
        </ItemsControl>

    </Grid>
</UserControl>

In this example, we use two TextBlock controls to display two lines of text. The results of running this app are shown below:

Results of running the Silverlight app above

The first TextBlock changes its Foreground property to Blue. Once we run this Silverlight app, we see that the first line of text has blue color, which matches our intuition since we did set the Foreground property to Blue. However, the second line of text is red. This is somewhat surprising (especially for folks who are new to WPF/Silverlight). I never set the Foreground property of the second TextBlock , so why is it red?

This is an example of dependency properties. Foreground of a TextBlock is a dependency property and the Silverlight runtime sets it to red, which is the value of the Foreground property of the encapsulating ItemsControl .

Defining a Dependency Property

The syntax for creating a dependency property is different than creating an ordinary .NET property. Let's look at how to add a dependency property to a custom WidgetControl.

1. The first step is to define the object that represents the property. This is an instance of DependencyProperty class. This object must be defined as static readonly field. By convention, this field has the name of the ordinary property plus the post-fix Property. For example, if my new property is called WidgetState, the DependencyProperty object will be called WidgetStateProperty.

         public static readonly DependencyProperty WidgetStateProperty;

2. The second step is to register the dependency property with Silverlight. This step needs to be completed before any code uses the property, so it must be performed in a static constructor.

        static WidgetControl()
        {
            WidgetStateProperty = DependencyProperty.Register(
                "WidgetState", 
                typeof(Boolean), 
                typeof(WidgetControl),
                new PropertyMetadata(false));
        }

The arguments to DependencyProperty.Register() method are: the property name (WidgetState in this example), the data type used by the property (Boolean), the type that owns this property (WidgetControl), and a PropertyMetadata object that provides additional information. In this example, I am simply passing a default value of "false" to the PropertyMetadata constructor

3. Define a CLR wrapper property whose names matches the name of the dependency property.

        public Boolean WidgetState
        {
            get
            {
                return (Boolean)GetValue(WidgetStateProperty);
            }
            set
            {
                SetValue(WidgetStateProperty, value);
            }
        }

We now have a fully functioning dependency property which can be set just like any other .NET property using the property wrapper

	widgetCtrl.WidgetState = True;

OR, using XAML:

        <cnmspc:WidgetControl x:Name="widgetCtrl" WidgetState="True">
        </cnmspc:WidgetControl>

The complete code for this WidgetControl is shown below:

    public partial class WidgetControl : UserControl
    {
        public WidgetControl()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty WidgetStateProperty;

        static WidgetControl()
        {
            WidgetStateProperty = DependencyProperty.Register(
                "WidgetState", 
                typeof(Boolean), 
                typeof(WidgetControl),
                new PropertyMetadata(false));
        }

        public Boolean WidgetState
        {
            get
            {
                return (Boolean)GetValue(WidgetStateProperty);
            }
            set
            {
                SetValue(WidgetStateProperty, value);
            }
        }
    }

5 Comments

Filed under .NET, Programming

Creating a Custom XAML TypeConverter

TypeConverters provide a means of converting a String to the appropriate .NET type or a new instance when XAML is processed. I’ve already looked at how the XAML parser searches for TypeConverters (XAML and TypeConverters ) Now let’s take a look at how to create our custom TypeConverter.

At a minimum, for a class to conform to the Silverlight implementation of TypeConverters it must be a subclass of the TypeConverter class and must contain the following two members for converting from strings for XAML processing:

1. The class must override the CanConvertFrom(…) method:

public virtual bool CanConvertFrom(
    ITypeDescriptorContext context,
    Type sourceType
)

It must return true when the sourceType parameter is String, and otherwise defer to the base implementation.

2. The class must provide an implementation of ConvertFrom(...) method:

public virtual Object ConvertFrom(
    ITypeDescriptorContext context,
    CultureInfo culture,
    Object value
)

To be usable as a TypeConverter implementation that supports XAML, this method must accept a string as the value parameter. If the string is valid, the returned object must support a cast to the type expected by the property. Otherwise it must return null.

The .NET specification for TypeConverters also contains two more key methods, which are ConvertTo and CanConvertTo. However, Silverlight 3 (as well as Silverlight 4 Beta) does not use ConvertTo and CanConvertTo, so you can skip these if your TypeConverter is for Silverlight's XAML processing. It's still a good idea to implement these two as a best practice for completing the wider interoperation functionality of the converter class.

 

Putting it all together: An Example:

Suppose I have a custom Silverlight control called WidgetControl, that has a property called WidgetHeight. If you need to see how to add custom controls to your project, please check out my post "Adding a Custom Silverlight Control". I use this control in my XAML file as follows:

<Custom:WidgetControl x:Name="widget" WidgetHeight="2 inches"/>

Somehow I need to handle the case where the unit of length is specified for the value of WidgetHeight property. This is done via a custom XAML TypeConverter called CustomLengthConverter, which is shown below:

    public class CustomLengthConverter : TypeConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }


        public override object ConvertFrom(ITypeDescriptorContext
                context, CultureInfo culture, object value)
        {

            if (value == null)
            {
                return new Double();
            }
            if (value is string)
            {
                string s = (string)value;
                if (s.Length == 0)
                {
                    return new Double();
                }

                string[] arguments = s.Split(' ');
                if (arguments.Length != 2)
                {
                    throw new ArgumentException("Value must have the format <number length_unit>");
                }
                else
                {
                    return InternalParseInput(arguments[0]);
                }
            }

            return base.ConvertFrom(context, culture, value);
        }


        public Double InternalParseInput(String inputString)
        {
            Double doubleValue;

            try
            {
                doubleValue = Double.Parse(inputString);
            }
            catch(Exception){
                doubleValue = new Double();
            }

            return doubleValue;
        }
    }

Finally, in my WidgetControl class, I explicitly specify that the WidgetHeight property should use the CustomLengthConverter defined above:

    public partial class WidgetControl : UserControl
    {
	...

        [TypeConverter(typeof(CustomLengthConverter))]
        public Double WidgetHeight
        {
	   ...
        }
    }

So every time my XAML for WidgetControl's WidgetHeight property is parsed, the parser uses the CustomLengthConverter to convert the property value from String to the appropriate .NET type (Double)

5 Comments

Filed under Programming

Adding a Custom Silverlight Control

Silverlight has a ton of controls that we can use in our Silverlight apps. Most of the times, this collection of controls is sufficient, but every once in a while, we need to create a custom control. Adding a new custom control for Silverlight is fairly straightforward, and in this blog post I am going to take a look at the steps involved in adding a new control to our Visual Studio project.

(Note: My aim is to show the steps for adding a new control, so I will not go into the specifics of the control itself)

I am going to start by creating a new project (type: Silverlight Application) in Visual Studio. Let’s call it Widget. To add a new Custom control, right click on the project in Solution Explorer, and go to Add->New Item, as shown in the figure below:

Add New Item

We get to a selection dialog which lists the various items that can be added. Let’s select “Silverlight User Control”, and change the name of the XAML file to WidgetControl.xaml

Add New Item - Selection

For this example, my new control is a pretty basic control as it simply contains a TextBox. Open the WidgetControl.xaml file, and add the TextBox element. Once done, the WidgetControl.xaml.cs file looks like:

<UserControl x:Class="Widget.WidgetControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBox x:Name="txtBox" Text="Widget Box"></TextBox>
    </Grid>
</UserControl>

We can add new properties to our WidgetControl, and to illustrate this let’s add a new property called InternalText that is used to manipulate the text for the txtBox. Right click on the WidgetControl.xaml.cs file, and click on “View class Designer”.

View Class Diagram

When the class designer opens up right click on the WidgetControl class, click Add->Property.

Add Property

Add the new String property called InternalText. Once the property has been added, the WidgetControl.xaml.cs file will be updated automatically to include the new property. The file looks as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Widget
{
    public partial class WidgetControl : UserControl
    {
        public WidgetControl()
        {
            InitializeComponent();
        }

        public String InternalText
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }
    }
}

Since our new property simply wraps around the Text property of the TextBox, so let’s go ahead and implement our InternalText property:

        public String InternalText
        {
            get
            {
                return txtBox.Text;
            }
            set
            {
                txtBox.Text = value;
            }
        }

Using a Custom Control:

Once we’ve created a custom control, using it is pretty straightforward. All we need is to declare our xml namespace, and start using the control. Continuing my example, I’ve added my custom WidgetControl to MainPage.xaml file. The code to make this happen is on lines 6 & 11 below:

<UserControl x:Class="Widget.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:wts="clr-namespace:Widget"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <wts:WidgetControl x:Name="widgetCtrl" InternalText="Let's Text"/>
    </Grid>
</UserControl>

5 Comments

Filed under .NET, Programming

XAML and TypeConverters

In a XAML document, every element maps to an instance of a Silverlight (.NET) class. The properties of this instance can be set through attributes in the XAML file. There is a bit of a catch though. These attribute values (in the XAML file) are in text form, whereas the corresponding Silverlight property is a .NET type. There needs to be a way to convert these String attribute values into corresponding .NET types. This is where TypeConverters come in.

In the context of Silverlight, a TypeConverter is a class which knows how to convert between a String and a .NET type. For each attribute in XAML, the parser follows a two-step process to find the appropriate type converter:

1. The XAML parser checks the declaration of the property that corresponds to the XML attribute, and tries to see if the property contains a TypeConverter attribute. The TypeConverter attribute specifies the class that can perform the type conversion from String to the .NET type of the property. The parser then uses the TypeConverter class to convert the XML attribute into a .NET type.

2. If the property declaration does not contain a TypeConverter attribute, the XAML parser looks at the property’s Type, to see if it containts TypeConverter attribute declaration.

3. If neither the property declaration or type (class) declaration have an associated TypeConverter attribute, the XAML parser returns an error.

Let’s consider a couple of examples to better illustrate this. Suppose we have two .NET Types called a Widget and WidgetBox, which are defined as follows:

 
    public class Widget{
        public Brush Foreground
        {
        }
    }


    public class WidgetBox
    {
        [System.ComponentModel.TypeConverter(typeof(CustomLengthConverter)]
        public Double Height
        {
        }
    }

    public class CustomLengthConverter : System.ComponentModel.TypeConverter
    {
        ...
    }

Example-1:

Consider the following XML element in the XAML file.

	<WidgetBox Height="1in" />

1. When the XAML parser encounters this code, it checks the property declaration for Height. In this case, it finds a TypeConverter attribute for the Height property, which tells the parser to use the CustomLengthConverter class to convert the string "1in" to Double. So, this snippet of XAML code is equivalent to:

 
	WidgetBox wb = new WidgetBox();
	wb.Height = new CustomLengthConverter().ConvertFrom("1in");

Example-2:

Here's another snippet of XAML code:

	<Widget Foreground="Blue" />

1. When XAML parser encounters this code, it first checks the property declaration for Foreground. There's no TypeConverter associated with the Foreground property, so the parser moves to step-2.

2. Now the XAML parser checks the class declaration of the Foreground's Type. In our example, the type of Foreground is Brush, and it turns out that the Brush class is decorated with the [TypeConverter(typeof(BrushConverter))] attribute declaration:

 
	[TypeConverter(typeof(BrushConverter))]
	public class Brush
	{
	...
	}

In this case, the parser uses the BrushConverter class to convert the string "Blue" into a Brush .NET type. So this snippet of XAML is equivalent to:

  
	Widget w = new Widget();
	w.Foreground = new BrushConverter().ConvertFrom(&quot;Blue&quot;);

For more information about TypeConverters, check out MSDN. There's also a lot of great information at Rob Relyea's blog post about TypeConverters

3 Comments

Filed under .NET, Programming

Silverlight – Getting started with XAML

XAML stands for eXtensible Application Markup Language (pronounced zamm-uhl). It is an XML based markup language used to instantiate .NET objects. XAML was initially designed as part of Windows Presentation Foundation (WPF), and allows developers to define rich user interfaces. A XAML file defines the elements that make up a content region. This enables a clean separation between UI and the business logic code. One big advantage of this separation is that the UI designers can focus on creating the user-interface in XAML (using tools such as Microsoft’s Expression), and the developers can then create the business objects corresponding to the UI.

XAML document has the following properties:

- Every element in a XAML documents maps to an instance of a Silverlight (.NET) class, and its name exactly matches that of the class.
- The properties of each class can be set through attributes in the XAML file.
- Similar to any XML document, a XAML element can contain nested elements.

For example, when we create a new Silverlight application (called SampleApplication) in Visual Studio 2010 (beta), we get the following skeleton XAML document:

<UserControl x:Class="SampleApplication.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">

    </Grid>
</UserControl>

As I’ve mentioned before, XAML allows us to create user-interfaces. However, for the interface to be useful, it needs to connect to code (typically written in C#). To accomplish this, we need a way to connect the event handlers with the UI. Usually, every XAML file has a corresponding class with client-side C# code. This class is generated by the Class attribute in the XAML namespace. This attribute tells the Silverlight parser to create a new class with the specified name that derives from the class represented by the XML element. When the XAML code above is parsed, the parser creates a new class named SampleApplication.MainPage, which derives from the UserControl class. This class is in the file called MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SampleApplication
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

    }
}

The class is partial , as it is split across two files. The code that we write goes into MainPage.xaml.cs. The rest of the class definition contains auto-generated code and goes into a file called MainPage.g.cs. In the solution, this file is located in obj\Debug folder. For the above XAML code, the contents of this auto-generated file are as follows:

using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace SampleApplication {

    public partial class MainPage : System.Windows.Controls.UserControl {

        internal System.Windows.Controls.Grid LayoutRoot;

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri("/SampleApplication;component/MainPage.xaml", System.UriKind.Relative));
            this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
        }
    }
}

Finally, a quick note about the Name attribute. If we want to access and manipulate Silverlight elements programmatically, XAML must include the Name attribute. This is useful if we want to change properties or attach and detach event handlers on the fly. In the above example, line-9 of the XAML file tells the XAML parser to add the following field to the autogenerated portion of the MainPage class

private System.Windows.Controls.Grid LayoutRoot;

4 Comments

Filed under .NET, Programming