Thursday, April 05, 2007

Read your data easily from application resources

"I put my images and xaml vectors into projects resources and how I do not know how to get it" - this one of most common customers' questions. Really, how to get something exists in application resources, and the most important question is how to do it easy way? So, let's start.

Create new project. By using VS Solution Explorer create resource directory inside your project directory. Drag your images from Windows Explorer into this directory. Now create a couple of XAML vector elements or pages by using Microsoft Expression Suite and drop them into the same directory. Now let's take a close look to the properties of those files, all images become resources, when all xamls - pages. You do not really need them in this case as pages, so change their Build Action into Resource as well as appears within images.

So far so good. Now you have to pick them from your application. In order to get binary stream of our resources we'll have to use GetResourceStream method of Application. But stop. We have to do it as number of items we want to get. We have to hardcode it. Why not to build handy static method, that receives the resource path as parameter and return us the type we need. Good idea. The brilliant feature of .NET 2.0 and up is generics, and this is the "king case" to use them within this method. Let's do it.

 

static T loadResource<T>(string path)

        {

            T c = default(T);

            StreamResourceInfo sri = Application.GetResourceStream(new Uri(path, UriKind.Relative));

 

            if (sri.ContentType == "application/xaml+xml")

            {

                c = (T)XamlReader.Load(sri.Stream);

            }

            else if (sri.ContentType.IndexOf("image") >= 0)

            {

                BitmapImage bi = new BitmapImage();

                bi.BeginInit();

                bi.StreamSource = sri.Stream;

                bi.EndInit();

                if (typeof(T) == typeof(ImageSource))

                {

                    c = (T)((object)bi);

                }

                else if (typeof(T) == typeof(Image))

                {

 

                    Image img = new Image();

                    img.Source = bi;

                    c = (T)((object)img);

                }

            }

 

            sri.Stream.Close();

            sri.Stream.Dispose();

 

            return c;

        }

We done. Now, all you have to do is to call something like this to bring image source.

 

Image img = new Image();

img.Source = loadResource<ImageSource>("Resources/myImage.png");

Or something like this to bring FrameworkElement.

 

Window w = new Window();

w.Content = loadResource<Border>("Resources/myBorder.xaml");

((Border)w.Content).Child = loadResource<StackPanel>("Resources/myStackPanel.xaml");

((StackPanel)((Border)w.Content).Child).Children.Add(img);

Have a good day, dudes. Take this day to extend our magic resources loader class to another content types (if needed)

Binding to binding of two listboxes

Let's imagine following thing. I have list of projects and list of employees, assigned to those projects. Now I want to select some projects and see employees' assignments - who's going to work overtime. Simple, yes? We just create two listboxes. One binded to the list pro projects, and the second is binded to the selected items of first listbox with converter, that calculate unique employees and return calculated result. Something like this. Here we can clearly see, that Employee 12 already forgot how his kids looks like.

 

      <ListBox Name="prjs" SelectionMode="Extended" ItemsSource="{StaticResource projects}"/>

      <ListBox Name="emps1" ItemsSource="{Binding ElementName=prjs, Path=SelectedItems, Converter={StaticResource myConv}}"/>

Do it. You'll notice very fast, that your converter myConv will be called only once, when you have nothing selected, so it simple impossible to convert selected values to something, we need.  You know what, it makes sense, why I should reinitialize converter, if my types are not going to change?

Let's try another trick. We'll put shared datasource in application resource level and on SelectionChanged event put our stuff there. After it we'll just bind second listbox to this source.

 

<l:Employees x:Key="employees"/>

<l:Projects x:Key="projects"/>

 

 

<ListBox Name="prjs" SelectionMode="Extended" ItemsSource="{StaticResource projects}" SelectionChanged="onSelection"/>

<ListBox Name="emps" ItemsSource="{Binding Source={StaticResource employees}}"/>

 

 

