Solved: Objects are not fully deserializing when using DataContractSerializer in Silverlight.

By dsandor at July 07, 2010 02:53
Filed Under: Programming, Silverlight, WCF, WPF

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer_members.aspx

So as it turns out, your XML stream must have the XML Nodes in Alphabetical Order when trying to deserialize XML data into an object.  Very wierd.

Silverlight Hover Button – XAML Style implementation with code that is dynamic and skinnable.

By dsandor at July 06, 2010 04:52
Filed Under: WPF, Silverlight, Programming

So I needed to create a hover button.  The idea is that when the mouse rolls over the button the image will flip between a normal and ‘over’ version of the button image.  This is the same thing as old school image rollover code we have all used before.  There is an image that you use for a button in the ‘normal’ or ‘off’ state and when the mouse rolls over the image the picture changes to the ‘over’ or ‘on’ state.

It is pretty easy to do this statically.  Edit the button style, slap a couple of images in the ControlTemplate and tie that to the Normal and MouseOver visual states and you are done.

But what if you want to be able to use that same style for all your buttons and you want to be able to databind the Normal and MouseOver images?

This was pretty easy with a trick here or there.

First, we need to create a HoverButton class that inherits from the standard Button.  We need to do this because we need 2 new properties for our Normal and Over image url’s.

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
 
namespace MySLApplication.Local
{
    public class HoverButton : Button
    {
 
 
        public string NormalImageUrl
        {
            get { return (string)GetValue(NormalImageUrlProperty); }
            set { SetValue(NormalImageUrlProperty, value); }
        }
 
        public static readonly DependencyProperty NormalImageUrlProperty =
            DependencyProperty.Register("NormalImageUrl", typeof(string), typeof(HoverButton), 
            new PropertyMetadata(""));
 
 
 
        public string MouseOverImageUrl
        {
            get { return (string)GetValue(MouseOverImageUrlProperty); }
            set { SetValue(MouseOverImageUrlProperty, value); }
        }
 
        public static readonly DependencyProperty MouseOverImageUrlProperty =
            DependencyProperty.Register("MouseOverImageUrl", typeof(string), typeof(HoverButton), 
            new PropertyMetadata(""));
 
 
 
    }
}

This is the button you will place on your design surface instead of the regular button.  This one gives us NormalImageUrl and the MouseOverImageUrl.  These properties we will set to the URL for the images we want to use for our normal state and mouse over state.

Next is the Style (see the zip file at the bottom of this post for the actual code).  Since the Style is so big, I will describe the important pieces to you.

First, your XAML that contains this style code needs to have a namespace reference to the HoverButton’s namespace.  I named mine local so you will see my TargetType set to local:HoverButton.

xmlns:local="clr-namespace:MySLApplication.Local"

So the style starts out like this:

<Style x:Key="HoverButtonStyle" TargetType="local:HoverButton">
            <Setter Property="Background" Value="#FF1F3B53"/>
            <Setter Property="Foreground" Value="#FF000000"/>
            <Setter Property="Padding" Value="3"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Height" Value="36" />
            <Setter Property="Width" Value="118" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="local:HoverButton">
                        <Grid>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">

Note the TargetType in both instances is pointed to the local namespace and the HoverButton class name.  The real magic occurs in the ControlTemplate portion of the code.  Here there are several Visual States defined.  We are concered with two of them (feel free to extend this to the others also): Normal and MouseOver.

You will notice in each of the two Visual States we are concerned with there is a storyboard.  The StroryBoard executes when the visual state is entered.  So for example, when the button starts out it is in the Normal state.  When the control is rendered the Normal visual state causes the storyboard defined here to execute:

 

<VisualState x:Name="Normal">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" 
        Storyboard.TargetName="OverImage">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Collapsed</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" 
        Storyboard.TargetName="NormalImage">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

What happens here is that the StoryBoard sets the OverImage’s Visibility property to Collapsed and the NormalImage’s Visibility property to Visible. 

