Archive for the ‘WPF’ Category

Dependency Properties - Value Precendence

Thursday, March 13th, 2008

The value of a Dependency Properties in WPF can be set from many sources: Templates, Styles, Data Binding, Animation, Local, Inherited from Element Tree,… That’s the reason why they are called "Dependency" Properties. Their values depend on many sources.

To get not a total chaos, there’s a precedence list in WPF that rules which value finally will be set. Here’s the list beginning with the source with lowest precedence (1.) up to the Source with highest precedence (10.):

  1. default-value
  2. Inherited Value
  3. Theme Style Setter
  4. Theme Style Trigger
  5. Style Setter
  6. Template Trigger
  7. Style Trigger
  8. Local Value
  9. Animated Value
  10. Coerced Value

WPF or better say its Property Engine calculates the value of a Dependency Property out of these sources. Finally the ValidateValueCallback checks if the value is valid (If a ValidateValueCallback was registered with the Dependency Property). If the value is not valid, the calculated-value wouldn’t be used (of course).

You have always to be aware of this precedence list, even in simple scenarios. Let’s take a short example. The Attached Property TextElement.Foreground has the Inherits-Flag set to true, so the value of this property is inherited through the element tree and you can set it on any element by using the attached property syntax, e.g. on a StackPanel like below:

<StackPanel TextElement.Foreground="Green">
    <TextBox>Should be green</TextBox>
    <TextBlock>Should also be green</TextBlock>
</StackPanel>

What do you think is the result of the codesnippet above? Do both, TextBox and TextBlock, display green text? I wouldn’t ask if they would do so. :-)

No, not both Elements display green text. The text inside the TextBox is still in the standard black or darkGray. The TextBlock displays its text in green.

Mhm… why doesn’t the TextBox inherit the Foreground-Value from the StackPanel? If you set the TextElement.Foreground-Property locally, it works, and the text inside the TextBox gets green:

<TextBox TextElement.Foreground="Green">
  Should be green
</TextBox>

So lets find out why the TextBox doesn’t get the inherited Value and displays its text still in standard color. Let’s take a look at the TextBox’s ControlTemplate defined in the Theme-Style for Vista’s Aero-Theme (the theme my PC is running on). In the Triggers-Section of the ControlTemplate a Trigger is defined that is actived when the IsEnabled-Property of the TextBox is true. You can see the Templates Trigger-Section below. And as you can see there, the Trigger sets the TextElement.Foreground-Property to the Brush stored in the Field SystemColors.GrayTextBrush (by using the GrayTextBrushKey-ResourceKey).

<ControlTemplate.Triggers>
  <Trigger Property="UIElement.IsEnabled">
    <Setter Property="Panel.Background" TargetName="Bd">
      <Setter.Value>
        <DynamicResource
     ResourceKey="{x:Static SystemColors.ControlBrushKey}"/>
      </Setter.Value>
    </Setter>
    <Setter Property="TextElement.Foreground">
      <Setter.Value>
        <DynamicResource
    ResourceKey="{x:Static SystemColors.GrayTextBrushKey}"/>
      </Setter.Value>
    </Setter>
    <Trigger.Value>
      <s:Boolean>False</s:Boolean>
    </Trigger.Value>
  </Trigger>
</ControlTemplate.Triggers>

If you look to the precedence-list at the beginning of this post, you see that the Inherited Value is on position 2., and the Template Trigger is on Position 6. So the Template Trigger has higher precedence. In the StackPanel with a TextBox and a TextBlock, the Template Trigger of the TextBox will set the foreground, and not the inherited value. When we set the local value, this local value is used, cause local value is on a higher position than the Template Trigger in the precedence list.

To go one step further, let’s override the Template of the TextBox and don’t set the TextElement.Foreground-Property in the Trigger-Section. As a result of the following code with the new TextBox-Template you’ll see that both, TextBox and TextBlock will display green text. :-)

<Window.Resources>
  <Style TargetType="TextBox">
  <Setter Property="Template">
   <Setter.Value>
    <ControlTemplate TargetType="TextBoxBase" …>
     <ScrollViewer Name="PART_ContentHost" …/>
    <ControlTemplate.Triggers>
     <Trigger Property="UIElement.IsEnabled">
      <Setter Property="TextElement.Foreground">
       <Setter.Value>
        <DynamicResource
  ResourceKey="{x:Static SystemColors.GrayTextBrushKey}" />
       </Setter.Value>
      </Setter>
      <Trigger.Value>
       <s:Boolean>False</s:Boolean>
      </Trigger.Value>
     </Trigger>
    </ControlTemplate.Triggers>
   </ControlTemplate>
   </Setter.Value>
  </Setter>
 </Style>