void onSelection(object sender, SelectionChangedEventArgs e)

        {

            Employees emps = this.Resources["employees"] as Employees;

 

            if (emps != null)

            {

                for (int i = 0; i < e.RemovedItems.Count; i++)

                {

                    Project p = e.RemovedItems[i] as Project;

                    for (int j = 0; j < p.Employees.Count; j++)

                    {

                        if (emps.Contains(p.Employees[j]))

                        {

                            if(emps[emps.IndexOf(p.Employees[j])].Width == 0)

                            {

                                emps.Remove(p.Employees[j]);

                            }

                            else

                            {

                                emps[emps.IndexOf(p.Employees[j])].Width--;

                            }

                        }

                    }

                }

 

                for (int i = 0; i < e.AddedItems.Count; i++)

                {

                    Project p = e.AddedItems[i] as Project;

                    for (int j = 0; j < p.Employees.Count; j++)

                    {

                        if (!emps.Contains(p.Employees[j]))

                        {

                            emps.Add(p.Employees[j]);

                        }

                        else

                        {

                            emps[emps.IndexOf(p.Employees[j])].Width++;

                        }

                    }

                }

            }

        }

Now it's works. The only thing we have to do is create simple datatemplate to visualize an employee assignment.

 

    <DataTemplate DataType="{x:Type l:Employees}" x:Key="emp">

      <TextBlock FontSize="{Binding Path=Width, Converter={StaticResource wts}}" Text="{Binding Path=Name}"/>

    </DataTemplate>

That's all folks, not always we should go straight-forward to get what we need from WPF, but it's looks like no really obstacles can be found there.

Source code for this article. 

Wednesday, April 04, 2007

Expression Blend and Web are available on MSDN

For all those who asked about how goes licensing of Microsoft Expression Suite, the answer is, that both Blend and Web Expression are available for MSDN Premium users. Great news.

Sunday, April 01, 2007

Too much "async" with this WPF

What's this post about? This post begins with DIY. Try to do the following:

  1. Add simple ListView to your application
  2. Inside the ListView add two TextBlocks
  3. For each TextBlock subscribe to OnMouseDown (or any other mouse event)
  4. OnMouseEvent create new Window and open it with Show() method.

Did it? Fine. Have you paid your attention, that each new window opens this way goes backward? Don't it looks a bit strange?Let's give ListView other try.

  1. Add simple ListView to your application
  2. Inside the ListView add two TextBlocks
  3. Subscribe to SelectionChanged event of the listview
  4. OnSelectionChanged create new Window and open it with Show() method.

The same result? Maybe all collections have this bug behavior? Let's give a try to LiveBox... Do the same as in previous try, but instead of ListView use ListBox. The behavior disappears. Now the new window opens normally over the main window. What's the difference?

Return to second try (with SelectionChanged event), but put SelectionMode property of ListView to "simple" or "multiple". Works fine, right. So the problem with SelectorItem selection. Let's dive a bit deeper.

What's actually happens? If you have rather slow computer, you can clearly see the process. First occurs "mouse event", then opens window at the front of openner, next the item becomes selected and steals focus. Why ListViewItem doing it? According my short investigation, the root of the problem is Automation boundary. If you have time and wish to do it, trace all events (by using global events handling) and see it yourself. If you have either time nor wish, the answer is following.

WPF process almost any operation asynchronously, so with new window opening, the item becomes selected  and grab focus. How to solve this. Simple. Do your work very asynchronous way. Following the code, that opens window with normal thread priority, so it waits for openner to finish all tasks to process new job.

 

delegate void OpenWindowDelegate(bool bringFocus);

        void OpenWindow(bool bringFocus)

        {

            if (!bringFocus)

            {

                Window1 w = new Window1();

 

                w.Show();

            }

            else

            {

                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,

                    new OpenWindowDelegate(OpenWindow), false);

            }

 

 

        }

We finished, now your windows will be opened above the opener and you're be able to do anything with both of those windows (ShowDialog() method or setting owner property for opened window will works fines, even without it, 'cos it locks the focus on newly opened window.

Happy Passover to all of you. Oh, I almost forgot my original question: Does this behavior is bug or not? I'm really interested with your opinion.

Source code for this article

Thursday, March 29, 2007

Asynchronous Data templates, data providers and Data Binding

