Archive for the ‘WPF’ Category

The Lottery-Console-Application used at the last WPF-Event @ Microsoft Usergroup Switzerland

Monday, August 25th, 2008

Last week we had a great WPF-afterwork-event at Microsoft Usergroup Switzerland (MSUGS) sponsored by Trivadis. I gave a deep-dive session about developing custom controls using WPF with many of it’s features like Dependency Properties, Commands, Routed Events, PART-Elements, Theme-Styles and so on.

At the end of the session a copy of my German WPF-book was drawn. We made a small lottery, but not a normal one. As all attendees were .NET-developers, everyone trusted in .NETs Random-class, so why don’t do it just in code?! We’ve written life a small console-application that did the job for us. As some people asked for the code (of course only the loosers and not the winner of the book ;-) ), here it is:

static void Main(string[] args)
{
  Console.WriteLine();
  Console.WriteLine("  — MSUGS- WPF-Book Lottery");
  Console.WriteLine("  Enter names and a dot (\".\")"
                  + " when names are complete");
  Console.WriteLine();

  List<string> names = new List<string>();
  Console.Write(">");
  string name = Console.ReadLine().Trim();

  while (!name.Equals("."))
  {
    names.Add(name);
    Console.Write(">");
    name = Console.ReadLine().Trim();
  }

  Random random = new Random();
  int winnerIndex = random.Next(names.Count);

  string winner = names[winnerIndex];

  Console.WriteLine();
  Console.WriteLine("Starting lottery…");

  Thread.Sleep(3000);

  Console.Write("And the winner is");

  for (int i = 0; i < 10; i++)
  {
    Thread.Sleep(1000);
    Console.Write(".");
  }
  Console.WriteLine();
  Console.WriteLine();

  Console.WriteLine(winner);

  Console.ReadLine();
}

The Console-Application looks like this:

image

The lucky winner at the MSUGS-event was Stefan, he was at index zero in the names-Collection. Congratulations!

st_msugs_080820

Thanks to MSUGS for the great organization and to all developers who attended in the session. I hope you enjoyed it.

WPF-book is now available in stores, maybe you win a free one @MSUGS

Monday, June 30th, 2008

Since last week my German WPF-book is available in stores. You find more details about the book and some snippets of chapter 1 and chapter 14 on Galileo Computing. You can order the book on the Galileo Comuting-Website or on amazon.de and other stores.

For any questions about the book, write a comment to this post or use the contact-form of my homepage. If you’ve already got the book, I’m looking forward to your feedback.

What’s going on next:

Free MSUGS-Event about developing Custom Controls with the chance to win a WPF-book:
On Wednesday, 20th August, you can visit a free event in cooperation with the Microsoft User Group Switzerland (MSUGS) about developing Custom Controls with WPF. The event will be in Zurich @Trivadis (Europastrasse 5). You find more details about the event here. At the end of this event, you can win one WPF-Book for free.

WPF-Course @Trivadis:
If you want to know more things about WPF-Programming, take a look at the 3-day WPF-course at Trivadis, which you find here. If you take this course, you’ll get a WPF-book, the Trivadis course-material, and everything you need to become a rich & famous WPF-Programmer. ;-)

DataAccess in the time of LINQ:
Christoph Pletz and I are working on a TechnoCircle - a one day event you can visit in the second half of this year @Trivadis - about DataAccess in the time of LINQ. This TechnoCircle does not only show you how LINQ works, it shows how to implement a Data Access Layer in the time of LINQ in a Three-Layer-Architecture. It also discusses the usage of LINQ to SQL vs. Entity Framework vs. DataSets etc. As soon as you can register for the TechnoCircle, you’ll find more infos on the Trivadis-website and of course here on my blog…

Print of WPF-book will start next week

Saturday, May 31st, 2008

As I promised in my last post, here are some infos about my nearly finished book project:

Last weekend I made checks on the first galley proof of my german WPF-book. Yesterday I got the second galley proof, the corrected one. The second galley proof I’ve checked yesterday evening and today. The book will have about 1125 pages filled up with pure Windows Presentation Foundation and will be printed at the end of next week.

Last week I saw that the book is already listed under the WPF-books on WindowsClient.NET. Who ever linked it up, thanks a lot for doing so:
>> http://windowsclient.net/community/books.aspx

As the corrections are made and the book will be printed next week, the upcoming weekend will be the first totally free weekend for me since one year. Two weeks ago I got a red card in a soccer match, so I’m not allowed to play the last game. So next weekend is really totally free, no soccer game and no book-writing. :-)

So what should I do this upcoming weekend? I could start writing another WPF- or Silverlight-article. But no, on that first free weekend for such a long time I won’t do that. I tell you what I’m going to do, if the weather won’t be totally bad:

About one month ago I bought a new bike (on the picture below), so I’ll test it on a tour with my family next weekend. There are several mountains and single trails directly around our home, where you can jump and ride with a lot of fun. As I know there are also many bikers at Trivadis (the company I’m working for), maybe I’ll meet some of them in a race down the hills through the great black forest

bikingThomas

Got the MCTS: .NET Framework 3.5, Windows Presentation Foundation

Sunday, May 18th, 2008

Last Thursday I took the exam for the Microsoft Certified Technology Specialist .NET Framework 3.5, Windows Presentation Foundation. The exam is brand new and covers a wide spectrum of WPF.

Im not sure, if asking Multiple-choice-questions is a good thing for testing the knowledge of programmers, but hey, the exam was a good test for my German WPF-book. (I didn’t have the book with me, but it’s still in my head. Like a branding :-)).

After every question I read, I thought, if the answer of the question can be found in my book. And I’m really glad to say that, with some exceptions to specific deployment questions, everything can be found in my book. So if you know all contents and details of my book well, you won’t have any problems to pass this exam. So with the book still in my head I did it and earned my fourth MCTS:

 MCTS_Logo

By the way, I’ve finished the manuscript for my wpf book in time. Since end of April the correctors give their best and I’m sure the book will be in stores in June 2008, according to plan. Find more infos about the book-process during the next weeks on this blog.

UIAutomation to open ComboBox from Code

Sunday, May 18th, 2008

In WPF there’s an Automation Framework called UIAutomation. This Framework can be used to control UIElements from code. This can be useful for different scenarios:

  • Provide the user additional help
  • Control a programm by another programm
  • Test applications
  • Execute a user-action from code

The Automation Frameowork isn’t limited to WPF. You can also control Win32-Applications.

In WPF for every FrameworkElement you find a class named like [TheElementsName]AutomationPeer. E.g. for the Button-class there’s a ButtonAutomationPeer-class, for ComboBox there’s a ComboBoxAutomationPeer-class…

Such AutomationPeer-Classes support different Patterns. E.g. the ComboBoxAutomationPeer-class supports the ExpandCollapse-Pattern to expand and collapse the ComboBox. You do this with the following snippet:

ComboBoxAutomationPeer peer =
  new ComboBoxAutomationPeer(yourComboBox);
IExpandCollapseProvider provider =
  (IExpandCollapseProvider)
  peer.GetPattern(PatternInterface.ExpandCollapse);
provider.Expand();

There’s much more you can do with UIAutomation, which is part of my German WPF-book (Chapter 19).

WPF Multi-Layer Business Application for Download

Friday, May 16th, 2008

Tomorrow Karl Shifflett is giving a Code Camp session in Charlotte. Unfortunately it’s too far away for me to participate. :-)

Today Karl has posted a really great WPF Multi-Layer Business Application that can be downloaded from his blog. Check it out here and learn from it. Thx to Karl for posting and sharing that great sample app.

LostFocus (TextBox) vs. Buttons IsDefault-Property

Friday, May 2nd, 2008

If you bind the Text-Property of a TextBox to something, the "something" is updated when the TextBox loses focus. This is the Default-UpdateSourceTrigger defined in the Metadata for the TextBox.TextProperty. In a Data Binding you can specify another UpdateSourceTrigger, like e.g. PropertyChanged.

If a TextBox has LostFocus as UpdateSourceTrigger, which is the default, you can get problems if the TextBox is inside of a Dialog that contains a OK-Button with the IsDefault-Property set to true. When the TextBox has the Focus, the user can press Enter and the Button is clicked, but the TextBox still keeps the Focus. The LostFocus-Event doesn’t occur, so the Source of a Data Binding isn’t updated with the value of the TextBoxs Text-Property. You need to update the source explicit. Let’s take an example and use the Person-class of my previous post:

public class Person : INotifyPropertyChanged
{
  private string _name;
  public string Name
  {
    get { return _name; }
    set
    {
      _name = value;
      if (PropertyChanged != null)
        PropertyChanged(this,
          new PropertyChangedEventArgs("Name"));
    }
  }
  public event PropertyChangedEventHandler PropertyChanged;
}

The Window below just contains a TextBox and a Button. The Text-Property of the TextBox is bound to the Name of the data in the DataContext. This would be a Person-instance, as you’ll see below in the codebehind-file. The Button has it’s IsDefault-Property set to true and defines an eventhandler for the Click-Event.

<Window x:Class="LostFocusTest.Window1" …
  xmlns:local="clr-namespace:LostFocusTest"
  Title="Focus/IsDefault" Width="200" SizeToContent="Height">
  <StackPanel>
    <TextBox Margin="5" Text="{Binding Name}"/>
    <Button Content="OK" IsDefault="True"
       Click="Button_Click"/>
  </StackPanel>
</Window>