</Window.Resources>
<StackPanel TextElement.Foreground="Green">
 <TextBox>Should be green</TextBox>
 <TextBlock>Should also be green</TextBlock>
</StackPanel>

Built-in DataGrid for WPF is planned

Saturday, February 23rd, 2008

Yes, they are planning to release it. Really great news. Today there’s no DataGrid for WPF-applications as part of .NET Framework 3.5. There are only third-party controls like the Grid from Xceed or Infragistics.

Have you ever built a business application without a DataGrid? I haven’t. I’m really happy to hear that microsoft will release a DataGrid for WPF as part of .NET. That wouldn’t make thirdparty-components necessary (If you don’t need all functionality e.g. Infragistics provides). I hope the DataGrid for WPF will be more like the DataGridView of WinForms in NET 2.0, and not like DataGrid in .NET < 2.0. :-)

Take a look at the .NET 3.5 roadmap on Scott Guthries blogpost. There’s a little line containing this information about a planned built-in DataGrid by end 2008. Also some other missing controls are planned, like Calendar/DatePicker.

Kick it like Beckham with WPF Animations

Thursday, February 21st, 2008

I’m just finishing the Animation-Chapter of my German-speaking WPF book (WPF-Buch erscheint im Juni 2008). I had a hard time to find a good idea how to show the reader animations in a really "non-boring", but easy way. And I think I’ve found one.

Animations in WPF are really powerful. You can create them completely in XAML. Even if the example of this post doesn’t make sense for a business application, think of the things you can do with animations:

  • Create buttons with professional hover-effekts
  • Improve the user-interface with some nice effects
  • Ease navigation for the user by animating something he should do now

Of course, Animations in business applications must be placed in the right way. It’s not recommended to animate everything you can. If you do so, your application won’t be serious anymore.

The application we are looking at here isn’t a business application. It’s just a small Loose XAML-File that allows you to become a soccer profi. :-) It show’s how animations are completely created in XAML and how they can be controlled.

Animations in XAML are placed inside Triggers. Either in an EventTriggers Action-Property or in another Triggers EnterAction or ExitAction-Property. These Properties are all of type TriggerAction. The BeginStoryboard-class and some other classes derive from TriggerAction. BeginStoryboard contains a Storyboard. The Storyboard itself contains the Animations.

Below a loose XAML. The Animation (bold) changes the Canvas.Top-Property of an image that contains a ball (the teamgeist-ball of worldcup 2006 Germany). The Animation starts, when a button with the Name btnStart is clicked. Between the ball-image the Canvas contains an image of me. And the clou is, it looks like I kick the ball for thousand times like a real profi.

<Grid Height="260" Width="300">
 <Grid.RowDefinitions>
  <RowDefinition/>
  <RowDefinition Height="Auto"/>
 </Grid.RowDefinitions>
 <Grid.Triggers>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnStart">
   <BeginStoryboard Name="beginStoryboard">
    <Storyboard TargetProperty="(Canvas.Top)"
      TargetName="imgBall">
     <DoubleAnimation AutoReverse="True" To="110"
     RepeatBehavior="Forever" Duration="0:0:0.25"
     AccelerationRatio="1"/>
    </Storyboard>
   </BeginStoryboard>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnStop">
   <StopStoryboard BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnPause">
   <PauseStoryboard BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnResume">
   <ResumeStoryboard BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnSpeed2x">
   <SetStoryboardSpeedRatio SpeedRatio="2"
     BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
  <EventTrigger RoutedEvent="Button.Click"
    SourceName="btnSpeed1x">
   <SetStoryboardSpeedRatio SpeedRatio="1"
     BeginStoryboardName="beginStoryboard"/>
  </EventTrigger>
 </Grid.Triggers>
 <Canvas Width="250" Height="185">
  <Image Height="185" Source="fussballthomi.png"
    Canvas.Left="40"/>
  <Image x:Name="imgBall" Width="25" Canvas.Top="10"
    Canvas.Left="140" Source="teamgeist.png"/>
 </Canvas>
 <DockPanel Grid.Row="1" LastChildFill="False">
  <Button Margin="5" x:Name="btnStart" Content="Start"/>
  <Button Margin="5" x:Name="btnStop" Content="Stop"/>
  <Button Margin="5" x:Name="btnPause" Content="Pause"/>
  <Button Margin="5" x:Name="btnResume" Content="Weiter"/>
  <Button Margin="5" x:Name="btnSpeed1x" Content="1x"/>
  <Button Margin="5" x:Name="btnSpeed2x" Content="2x"/>
 </DockPanel>