DataBinding, templates and providers and really cool things in WPF, but have you tried to load something really heavy? How time it's take to load 20 images? A couple of seconds? And what about if each image is 3000X3000 px? Huh, your HMI thread will be locked until all those images will be downloaded and displayed. In this post, I'll explain how to build asynchronous XMLDataProvider, that load RSS from Flickr, asynchronous DataTemplate, that loaded image by image without locking your application and asynchronous Binding, that provides an ability to separate images and not to load all of them, if they not visible. So, let's start.

First of all we have to retrieve Flickr RSS feed. So, we'll create XmlDataProvider for this

<XmlDataProvider  
                 Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=wallpaper&amp;format=rss_200" 
                 XPath="/rss/channel/item" x:Key="src"/>

This the first and really easy part. Nice, now we'll create data template and the host for it



<DataTemplate x:Key="img">
      <Image Source="{Binding XPath=media:content/@url}" Stretch="Uniform"/>
</DataTemplate>
 


<ListBox Grid.Row="1" ItemsSource="{Binding Source={StaticResource src}}"
            ItemTemplate="{StaticResource img}"/>

Fine, run it to see nothing. Why? because of XmlNamespace media, found in RSS 2.0. We should tell XmlDataProvider what's the namespace, so we have to add Namespace manager to point to http://search.yahoo.com/mrss/ URI, that actually describes media namespace. To do it, all you have to do it to add XmlNamespaceMapping to your resources and point XmlDataProvider to see it.


 



<XmlNamespaceMappingCollection x:Key="map">
      <XmlNamespaceMapping Uri="http://search.yahoo.com/mrss/" Prefix="media"/>
</XmlNamespaceMappingCollection>
 
<XmlDataProvider XmlNamespaceManager="{StaticResource map}" 
                     Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=wallpaper&amp;format=rss_200" 
                     XPath="/rss/channel/item" x:Key="src"/>

So far so good, but now, when you'll run your application, it become frozen for 15 minutes, until all images will be loaded, then it force your CPU to 100% for 2 minutes to render all those images. Hm, well, you have really fast internet and your computer has Four Quad Core CPU. In this case, your application freeze for only three minutes. Really bad, isn't it?


So what to do? Let try first of all convert our data source to asynchronous. In order to do it, we'll set IsAsynchronous property to"True". Additional fix we'll add is to force the data provider to work, even before, we'll need it. Set IsInitialLoadEnabled="True". Compile.


Now it's better. We just saved the interface from freezing for 10 seconds (while RSS loaded). Still bad, really bad! The actual problem is not in DataProvider, but in all those urls and large images in it. Let make our DataBinding to work asynchronous. Let's make it load images one by one.


We'll add another property to the binding expression of our hosting control. And now it'll looks like this


 



<ListBox ItemsSource="{Binding IsAsync=True, Source={StaticResource src}}"
             ItemTemplate="{StaticResource img}"/>

Very well. Now our UI is released and all images loaded one-by-one without holding STAThread, which actually run it.


The next challenge is to force an application not to load all those images, which are not visible and see how many images already downloaded. For this, we'll add eventhandler Loaded event of image in the template. Add read only Dependency Property to your window and bind it to textblock to see.



int loadedTotalCounter = 0;
        void onImgLoaded(object sender, RoutedEventArgs e)
        {

SetValue(ImagesTotalPropertyKey, ++loadedTotalCounter);
        }


public static readonly DependencyPropertyKey ImagesTotalPropertyKey = DependencyProperty.RegisterReadOnly("ImagesTotal",

    typeof(int),

    typeof(Window1),

    new PropertyMetadata(0));

 

public static readonly DependencyProperty ImagesTotalProperty = ImagesTotalPropertyKey.DependencyProperty;

 

public int ImagesTotal

{

    get { return (int)GetValue(ImagesTotalProperty); }

}

Wow, if we'll put our ListView into grid, all invisible items will not being loaded, until we'll reveal them. Nice feature. Really nice, but why our counter of loaded images grows, even if the images are invisible?


The reason is simple, ImageSource is asynchronous property, so when we even got the source, this does not means, that the image is really loaded, so how to figure the actually number of loaded images. Let's dive deeper into ImageSource.