In the Constructor in the Codebehind-file a Person-instance is created. It’s assigned to the Windows DataContext-Property, so the TextBox above will display the Persons name, which is set to "Thomas". The Click-Eventhandler for the Button simply displays the name of the Person in a MessageBox.

public partial class Window1 : Window
{
  private Person _pers;
  public Window1()
  {
    InitializeComponent();
    _pers = new Person();
    _pers.Name = "Thomas";
    this.DataContext = _pers;
  }

  private void Button_Click(object sender, RoutedEventArgs e)
  {
    MessageBox.Show(_pers.Name);
  }
}

If I start the application and type "Urs" into the TextBox and press Enter, the Button is clicked but the TextBox keeps the focus. So the Source, which is the Person-Instance, isn’t updated and the MessageBox still displays the old value (”Thomas”), as you can see in the Image below:

LostFocus vs. IsDefault

For such a scenario, you have to update the source explicit. You could do this in the Click-Eventhandler. To update the source, you have to get the BindingExpression for the TextProperty. You get the BindingExpression by calling the GetBindingExpression-Method on the TextBox. Pass in the Text-Property as parameter. On the BindingExpression call the UpdateSource-Method to update the Person-instance explicitly with the value defined in the Text-Property of the TextBox. With the Eventhandler below the Person-Instance would always be actualized when the Button is clicked. The MessageBox would display the right value:

private void Button_Click(object sender, RoutedEventArgs e)
{
  TextBox textBox = Keyboard.FocusedElement as TextBox;
  if (textBox != null)
  {
    BindingExpression be =
      textBox.GetBindingExpression(TextBox.TextProperty);
    if (be != null)
      be.UpdateSource();
  }
  MessageBox.Show(_pers.Name);
}

Just kick it for me:

kick it on DotNetKicks.com

Vista’s SaveFileDialog and OpenFileDialog in WPF

Saturday, April 12th, 2008

Windows Vista contains new Win32-Dialogs to save and open a file. There are also the old dialogs from XP available.

Windows Presentation Foundation has two wrapper-classes for Win32-Dialogs. The Microsoft.Win32-Namespace contains a SaveFileDialog- and an OpenFileDialog-class. The classes are located in the PresentationFramework-Assembly, one of the central assemblies of WPF.

When you use the classes from Microsoft.Win32-Namespace, you get the old dialogs from XP. In the snippet below the OpenFileDialog is opened.

Microsoft.Win32.OpenFileDialog dlg =
  new Microsoft.Win32.OpenFileDialog();
dlg.ShowDialog()

With the two lines above the dialog below is shown, and that’s the old-style Windows XP OpenFileDialog:

image

Windows Forms also wraps the two Dialogs SaveFileDialog and OpenFileDialog with classes in the namespace System.Windows.Forms. Add a reference to the assembly System.Windows.Forms.dll to your WPF-Project, and you can use these wrapper-classes. The interesting part is that they show per default the new Vista Dialog.

System.Windows.Forms.OpenFileDialog dlg =
  new System.Windows.Forms.OpenFileDialog();
dlg.ShowDialog();

With the lines above the new Vista Dialog is displayed:

image

Both WinForms-Dialog-Classes contain a property called AutoUpgradeEnabled (inherited from FileDialog, property is supported in .NET Versions 3.5, 3.0 SP1 and 2.0 SP1). This property is per default true, so the FileDialog-Instance will automatically upgrade appearance and behavior when running on Windows Vista. Set it to false, to get the old dialog-style:

System.Windows.Forms.OpenFileDialog dlg =
  new System.Windows.Forms.OpenFileDialog();
dlg.AutoUpgradeEnabled = false;
dlg.ShowDialog();

On XP, the AutoUpgradeEnabled-property doesn’t have any effect, of course, there’s only the old dialog available.

Fazit: The cool thing about Microsoft.Win32 is that you can add a using-directive to your WPF-Project and use the classes inside that namespace without a full qualified name. Adding a using-directive for System.Windows.Forms isn’t a good thing in a WPF-Project. There are many double-matches in System.Windows.Forms and e.g. WPF’s System.Windows.Controls-Namespace, like e.g. the Button-class. So the compiler needs full qualified names. But if you wan’t to use the new Dialogs, you have to use the Wrappers from Windows Forms, but don’t add a using-directive for System.Windows.Forms, use full qualified names instead.

There are also other possibilities to get the new vista dialogs. E.g. you could make a Win32-call into comdlg32.dll, but the already available wrappers from Windows Forms are the easiest and fastest way to do it. And you won’t program something, if it’s already there, right? But you have to know that it is there. 8-)

I think Microsoft will update the classes in Microsoft.Win32 in the near future, maybe in the upcoming servicing release for .NET 3.5 planned for Summer 2008? It’s really a little bit strange, WPF is the technology to create first class Vista apps, and its wrappers show still old dialogs, while Windows Forms wrappers don’t…