</Grid>

Thomas kicks it like beckham. :-)

kickItXAML

More informations about my book, that contains the sample above and hundreds more (also more real world applications), you’ll find by march on www.thomasclaudiushuber.com

Bind to methods with ObjectDataProvider

Thursday, January 10th, 2008

Two classes inherit from DataSourceProvider. XmlDataProvider and ObjectDataProvider. ObjectDataProvider wraps an object and allows you to bind to the wrapped object in XAML. The ObjectDataProvider has a ConstructorParameters-Property for creating an object by using a constructor with parameters.

The cool thing is that a Data Binding to the wrapped object of the ObjectDataProvider is not all. With ObjectDataProvider you can even bind to a static method or to an instance method of the wrapped object. I’ll show you an example.

Just think about a really simple ComboBox that allows the user to chose some colors. Between the name of the color a rectangle filled with the color should be displayed (In WPF this is quite easy. You haven’t to create eventhandlers like you would do in Windows Forms. There you consumed the DrawItem-event of the ComboBox and used the Graphics-object to do a little bit of GDI+. In WPF GDI+ is gone). WPF’s Color class doesn’t have a name property. So just create a static class ColorHelper with one static method GetColorNames that returns an IEnumerable<string> and uses reflection to iterate over all public static properties of the Colors class that all contain Color-objects.

public static class ColorHelper
{
  public static IEnumerable<string> GetColorNames()
  {
    foreach (PropertyInfo p
      in typeof(Colors).GetProperties(
      BindingFlags.Public | BindingFlags.Static))
    {
      yield return p.Name;
    }
  }
}

The Window in the following XAML contains an ObjectDataProvider that uses the Static GetColorNames-Method of the ColorHelper class. The ItemsSource-Property (Typ: IEnumerable) of the ComboBox is bound to the ObjectDataProvider. The ItemTemplate-Property contains a DataTemplate that specifies the Visual Tree (the "look") of an item. Thanks to TypeConverters, a SolidColorBrush-Object is created for the Fill-Property of each Rectangle specified in the DataTemplate.

<Window    xmlns:local="clr-namespace:SimpleObjectDataProvider">
 <Window.Resources>
  <ObjectDataProvider x:Key="colors"
   ObjectType="{x:Type local:ColorHelper}"
   MethodName="GetColorNames"/>
 </Window.Resources>
 <StackPanel>
  <ComboBox
   ItemsSource="{Binding Source={StaticResource colors}}">
   <ComboBox.ItemTemplate>
    <DataTemplate>
     <StackPanel Margin="1" Orientation="Horizontal">
      <Rectangle Fill="{Binding}" Height="10" Width="10"
        Margin="2"/>
      <TextBlock Text="{Binding}" Margin="2 0 0 0"/>
     </StackPanel>
    </DataTemplate>
   </ComboBox.ItemTemplate>
  </ComboBox>
 </StackPanel>
</Window>

The displayed, open ComboBox looks like this:

comboBoxObjectDataProvider

Working with the XmlDataProvider

Monday, January 7th, 2008

The XmlDataProvider class enables Binding to XML inside XAML. This will allow you to bind e.g. to the rss feed of a blog like http://www.thomasclaudiushuber.com/blog/feed/, cause rss is simple XML.

A XmlDataProvider-Element is declared as a logic resource. You simply set the Source-Property to a XML-Document and optionally set the XPath-Property. The default value of the IsAsynchronous-Property of the XmlDataProvider is true, so your client won’t freeze if you specify a url as the source.