Before confusion sets in, scroll down to the bottom of the style.  You will see the two images we just discussed.

<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" 
   Content="{TemplateBinding Content}" 
   HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
   Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
<Image x:Name="NormalImage" DataContext="{TemplateBinding NormalImageUrl}" Source="{Binding}" />
<Image x:Name="OverImage" DataContext="{TemplateBinding MouseOverImageUrl}" Source="{Binding}" />

The two images defined inside the button’s visual surface are the actual images you will see at runtime.  Notice that we had to set the DataContext of the Image control to the property NormalImageUrl and MouseOverImageUrl and THEN set the Source property to {Binding}.  You need this little trick in order to allow databinding to convert the string based URL to an ImageSource.

So now we are good to go.  We can use our HoverButton like this:

<local:HoverButton Content="" Height="36" HorizontalAlignment="Left" 
    Margin="508,558,0,0" x:Name="btnSpin" VerticalAlignment="Top" Width="118" 
    Click="btnSpin_Click" Style="{StaticResource HoverButtonStyle}"
    NormalImageUrl="http://yourdomain.com/Normal.png"
    MouseOverImageUrl="http://yourdomain.com/Over.png"/>

So now you can specify the Normal and MouseOver images for your button.  The same style can be used for all these hover buttons, just specify the 2 images and you are set. 

 

Download File - HoverButtonSource

 

 

 

 

 

 

Solved: Cannot resolve TargetProperty (UIElement.RenderTransform).(CompositeTransform.TranslateY) on specified object.

By dsandor at July 04, 2010 05:02
Filed Under: Programming, Silverlight, WPF

I was using Blend 4 to do some simple animations then copy and pasting the storyboard for use on other objects in my application.  When I executed the Begin() method on the storyboard I would get the following:

Cannot resolve TargetProperty (UIElement.RenderTransform).(CompositeTransform.TranslateY) on specified object.

My XAML was pretty basic.  I finally noticed that Blend had populated the RenderTransform property for me on the working objects.  When I cut and pasted and updated the target object I failed to add the render transform.  Doing so fixes the problem:

Working:

<local:Tile ImageUrl="/SL;component/Images/02_100x100.png" Margin="0,200,0,0" Height="100"
 Width="100" VerticalAlignment="Top" x:Name="Tile_2"
 RenderTransformOrigin="0.5,0.5" >
   <local:Tile.RenderTransform>
        <CompositeTransform/>
   </local:Tile.RenderTransform>
</local:Tile>

Not working:

<local:Tile ImageUrl="/SL;component/Images/02_100x100.png" Margin="0,200,0,0" Height="100"
 Width="100" VerticalAlignment="Top" x:Name="Tile_2"
 RenderTransformOrigin="0.5,0.5" >
</local:Tile>
 

So if you get this message it is basically telling you that you are missing the RenderTransform property on the target object.

How To: Make a complex clipping path in Blend 4.

By dsandor at July 03, 2010 18:38
Filed Under: Silverlight, Programming, Expression Blend, WPF

This how-to will show you a few simple steps to making a clipping path in Blend 4.  Below is a mockup of my basic canvas (this is a PNG imported into Blend).  I want to make the green area visible and I want to clip the while rectangles out of the image.  Eventually, I will place some animated elements where the white rectangles are.

game-mockup

The first thing you want to do is to draw rectangles where you want the image to be visible.

image 

Now that I have all of my purple rectangles drawn out I am ready to convert them to a clipping path.

Remember, the rectangles are the areas that will be visible on the clipped object.

image

Choose the direct select tool: image and select all of your rectangles.  Hold down the CTRL key and you can multi-select.  You can also select the rectangles from the Objects and Timeline window.

image

Choose Object | Path | Convert to Path from the Blend menu.  This converts all your rectangles to a path which we will in turn convert to a clipping path.

image

Next, go back to Object | Path on the menu and choose Make Compound Path.  This will make one complex path from your individual paths.

image