Take Snapshots PART II - Save as animated GIF

Wednesday, April 9th, 2008

I was asked, if it would be possible to save the snapshots created in my last post as an animated gif. With a DispatcherTimer and the GifBitmapEncoder-class you’re not far away from it. Just create a MediaElement in your Window:

<MediaElement Source="thomasOnBoard.wmv"
  x:Name="media" MediaOpened="media_MediaOpened"
  MediaEnded="media_MediaEnded" Width="300"
  Height="200" Stretch="Fill"/>

In the Codebehind-File, implement Eventhandlers for MediaOpened and MediaEnded-Events. In MediaOpened you start the DispatcherTimer. I’ve just used an interval of 100 milliseconds. In the Tick-Eventhandler, which is called each 100 milliseconds, a BitmapFrame is added to the GifBitmapEncoders Frames-Property. When the video ends, the MediaEnded-Eventhandler writes the GIF to your disk and opens the file. That’s it. :-)

public partial class Window1 : Window
{  …
  GifBitmapEncoder _encoder;
  DispatcherTimer _timer;
  private void media_MediaOpened(object sender, …)
  {
    _timer = new DispatcherTimer();
    _timer.Interval = TimeSpan.FromMilliseconds(100);
    _timer.Tick += OnTick;
    _timer.Start();
  }
  void OnTick(object sender, EventArgs e)
  {
    Size dpi = new Size(96, 96);
    RenderTargetBitmap bmp =
      new RenderTargetBitmap(300, 200,
        dpi.Width, dpi.Height, PixelFormats.Pbgra32);
    bmp.Render(media);

    if (_encoder == null)
      _encoder = new GifBitmapEncoder();

    _encoder.Frames.Add(BitmapFrame.Create(bmp));
  }

  private void media_MediaEnded(object sender, …)
  {
    _timer.Tick -= OnTick;
    _timer = null;

    string filename = Guid.NewGuid().ToString() + ".gif";
  FileStream fs = new FileStream(filename, FileMode.Create);
    _encoder.Save(fs);
    fs.Close();
    _encoder = null;

    Process.Start(filename);
  }
}

Here’s the gif saved from my video. Just click on it to see it animated:

withWPFCreated

Take Snapshots of Videos with WPF

Sunday, April 6th, 2008

With WPF’s Imaging-Classes you can take snapshots of any Visual. The snapshot can be saved in any common Image-Format, like e.g. JPG. Let’s take a look at a pretty short example, that shows how easy this can be done. The example takes snapshots of a Video.

The following Window contains a MediaElement and a Button. The MediaElement plays the Video thomasOnBoard.wmv. The Button defines an Eventhandler for the Click-Event. It takes a snapshot of the video, when you click it.

<Window x:Class="SnapShots.Window1"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/…
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
 ResizeMode="NoResize">
  <StackPanel>
   <MediaElement x:Name="media" Height="200" Stretch="Fill">
      <MediaElement.Triggers>
       <EventTrigger RoutedEvent="MediaElement.Loaded">
        <BeginStoryboard>
         <Storyboard>
          <MediaTimelineSource="thomasOnBoard.wmv"
           RepeatBehavior="Forever"/>
         </Storyboard>
        </BeginStoryboard>
       </EventTrigger>
      </MediaElement.Triggers>
     </MediaElement>
     <Button Click="Button_Click" Content="Snapshot"/>
  </StackPanel>
</Window>

Let’s look at the Eventhandler of the Button. An instance of the RenderTargetBitmap-class is created with some parameters about image-size, dots per inch (dpi) and Pixelformat. The Render-Method gets the MediaElement as a parameter, so MediaElements visual appearance is stored in the RenderTargetBitmap in memory. With a JpegBitmapEncoder and a FileStream the Image is written as a JPG to disk. That’s it.

void Button_Click(object sender, RoutedEventArgs e)
{
  Size dpi = new Size(96,96);
  RenderTargetBitmap bmp =
    new RenderTargetBitmap(300, 200,
      dpi.Width, dpi.Height, PixelFormats.Pbgra32);
  bmp.Render(media);

  JpegBitmapEncoder encoder = new JpegBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(bmp));

  string filename = Guid.NewGuid().ToString()+".jpg";
  FileStream fs = new FileStream(filename,FileMode.Create);
  encoder.Save(fs);
  fs.Close();

  Process.Start(filename);
}

Instead of taking the picture in the Button_Click eventhandler, you could create a Timer and take an Image every 0.1s. That allows you to extract an image-sequence of your videos. As it works for any Visual, and everything that’s on the screen in a WPF-Application is a visual, there are many things you can do with it. You could create a snapshot of an Image drawn to an inkCanvas, upload it to a webserver to display it on a webpage etc.