The following XAML creates a simple rss-reader. The root is a Window object that contains a XmlDataProvider inside its Resources-Property. The XmlDataProvider loads the feed of this blog and its XPath-Property points to the blogs items. The elements inside the Window are indirectly bound to the XmlDataProvider. They use the DataContext specified on the DockPanel. The special thing of the Bindings on this elements is that they do not directly point to the XmlDataProvider. Instead the Bindings start at the /rss/channel/item like specified in the XPath-Property of the XmlDataProvider. If you want to point directly to the XmlDataProvider-object, you’ve to set the BindsDirectlyToSource-Property of the Binding to true. This is used by the first TextBox. It allows the user to change the Source-Property of the XmlDataProvider to navigate to another feed like http://blog.trivadis.com/blogs/MainFeed.aspx. The Binding for this TextBox also specifies that the UpdateSourceTrigger is PropertyChanged. Without this, the Source would be updated on LostFocus, cause the TextBox.TextProperty has specified this behaviour in its metadata.

<Window x:Class="SimpleRssReader.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/…"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="RSS Reader" Height="600" Width="800">
 <Window.Resources>
  <XmlDataProvider x:Key="blog"
   Source="http://www.thomasclaudiushuber.com/blog/feed/"
   XPath="/rss/channel/item"/>
 </Window.Resources>
 <DockPanel
   DataContext="{Binding Source={StaticResource blog}}">
  <StackPanel DockPanel.Dock="Top"
    TextElement.FontWeight="Bold" Background="LightGray">
   <TextBlock Text="{Binding XPath=./../title}"
     FontSize="20" Margin="10 10 10 0"/>
    <TextBlock Text="{Binding XPath=./../description}"
      FontSize="10" FontWeight="Normal" Margin="10 0"/>
   <TextBox Margin="5" Text="{Binding
     Source={StaticResource blog},
     BindsDirectlyToSource=True,
     Path=Source,
     UpdateSourceTrigger=PropertyChanged}"/>
 </StackPanel>

  <StatusBar DockPanel.Dock="Bottom">
   <StatusBarItem Content="{Binding XPath=title}"/>
   <Separator/>
   <StatusBarItem Content="{Binding XPath=pubDate}"/>
  </StatusBar>

  <Grid>
   <Grid.ColumnDefinitions>
    <ColumnDefinition Width="308"/>
    <ColumnDefinition Width="Auto"/>
    <ColumnDefinition/>
   </Grid.ColumnDefinitions>

   <GroupBox Header="Blog-Eintr?ge">
    <ListBox IsSynchronizedWithCurrentItem="True"
      ItemsSource="{Binding}" DisplayMemberPath="title"/>
   </GroupBox>

   <GridSplitter Grid.Column="1"
     HorizontalAlignment="Center" Width="10"/>

   <Frame Grid.Column="2" Source="{Binding XPath=link}"/>
  </Grid>

 </DockPanel>
</Window>

To test the rss reader yourself, simply create a new WPF-Application Project and paste the XAML above into the Window1.xaml. You have just to set the value of the x:Class-Attribut on the Window-Element so that it matches your class in the Codebehind-File. The Codebehind-File itself doesn’t need any logic. The reader looks like this:

rssreader_XmlDataSource

C# 3.0 and WPF’s ListView

Wednesday, December 12th, 2007

In many applications you want to fill up a ListView or a GridView with some data. In WPF applications you set the View-Property of the ListView to a GridView to show the data nicely in columns. In most cases you have an entity class (think of it as a "real" entity class or a DataRow as part of a DataTable), and objects of this class should be represented in a row of the GridView. In WPF the DisplayMemberBinding-Property of each GridViewColumn is bound to a property of the entity class, so objects of the entity class can be easily added to the ListView and are displayed correctly in the GridViewColumns. But…

The problem (… the problem is more code as you want to have) begins, when you have no entity class and your data is stored in objects of different classes, maybe only in some variables, and you just want to display the data in one row of the ListView. If your variables have a relation to each other, it’s semantically correct to put them into one row of the ListView, displayed in different GridViewColumns. But to display the data in the ListView, you have to create a dummy entity class that contains your data. There’s no other way!

… no other way with C# 2.0. But now we have C# 3.0, and things can get much easier, cause the compiler can create nearly everything for you. :-) To show you how some C# 3.0 features can help you for the problem above with the dummy entity class, I have to step some months back in time and pick out a small sample that exactly shows the necessity of creating a dummy entity class.