Now that you have one compound path select the Path object from the Objects and Timelines window.  Now you can go back to Object | Path and you have the option to Make Clipping Path.

image

Now you choose the object to clip and you will now have a clipped object (an image in my case). 

image

Here is the end result in the Blend designer:

image

And here is the nice clean XAML you generated (please note, for space constraints I truncated the path data in the Clip property):

    <Grid x:Name="LayoutRoot" >
        <Image Margin="0" Source="Images/game-mockup.png" Stretch="Fill" 
         Clip="M0.5,0.5 L799.5,0.5 L799.5,202.5 L0.5,202.5 z M0.5,203.5 ... z">
        </Image>
    </Grid>

New certifications added to my Resume this week.

By dsandor at July 01, 2010 22:29
Filed Under: Programming, Blog

So I went in and took 5 of the 6 new beta exams (the 6th one was the TS Exam for Web, that one was full and could not take it for free) and I am happy to say I passed 5 of the 5 I took.  I just need to take the Web TS and I should add Web Developer 4 and Enterprise Developer 4 to the MCPD.

Now my Microsoft Certifications look like this:

519
Pro: Designing and Developing Web Applications Using Microsoft .NET Framework 4.0
Apr 09, 2010

518
Pro: Designing and Developing Windows Applications Using Microsoft .NET Framework 4.0
Apr 08, 2010

516
TS: Microsoft .NET Framework 4, Accessing Data with ADO.NET
Apr 07, 2010

513
TS: Microsoft .NET Framework 4, Windows Communication Foundation Development
Apr 06, 2010

511
TS: Microsoft .NET Framework 4, Windows Applications Development
Apr 05, 2010

MCPD(rgb)_1371MCTS(rgb)_1269_1374_1369_1373_514

MCSE(rgb)

 

MCPI(rgb)

MCPSB(rgb)

MockupToXaml codeplex project progression.

By dsandor at May 18, 2010 06:47
Filed Under: Programming, WPF

The UI for the converter kind of stinks right now because I have been concentrating on functionality.  I am now rendering XAML via plug-in modules.  In addition a preview of the rendered XAML is displayed after generating the XAML.

The UI is really basic right now:

image

Click the Load Mockup button to locate a .BMML mockup file.

image

The BMML document is parsed into a set of .NET objects.  For now, the controls are displayed in a grid.  This is going to be removed.  It was mainly used while coding the Mockup XML parsing logic.

image

Clicking generate will generate the XAML in the texbox at the bottom of the form.

image

In addition to generating the XAML, it is parsed at runtime and the Mockup is compiled at runtime and previewed.

image

That is the preview of the XAML rendered from my mockup below:

image

I still need to include the properties and sample data in the Xaml controls.  But for now, we have a start.

How To: WPF Databind a URL / URI to an Image control.

By dsandor at May 12, 2010 21:59
Filed Under: WPF, Programming, C#

The following code creates a UriToBitmapImage value converter.  Simply reference the converter in your databinding and you will be able to data bind an Image control to a URL and have it displayed on your WPF surface.

First, the value converter code:

namespace MyApp.Local
{
    public class UriToBitmapImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
             CultureInfo culture)
        {
            BitmapImage image = new BitmapImage();
            if (value != null)
            {
                try
                {
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    image.UriSource = new Uri((string)value, UriKind.Absolute);
                    image.EndInit();
                }
                catch
                {
                    image = null;
                }
            }

            return image;
        }

        public object ConvertBack(object value, Type targetType, object parameter, 
               CultureInfo culture)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}

Add the value converter to your project and compile.

Next, you need to reference the namespace that contains this new class on the WPF Window/Page/Control that you wish to use the converter. (You can also add your converters at the App level.)

xmlns:loc="clr-namespace:MyApp.Local"

I added the UriToBitmapImageConverter class to the MyApp.Local namespace.  Thus, I needed to add a reference to the CLR namespace in my XAML in order to use the converter.