The object behind the ImageSource is BitmapFrame and it's (as we already tell) asynchronous object, so it has Download-related events such as DownloadCompleted, DownloadProgress and DownloadFailed. Let's put another readonly DP to our window, to cound actually downloaded frames


 



public static readonly DependencyPropertyKey ImagesLoadedPropertyKey = DependencyProperty.RegisterReadOnly("ImagesLoaded",
            typeof(int),
            typeof(Window1),
            new PropertyMetadata(0));
 
        public static readonly DependencyProperty ImagesLoadedProperty = ImagesLoadedPropertyKey.DependencyProperty;
 
        public int ImagesLoaded
        {
            get { return (int)GetValue(ImagesLoadedProperty); }
        }
 
        public static readonly DependencyPropertyKey ImagesTotalPropertyKey = DependencyProperty.RegisterReadOnly("ImagesTotal",
            typeof(int),
            typeof(Window1),
            new PropertyMetadata(0));

Now, let's get actual source and subscribe it to counter


 


void onDownloadCompleted(object sender, EventArgs e)
        {
            SetValue(ImagesLoadedPropertyKey, ++loadedCounter);
        }
 
 
 
        int loadedCounter = 0;
        int loadedTotalCounter = 0;
        void onImgLoaded(object sender, RoutedEventArgs e)
        {
            Image img = sender as Image;
            if (img != null)
            {
                BitmapFrame bimage = img.Source as BitmapFrame;
                if (bimage != null)
                {
                    bimage.DownloadCompleted += new EventHandler(onDownloadCompleted);
                }
            }
            SetValue(ImagesTotalPropertyKey, ++loadedTotalCounter);

        }

That's works great, but so some reason, DownloadCompleted event not always being fired. Recently, when the framework "skips" it, the image appears too fast. Is it bug? Not really. The real source for image is not network, but local cache, so not always BitmapFrame downloaded. And if it is not, why to fire event. Add handler for this, set break point and see.


 


void onDownloadCompleted(object sender, EventArgs e)
        {
            SetValue(ImagesLoadedPropertyKey, ++loadedCounter);
        }
 
 
 
        int loadedCounter = 0;
        int loadedTotalCounter = 0;
        void onImgLoaded(object sender, RoutedEventArgs e)
        {
            Image img = sender as Image;
            if (img != null)
            {
                BitmapFrame bimage = img.Source as BitmapFrame;
                if (bimage != null)
                {
                    //why this?
                    //Actually, the images are loaded from cache, so we have to check if it's downloading before, we'll want it to complete an action :)
                    if (bimage.IsDownloading)
                    {
                        bimage.DownloadCompleted += new EventHandler(onDownloadCompleted);
                    }
                    else
                    {
                        SetValue(ImagesLoadedPropertyKey, ++loadedCounter);
                    }
                }
            }
            SetValue(ImagesTotalPropertyKey, ++loadedTotalCounter);

        }

Dunno. Now we have everything working asynchronous way and our UI is free for action. Does WPF architecture is really genius to think about all those cases?


Source code for this article

textbox for high-contrast very small text

 The most common question about text capabilities in WPF is about small fonts. By default all texts rendered with presentation layer are anti-aliased,  wich means, that we will get great text experience with large fonts, and blurry texts with small and extra small fonts. 

As you, probably know, the common usage of big fonts is in entertainment-related application, however most of business-related applications using small fonts. There is impossible to solve "blurry" problem with WPF texts, so today, we'll solve it with WPF geometry. Today, we'll create custom textblock, that holds texts, which visible and readable on any background, even with very small fonts. 

 

 So, let the show start. First of all, we'll create new control, derived from FrameworkElement. We'll add a couple of dependency properties for Text, Font, FontSize, fore and background color. But, were the trick, you'll ask... Instead of drawing text, onRender event, we'll draw geometry of the text and stroke it with contrast color.

 

protected override void OnRender(DrawingContext drawingContext)
       {
           drawingContext.DrawGeometry(Fill, m_pen, m_textg);
       }