Some months ago I created a small WPF application (.NET 3.0 and C# 2.0) to show developers how Routed Events are routed through the Element Tree. The application contains a Button and a ListView. The Button contains a StackPanel and inside this StackPanel is a Rectangle. Below the Window1.xaml:

<Window x:Class="RoutedEventsBeispiel.Window1"
xmlns=="http://schemas.microsoft.com/winfx/2006/xaml/.."
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="RoutedEventsBeispiel" Height="450" Width="500">
 <Grid>
  <Grid.RowDefinitions>
   <RowDefinition Height="Auto"/>
   <RowDefinition/>
  </Grid.RowDefinitions>
  <Button x:Name="button1" Width="100"
          Height="100" Margin="5">
   <StackPanel x:Name="stackPanel1" Background="Black">
    <Rectangle x:Name="rectangle1" Margin="10"
                 Fill="Red" Width="50" Height="50"/>
   </StackPanel>
  </Button>
  <ListView x:Name="listView" Grid.Row="1">
   <ListView.View>
    <GridView>
     <GridViewColumn Header="RoutedEvent"
       DisplayMemberBinding="{Binding RoutedEventName}"/>
     <GridViewColumn Header="Sender"
       DisplayMemberBinding="{Binding Sender}"/>
    </GridView>
   </ListView.View>
  </ListView>
 </Grid>
</Window>

Especially take a look at the DisplayMemberBinding-Property of the two GridViewColumns in the Window1.xaml above. To represent some data in this ListView, the Data must be represented by an object that has a Property RoutedEventName and a Property Sender. Therefore the Dummy class joins the game. Of course the class could be named in a better way like "RoutedEventInfo", but I decided to name it Dummy, because later with C# 3.0 this class won’t be necessary anymore:

public class Dummy
{
  private string _sender;
  private string _routedEventName;

  public string Sender
  {
    get { return _sender; }
    set { _sender = value; }
  }
  public string RoutedEventName
  {
    get { return _routedEventName; }
    set { _routedEventName = value; }
  }
}

In the constructor of Window1 in the codebehind Window1.xaml.cs a general Eventhandler for the Events UIElement.PreviewMouseLeftButtonDown and UIElement.MouseLeftButtonDown is added to the Window, the Button, the StackPanel and the Rectangle. The third parameter of the AddHandler-Method is always set to true. This true stands for "handledEventsToo", so the GeneralOnMouseDown-Eventhandler is called even if any EventHandler has set the Handled-Property of the RoutedEventArgs to true (That’s exactly what the ButtonBase class does internally with the MouseLeftButtonDown-Event, when the ButtonBase class raises its own Click-Event. So the third parameter is necessary here to get the application show the tunneling and bubbling of the events like expected)

public partial class Window1 : System.Windows.Window
{
  public Window1()
  {
   InitializeComponent();

   this.AddHandler(UIElement.PreviewMouseLeftButtonDown…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   this.AddHandler(UIElement.MouseLeftButtonDownEvent,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   button1.AddHandler(UIElement.PreviewMouseLeftButtonDown…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   button1.AddHandler(UIElement.MouseLeftButtonDown…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   stackPanel1.AddHandler(UIElement.PreviewMouseLe…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   stackPanel1.AddHandler(UIElement.MouseLeftButton…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   rectangle1.AddHandler(UIElement.PreviewMouseLeft…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
   rectangle1.AddHandler(UIElement.MouseLeftButton…,
    new RoutedEventHandler(GeneralOnMouseDown), true);
  }
void GeneralOnMouseDown(object sender,RoutedEventArgs e)
  {
   if (sender is Window1 
    && e.RoutedEvent==UIElement.PreviewMouseLeftButton…)
   {
     listView.Items.Clear();
   }
   Dummy d = new Dummy();
   d.Sender = sender.GetType().Name;
   d.RoutedEventName = e.RoutedEvent.Name;
   listView.Items.Add(d);
  }
}

The general Eventhandler GeneralOnMouseDown clears the Items of the ListView if the sender is a Window1 instance and the routed event is the tunneling event PreviewMouseLeftButtonDown. After that, it creates an instance of type Dummy, sets its Sender- and RoutedEventName-Property, and adds the Dummy instance to the ListView.

When you click on the red Rectangle located inside of the black StackPanel that is located inside of the Button, the ListView is filled up with Dummy objects, and it shows us, in which order the routed events are raised. The PreviewMouseLeftButtonDown-Events tunnels down from the Window1 to the Rectangle, then the MouseLeftButtonDown-Event bubbles up to the Window1.

20071118_RoutedEvents

That’s the application like I developed it with C# 2.0 and .NET 3.0. The need of the Dummy class is only necessary, because I got two string variables (the name of the routed event and the type name of the sender) that I have to put into one object, and this one object is put into the ListView. The GridViewColumns are bound to the Properties Sender and RoutedEventName of the object inside the ListView, so the Dummy objects are displayed like expected in the correct GridViewColumns.

Now how can I shorten my code with C# 3.0? We just focus on the GeneralOnMouseDown-Eventhandler and the Dummy-class. To add a Dummy object to the ListView, you can just use the Object Initializer to get it done in one instead of four statements:

listView.Items.Add(new Dummy() {
    Sender = sender.GetType().Name,
    RoutedEventName = e.RoutedEvent.Name });

Of course you could alternatively add a constructor to the Dummy-class instead of using an object initializer and you would reach a similar effect. But not always you’re the owner of such a Dummy-class and so you won’t be able to add a constructor. Even if you’re the owner of the Dummy-class, I think you like it to write less code (if you’re not paid per lines of code :-) ). With object initializers you won’t have to create many different constructors.

Now take a look at the Dummy class itself. It could be much shorter, if you use the Automation Properties of C# 3.0 (the IL-Code will still look the similar like before). With automation properties, the compiler creates the backing private fields for the specified properties:

public class Dummy
{
  public string Sender { get; set; }
  public string RoutedEventName{get;set;}
}

We can go even further.

If you’ve read the C# 3.0 specification, you’ve also read about Anonymous Types. So let’s go ahead one more step. Anonymous types are not only a feature that is good to use in LINQ-statements. In this small application here we could throw the Dummy class away and instead of Dummy objects we can add anonymous type objects to the ListView. The anonymous type must contain the properties Sender and RoutedEventName. So without the Dummy class you could fill up the ListView in the GeneralOnMouseDown-Eventhandler just with anonymous types like below, and the application still works the same way:

void GeneralOnMouseDown(object sender,RoutedEventArgs e)
{
  if (sender is Window1 && e.RoutedEvent==…)
    listView.Items.Clear();

  listView.Items.Add(new { Sender = sender.GetType().Name,
    RoutedEventName = e.RoutedEvent.Name });
}

In the background, the compiler creates an Anonymous class, that contains two properties Sender and RoutedEventName. So in IL you’ll find a class created from the anonymous type used above. But that’s not your problem, your C# Code itself gets much shorter.

The cool thing about C# 3.0 and Visual Studio 2008 is that you can use these C# 3.0 features to build .NET 2.0 applications (Of course for WPF applications you need at least version 3.0 of .NET). But be careful when using C# 3.0 features for .NET 2.0 apps. E.g. language enhancement features like LINQ are based on Extension Methods located in assemblies introduced with .NET 3.5. :-)

TechEd Developers 2007 in retrospect - Tuesday

Saturday, November 17th, 2007

On the second day at TechEd, the first session I joined had the title "Cool Looking 3D visualizations with Windows Presentation Foundation (WPF)" (Speaker: Dennis Vroegop).

The WPF has a "built-in" 3D-API, and this session showed what you can do with 3D in your business applications. The 3D-API of WPF isn’t adequate for great 3D Games. For Games you should use Managed DirectX that has a much better performance than WPF’s 3D-API (which is build on a "Media Integration Layer" (Milcore) that is built on top of DirectX). WPF’s 3D-API is an easy way to bring some great 3D effects to your business applications. This session showed beside the basics of 3D an example how 3D can be used for a better data representation. The used example showed a 3D map and represented product-data for different locations as 3D-objects.

LINQ to SQL: Accessing Relational Data with Language was the session I joined next, speaker was Luca Bolognese. LINQ to SQL is the easiest way to access a relational database with .NET 3.5. In LINQ to SQL entity classes are mapped directly to tables in the database. For each table a class. To query a database a developer hasn’t to know anything about SQL. The query is defined in C# with the LINQ-Syntax introduced in C# 3.0. The SQL sent to the database is generated automatically. Let’s look at a very simple example to load some data.

To load data with LINQ to SQL, the first thing you have to do is to add a reference to the assembly System.Data.Linq.dll to your project and then create your entity classes. The entity classes are mapped to a table in the database via the attributes Table and Column contained in the namespace System.Data.Linq.Mapping. Of course Visual Studio 2008 contains a designer, that allows you to drag’n'drop tables from the server explorer to the designer surface, and it’ll create the entity classes for you. In this example I’ll just use a manually created class:

[Table(Name="Friends")]
class Friend
{
  [Column(IsPrimaryKey=true)]
  public Guid FriendID;
  [Column]
  public string Name;
  [Column]
  public int Age;
}

As shown above, the Class Friend maps to the table Friends as specified with the TableAttribute. You could also specify the TableAttribute without setting the Name-Property, then your classname must match exactly the table name in the database. The table Friends in the database contains the columns FriendID, Name and Age. You see exactly the same columns in the Friend class. The ColumnAttribute also has a Name-Property that you can use if your .NET field or property doesn’t match the columnname from the table in the database. The column FriendID is additionally marked as primary key. Only those fields/properties you’ve marked with an ColumnAttribute are persisted in the database and could be loaded from database via LINQ to SQL. Ok, so far we’ve created a Friend class mapping to a Friends table in the database.

Now we can already connect to the Database and query the Friends table by using the DataContext class. The DataContext is used similar to the ADO.NET Connection. In fact the DataContext constructor takes a connection string and internally uses an IDbConnection. The DataContext is responsible to translate the queries you write in LINQ against your objects to SQL. To view the SQL the DataContext has generated for you, assign a TextWriter to its Log-Property. In the following snippet I’ve just assigned the standard output stream of the console to the Log-Property of the DataContext. I’ve passed in a connection string for the database “hubethomsDB” in my local SQLEXPRESS instance to the constructor of the DataContext:

DataContext ctx = new DataContext(
  @"Server=.\SQLEXPRESS;Database=hubethomsDB");

ctx.Log = Console.Out;    

In LINQ to SQL every table is represented by a Table-Collection of type System.Data.Linq.Table<TEntity>. As the name implies, the Table itself is identified by the entity class. Back to our sample, you get a Table-Collection for the table Friends by calling the generic Method GetTable<TEntity> on the DataContext and give the Method the Friend entity as the generic argument:

Table<Friend> friends = ctx.GetTable<Friend>();

On the received Table-Collection, you can create a query in LINQ. And now there’s a big difference to SQL. The query isn’t executed by the statement you see below, it’s only created.

var query = from f in friends
            where f.Age < 30
            select f;

The query gets executed, when you iterate over it, not before!!!

foreach (var friend in query)
{
  Console.WriteLine(friend.ToString());
}

The SQL generated by the DataContext is shown in the console window below. As you can see in the generated SQL, the data is filtered on the database and not in .NET.

20071117_LINQToSQL

Luca Bolognese said in his session, that Microsoft has tried every possible query and the DataContext was able to create a good SQL statement out of it. The tests have been done by people working for long times in the sqlserver team. Time to try some real complex queries on it and check it out.

What is the benefit of LINQ to SQL, when classes are mapped directly to tables?

The biggest benefit out of LINQ to SQL is that a developer hasn’t to know anything about SQL, he can specify and execute his query directly in C#.

Conclusion: I haven’t tested real complex SQL statements with LINQ to SQL up to now. Interesting are also things like indexes used by the generated query etc.

TechEd Developers 2007 in retrospect - Monday

Wednesday, November 14th, 2007

Last week I went to Barcelona for five days, participating at TechEd Developers 2007 (05. - 09. november). In the following posts I’ll just show you a short summary of my experience at TechEd Developers 2007. Let’s start on Monday.

On Monday the Keynote-Session started after a life grafiti-show with some really breaking news presented by S. Somasegar (Microsofts Corporate Vice President of the developer division):

  • Visual Studio 2008 and .NET 3.5 will be available to MSDN subscribers by the end of November
  • The first CTP of Microsofts Sync Framework is available now
  • For those of you using Microsoft Popfly, a new Popfly Explorer will be available
  • This year there will already be a CTP of the next Version of Visual Studio, called “Rosario”. In 2008 there will be a Beta of it

That are great news, especially the release of Visual Studio 2008 before the end of November. In fact Visual Studio 2008 really differs from the Visual Studio versions we had before. It’s the first time you can build applications that target different Framework Versions. With Visual Studio 2008 you can build applications that target .NET 2.0, .NET 3.0 or even .NET 3.5. This feature is called Multi-Targeting, and its possible, because .NET 2.0, .NET 3.0 and .NET 3.5 are all using the same Common Language Runtime, the CLR 2.0 that was introduced with .NET 2.0. Of course another great feature is the possibility to debug into the .NET Framework source code. A great possibility to learn some new best practices and to look how Microsoft has done it

The Microsoft Sync Framework is a new platform for enabling roaming, offline and collaboration across your applications, services and devices. The Framework also contains built-in support for synchronizing relational databases, NTFS and FAT file systems, etc. Get some more infos and the first CTP of it here.

After the Keynote-Session I joined the Session A Tour of Visual Studio 2008 and the .NET Framework 3.5, speaker Daniel Moth. Daniel explained that the .NET Framework 3.5 is a superset of .NET 3.0 (and so still uses the CLR 2.0). He showed some great features of the new IDE, like the new refactoring features added to the contextmenu in the codeeditor, or the transparency-feature for the intellisense-Window. You can make the intellisense-Window transparent by pressing the Ctrl-Key. So you can look at your code while leaving the intellisense-window open. Daniel also explained the terms of the green and red bits in a really good manner. Green bits are those assemblies that are new in .NET 3.5, and haven’t existed in .NET 3.0. Red bits are those assemblies that already existed in .NET 3.0, but are lightly extended and fixed with an installation of .NET 3.5. The Red bits are called “red”, because they describe a difficulty. If your .NET 3.0 application takes advantage of a not well implemented feature (maybe call it a bug :-)) in .NET 3.0 and that bug will be fixed with .NET 3.5, your application won’t work correctly anymore when you change this bug/feature by installing .NET 3.5. So microsoft has to be very careful with the red bits that are shipped as part of .NET 3.5. From the green and red bits you could also conclude something about the installation of .NET 3.5:

  • If you have .NET 3.0 already installed, an installation of .NET 3.5 will use this existing installation and change the red bit assemblies (some existing .NET 3.0 assemblies) and add some brand new Assemblies (the green bits). That means, after the installation of .NET 3.5 you wont come back to .NET 3.0, but every .NET 3.0 application should run well on .NET 3.5 (if Microsoft has done a good job with the red bits)
  • If you haven’t .NET 3.0 installed, an installation of .NET 3.5 will install whole .NET 3.0, plus the red and green bits of .NET 3.5

As the last session on Monday, I joined the session A Windows Communication Foundation (WCF) Walkthrough using Visual Studio 2008, but it wasn’t really as amazing as I thought before. The only new stuff for me about WCF I got out of this session were the things that ship with Visual Studio 2008, but nothing about WCF itself. In Visual Studio 2008 there will be new Project-Templates to generate a WCF-Library and a new UI that allows you to test your services easily.

In the evening, the “Ask The Experts” was open. The first thing I was looking for was an “Ask The Experts to WPF”-stand. But I didn’t find one. There were stands with experts in Visual Studio 2008, SQL Server, BI, Office, Silverlight and Expression and many more, but no stand with experts in WPF. So I just went to the Silverlight stand and asked for the WPF stand. The guy pointed to another person and said: “He asked me exactly the same questions 10 seconds ago, unfortunately there is no stand with WPF-experts”. And the other person said, “Some questions about WPF?”. Yeah, I thought, here I was right. Looking at his name, I recognized the name of the person and I knew, here I’m really right. It was Ian Griffiths, author of the very first WPF-book, “Programming WPF”, currently in its second edition. We spoke about nearly 1 hour about developing real enterprise applications with WPF, about the WPF-Designer in Visual Studio and about using Blend for designing your app. In most cases, Ian and I had the same opinion, and we both are waiting for the datagrid as part of .NET/WPF. :-) Today there are only third-party-grids available from famous control authors like those from Infragistics. Even in .NET 3.5 and WPF 3.5 (it’s really called WPF 3.5 and not WPF 1.5), Microsoft introduced no more 2D-Controls. But WPF 3.5 contains some new 3D-Elements like UIElement3D or Viewport2DVisual3D, that receive Input Events and make interactive 3D much easier than in WPF 3.0.