Next, you need to add the converter to your XAML page’s resources:

   <Page.Resources>
        <loc:UriToBitmapImageConverter x:Key="UriToImageConverter" />
   </Page.Resources>

Here I used Page.Resources because I am adding this converter to a WPF Page.  It would be Window.Resources if you are working with a WPF Window or UserControl.Resources if you are adding this to a UserControl.

Now, simply data bind your image:

 

<Image Margin="8,7,4,8" 
      Source="{Binding ImageUri, Converter={StaticResource UriToImageConverter}}" 
      Stretch="Fill" d:IsHidden="False"/>

In the Source attribute I am data binding a URL / URI which is of type string.  This string is then passed through the UriToImageConverter and output is a BitmapImage object that downloads the image dynamically and displays it.

If I have some extra time, or requests, I will build a sample application to demonstrate.

My Fix: Unknown build error, 'Cannot resolve dependency to assembly…

By dsandor at February 03, 2010 18:19
Filed Under:

image

This work around did not work for me.  I have a solution with several projects.  One of them is a WPF application that uses a Telerik third party control for the DataGrid.  Yesterday everything worked fine and this morning I came in to work and I get the error:

Error    3    Unknown build error, 'Cannot resolve dependency to assembly 'Telerik.Windows.Controls, Version=2009.3.1314.35, Culture=neutral, PublicKeyToken=5803cfa389c90ce7' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event. Line 12 Position 10.'     D:\Projects\RFID\Source\RFID\Client\RFID.Client.UI\View\IdleView.xaml    12    10    RFID.Client.UI

No checkouts or get latest was performed.  Restarted VS2010 did not work. 

In my case the work around was to add the Telerik.Windows.Controls assembly to the project references manually.  This should have been done by the drag/drop of the Telerik control to the design surface but it did not.  Other issues were reported on connect.microsoft.com explaining that assemblies with a 2nd degree of separation which are not normally required to be directly referenced are now needed in VS2010 for whatever reason.

Silverlight – How do I add an icon to a button control.

By dsandor at November 06, 2009 22:13
Filed Under:

This is really easy, hopefully this helps some newbies.

image

I have a button with the text Add User in the ‘Content’ property.  XAML is cool because you can make the content anything you want, including other controls or groups of controls.

I start by changing my XAML to break out the content property:

1) Remove the Content="Add User" from the Button tag.

2) Break out the content property like this:

<Button Margin="10,5,10,5">
    <Button.Content></Button.Content>
</Button>

3) Add a stack panel inside the Content property and add an image control and a textblock control:

                   <Button Margin="10,5,10,5">
                        <Button.Content>
                            <StackPanel Orientation="Horizontal">
                                <Image Height="16" />
                                <TextBlock>Add User</TextBlock>
                            </StackPanel>
                        </Button.Content>
                    </Button>

4) Now you need to add an image resource to your Silverlight application.

5) Reference the new image in the Source attribute of your Image control inside the Content property of your Button control and you now have an image and text inside your button.

                   <Button Margin="10,5,10,5">
                        <Button.Content>
                            <StackPanel Orientation="Horizontal">
                                <Image Height="16" Source="Images/user_add.png" />
                                <TextBlock Margin="5,0,0,0">Add User</TextBlock>
                            </StackPanel>
                        </Button.Content>
                    </Button>

image

That’s all there is to it.  You can add pretty much anything inside the Content property.

WPF: Cannot create instance of 'MainWindow' defined in assembly…

By dsandor at November 04, 2009 05:21
Filed Under:

Back on a WPF project for a day and received this while wiring up a ViewModel to the main WPF form. 

image

As with most XAML errors the problem is related to something else deeper in the code.  The inner .. inner exception shows the problem.  An XML data file is being deserialized and the file does not exist. 

So if you get a wierd error like this you probably have some bad code in a constructor for the View’s class or your ViewModel.

Breakpoint the View’s class declaration right before initialize component or at the constructor of your ViewModel class.

image