The next question is - where to get the geometry of the text? FormattedText class exposes method named BuildGeomerty, that converts text into geometrical representation. So, in order to build a text and it's geometry, we'll build internal method, for text generation, based on control's DPs


 



private void GenerateText()
        {
            if (Font == null)
                Font = new FontFamily("Arial");
 
            FormattedText fText = new FormattedText(
               Text,
               CultureInfo.CurrentCulture,
               FlowDirection.LeftToRight,
               new Typeface(
                   Font,
                   FontStyles.Normal,
                   FontWeights.Heavy,
                   FontStretches.Normal),
               FontSize,
               Brushes.Black
               );
 
            m_textg = fText.BuildGeometry(new Point(0, 0)).GetAsFrozen() as Geometry;
        }

So now, after compilation, we'll get the text stroked with contrast pen, but it will be anti-aliased. What to do? Framework, can not cancel anti-aliasing for text, but it can do it for geometry. In order to do it, just call the framework to cancel it.



RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);


There are a couple of other tips you'll have to do. One is snap your graphics to device pixels. Why to do it? Read MSDN :)



this.SnapsToDevicePixels = true;


Additional tip is set linejoin to Round and MeterLimit to 1 for line "pike" prevention. One other trick is to freeze the pen after generation, because, you wont going to change it while rendering, so save the system resources.


 



private static void OnTextInvalidated(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            m_pen = new Pen(((HiResTextBlock)d).Stroke, ((HiResTextBlock)d).StrokeThickness);
            m_pen.LineJoin = PenLineJoin.Round;
            m_pen.MiterLimit = 1;
            m_pen = m_pen.GetAsFrozen() as Pen;
            ((HiResTextBlock)d).GenerateText();
        }

Now, tell the framework to call all those methods by doing this and you're done


 



public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
            "Text",
            typeof(string),
            typeof(HiResTextBlock),
            new FrameworkPropertyMetadata(
                 "",
                 FrameworkPropertyMetadataOptions.AffectsRender,
                 new PropertyChangedCallback(OnTextInvalidated),
                 null
                 )
            );

Now, let's see what we get. Pretty nice isn't it? 



 Source code for this article

Creating datatemplates from code

It's really easy to create data templates from XAML, but today, one of my clients asks me to do it from code. The other request was to handle events of element form inside the template. So let's do it together

First of all we have to create DataProvider as we usual do in xaml.

 

XmlDataProvider data = new XmlDataProvider();
           data.Document = new System.Xml.XmlDocument();
           data.Document.InnerXml = getXMLstring();
           data.XPath = "/root/node";

Next step is to create binding expression for data template usage


 



Binding itemsBinding = new Binding();
            itemsBinding.XPath = "val";

So far, so good. Now comes the trick. In order to use DataTemplate class, we have to create Visual Tree of elements, being used in the template. In order to do it, first we should create FrameworkElementFactory and set all necessary handlers and properties there. The factory, is actually, kind of meta element,  derived from FrameworkElement and makes us able to markup anything, we have to have within the instance of future element. So let's do it


 



FrameworkElementFactory comboFactory = new FrameworkElementFactory(typeof(ComboBox));
            comboFactory.Name = "myComboFactory";
            comboFactory.SetBinding(ComboBox.ItemsSourceProperty, itemsBinding);
            comboFactory.AddHandler(ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(popup));

As you can see, I'm setting Binding and add event handler to FrameworkElementFactory in order them to appears in real element that will be generated by the factory.


The next step is rather simple. We'll create DataTemplate and set it's VisualTree property to newly created factory.


 



DataTemplate itemsTemplate = new DataTemplate();
           itemsTemplate.VisualTree = comboFactory;

Another binding, setting ItemTemplate property and we done.


 



Binding nodeBinding = new Binding();
            nodeBinding.Source = data;
 
            ListView lv = new ListView();
            lv.ItemTemplate = itemsTemplate;
            lv.SetBinding(ListView.ItemsSourceProperty, nodeBinding);
 
            myGrid.Children.Add(lv);

It's rather straight-forward to do it, but still, it's much simpler to create templates from XAML, isn't it? :)


Source code for this article