d:DesignInstance, d:DesignData in Visual Studio 2010 Beta2

October 28, 2009

The WPF and Silverlight Designer for Visual Studio 2010 shares several new design time (d:) properties and design time MarkupExtensions with Expression Blend 3 that provide necessary information for the WPF and Silverlight Designer to deliver a great editing experience.

I have explained the d:DesignData MarkupExtension in detail in this blog post:  Visual Studio 2010 Beta2 Sample Data Project Templates.

In this post I’ll cover the d:DataContext property and the d:DesignInstance MarkupExtension.

d:DataContext

d:DataContext gives developers the ability to set a design time d:DataContext that is separate and independent of the run-time DataContext property.

This feature solves the problem of developers wanting to set their DataContext programmatically but also wanting design time data.

All d: properties are ignored during compilation and are not part of any run-time assemblies.

d:DesignInstance

Purpose:  Provides a design time shape to the d:DataContext its applied to.

Example:  In the below snippet the Person class is the shape provided by d:DesignInstance to the Grid’s d:DataContext.

<Grid d:DataContext="{d:DesignInstance local:Person}">

Note: In the above example, the Person class is actually a faux type (fake or substitute type).  This faux type enables types that are not creatable to be created and their properties exposed as a shape.  See the below section on creating creatable types.

Usage:  So, now that the d:DataContext has shape, what can I do with it?

The shape is used by the new Binding Builder to expose the properties of the type in d:DataContext.  You can see in the below image, the four properties exposed by the Person class.

BindingBuilder

The Binding Builder is opened by clicking or right clicking on the Property Marker in the Properties Window.  The Property Marker is the icon to the right of the property name.  The Binding Builder is a GUI for editing bindings in WPF and Silverlight.  This is a super feature

The Cider Team has a great explanation of the new features on WindowsClient.net that you can read here: Setting Up Visual Studio for WPF and Silverlight Development.  There is an article and video.

You can read additional Cider Team Online material here:  WPF and Silverlight Designer for Visual Studio 2010.  We are in the process of adding many more articles.  While the material is initially geared for developers coming from other platforms to WPF or Silverlight, it has a lot of great information even for the seasoned XAML Head.  Yea, I said it.  I’m a XAML Head too and proud of it.  (LOL)

Without d:DesignInstance, d:DesignData or d:Source applied to a CollectionViewSource the Binding Builder would have no way to determine shape and provide a list of properties.

Note:  If d:DataContext is not set, but DataContext is set and has a created type assigned to it, this will also supply shape that the Binding Builder can use for listing properties.

Creating Creatable Types

 <Grid d:DataContext="{d:DesignInstance local:Person, IsDesignTimeCreatable=True}">

d:DesignInstance provides a technique for creating a non-faux type.  Setting the property IsDesignTimeCreatable to True on the d:DesignInstance MarkupExtension enables this.

Links

MSDN d:DesignInstance Walkthrough

Video showing d:DesignData and d:DesignInstance can be viewed from this blog post:  Visual Studio 2010 Beta2 Sample Data Project Templates.

The above post also has source code for sample data templates.  There four of the templates are tutorial walkthroughs on this topic and sample data.

The two .xaml files in the DesignInstance Samples folder are the walkthroughs.  You can create this project in VB.NET or C# by using one of the below templates when creating your project.

  • VB WPF Application DesignData Sample – VB.NET Sample WPF Application that demonstrates consuming sample data.
  • CS WPF Application DesignData Sample – C# Sample WPF Application that demonstrates consuming sample data.

DesignInstanceExamples

Close

Hope you find d:DesignInstance and d:DesignData Sample Data in Visual Studio 2010 Beta2 a productive feature for your application development.

Have a great day,

Just a grain of sand on the worlds beaches.


How to watch Sunday Night Football Full Screen with two or more Monitors

September 20, 2009

If you have more than one monitor, keep reading.

When you open Sunday Night Football to view using the new Silverlight player, go full screen and then start using your other monitor to work, Silverlight immediately goes back to the smaller size.  Bummer.

It’s actually a security feature, which is good.

Workaround

1.  Open Sunday Night Football on your second monitor.

2.  Press CTRL + N.  This will open a new browser window that you can do what you want size wise.

3.  Close the original browser.

4.  Now use your browser zoom feature and zoom the screen the way you want.  The scrollbar allows you to position the screen as desired.

Have a great day,

Just a grain of sand on the worlds beaches.


Updated – INotifyPropertyChanged – How to remove the Property Name String Code Smell

August 2, 2009

Note: I updated this blog entry because the first method ran into problem with StackFrames in release builds without .pbd files.  I did find a JIT Compiler workaround but would never suggest such a hack.

I have so much to share with you since my last blog entry. 

Went on a cruise to Alaska to write BBQ Shack and Ocean v2 Code Name: Glacier.  Only got off the ship once because I was having way too much fun programming!  OK, I need an intervention, let’s move past the cruise bit.  Looking to go out again in September, need another week with whales, glaciers, seals, bald eagles, room service and my computer.

BBQ Shack is an end to end WPF & Silverlight Line of Business application that I’ll be using for a few months to write many Code Project articles and create tutorial videos.  The new Ocean API feature set is insane!

Since I got back from the cruise, I have been pair programing with Rock Stars Rob Zelt, Laurent Bugnion, Josh Smith and Glenn Block.  There is nothing like pair programming.  If you have not tried this, schedule it today and get your “Geek-On.”

BBQ Shack is almost ready for release but I felt the need to take a day and do what I did on the cruise.  Think, think, dream, think and question everything.  Be willing to look critically at my code, motivations, assumptions and the horizon.

So kdawg02  (my Twitter call sign), what did you do Saturday and 1/2 of Sunday that prompted you to fire off a blog post?

One item I’ve been hearing about is the Code Smell of having to put property names in the call to the method that raises the property changed event for Model and ViewModel classes.

Typical de facto Standard WPF or Silverlight Property

''' <summary>
''' No ma, that's not my dirty socks, its my setter stinking up the code again.
''' </summary>
Public Property TestMeString() As String
    Get
        Return _strTestMeString
    End Get
    Set(ByVal Value As String)
        _strTestMeString = Value
        OnPropertyChanged("TestMeString")
    End Set
End Property

Developers have long not like having quoted strings in their code.  Some would agree this practice is a bonafided Code Smell. 

I have not minded this smell because I always generate my entity classes so I never really cared.  If a property needs to change for some reason, I just regenerate my entity code.

One easy solution I’ve considered is to define a private constant for each property name and then simply use the constant.  More work, but does make the code cleaner.

But What if You Could Write Properties Like This?

''' <summary>
''' Look Ma, no code smell in my setter!
''' </summary>
Public Property TestMeGetCurrentMethodName() As String
    Get
        Return _strTestMeGetCurrentMethodName
    End Get
    Set(ByVal Value As String)
        _strTestMeGetCurrentMethodName = Value
        OnPropertyChanged(MethodBase.GetCurrentMethod.Name.Remove(0, 4))
    End Set
End Property

Well, you can!

The System.Reflection.MethodBase.GetCurrentMethod call gives us access to a wealth of information at runtime, including the name of the currently running method.  In our case the property setter.

The name of this property setter is, “set_TestMeGetCurrentMethodName.”  So by removing the first four characters the current property name is passed to the base classes OnPropertyChanged event handler.

Kind of anti-climatic isn’t it…

What is Performance Hit?

Below are 11 runs each doing 100 more iterations than the previous run.

The first result is the OnPropertyChanged(“TestMeString”) method.

The second result is the OnPropertyChanged(MethodBase.GetCurrentMethod.Name.Remove(0,4)) method.

The run is a release build, without any .pdb files, running from the command line.  I added some string manipulation code in the PropertyChangedEvent handler to simulate actual real world code that actually does some processing in the event handler.

When looking at the results the double quoted string method runs faster. 

But, do you really care about .4 milliseconds on 100 property changed events as in the second iteration?  Most WPF and Silverlight applications I’ve seen only raise one or two property changed events at a time. 

Note: If you have an application that has 100’s of events per second or more like real-time graphing applicaitons, I would not use this method for performance reasons.  Instead, go with string constants for the property names or double quoted strings if you like that better.

ReleaseModeCodeUpdated 

Where Are We

Want to thank the WPF Disciples who commented heavily and showed me holes in my first attempt.

I did receive a comment from Tamir Khason that he categorized as a gut feeling rather than known fact but am including it here for completeness, “There could be issues with reliability of reflection for production environment where assemblies can be obfuscated, delayed signed etc.”  Thanks for the heads up Tamir!

I’ve re-posted this blog entry to gain developer interest in finding a solid solution to this “Code Smell” issue without any external dependencies or Dependency Properties.

Other Solutions

Daniel Vaughan’s

Jonas Follesoe’s

Mike Brown’s

Neil Mosafi’s  (Be sure to read the comments on this blog post)

Peter O’Hanlon would like to see

public string Name

{

  get; [Notify]set;

}

Download

After downloading you must change the file extension from .doc to .zip.  This is a requirement of WordPress.com

Source Code (51KB)

Have a great day,

Just a grain of sand on the worlds beaches.


Searching Your Source Code – Getting Results From Vista File Indexing

January 25, 2009

About a week ago I needed to search all my source code to find a value contained within one or more files.  The search never returned any results.  So it was either turn the thing off or figure out the problem.

I feel like the last guy to figure out how to get the most from the Vista File Indexing feature, but just in case you don’t know about this, here we go.

Desired Result

Want to be able to enter a search string in the Windows Explorer Search Box and have it list all my code files that contain that search string.

Steps

  • Open Control Panel
  • Click on Indexing Options
    • You can modify file locations if desired.  I’m using the default as it works for me.
  • Click on the Advanced button
  • Click on the File Types tab
    • (continued below …)

IndexingOptions

Important Step

Below the dialog displays a list of file types on your system and how the Indexer indexes that file type.  You can also add any missing file extensions.

You’ll notice that for each file type you can select to index just the file properties or the file properties and the content.

Notice that I’ve changed the indexing behavior for my .vb files so that the content is indexed along with the file properties.  How simple is this?

I also have changed the .xaml and .cs files to index like the .vb files.

Now I have instant access to all my source code content.

IndexingAdvancedOptions

At your option you can now switch back to the Index Settings tab and press the Rebuild button to have you’re source code indexed immediately.

Have a great day!

Just a grain of sand on the worlds beaches.


WPF Sample Series – Using WPF Binding StringFormat Property with Nullable Types

December 16, 2008

One of the great features introduced in .NET 3.5 Framework Service Pack 1 is the BindingBase StringFormat property.  When used in a data binding expression the StringFormat property replaces most IValuteConverters that were used for formatting of values in  WPF 3.0 & WPF 3.5 applications.

Here are two examples of the StringFormat property in action formatting a currency field:

<TextBox Text="{Binding Path=Salary, StringFormat=c}" />

<TextBox Text="{Binding Path=Salary, StringFormat=\{0:c\}}" />

Nullable Type in the Mix

If you are binding to a non-Nullable data type the above will work just fine.

However, if you are binding to a Nullable data type the above will not work.

This breaks down when a UI Control like a TextBox as a value and the user clears the TextBox and press TAB.  The default implementation of StringFormat will attempt to set the Target Property to an empty string which in the the case of a Nullable Decimal property will cause the following or similar data binding exception.  The below data binding exception can be viewed in the Visual Studio Output window.

Exception
 

System.Windows.Data Error: 7 : ConvertBack cannot convert value ” (type ‘String’). BindingExpression:Path=Age; DataItem=’Customer’ (HashCode=31884011); target element is ‘TextBox’ (Name=”); target property is ‘Text’ (type ‘String’) FormatException:’System.FormatException: Input string was not in a correct format.

at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)

at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

at System.String.System.IConvertible.ToInt32(IFormatProvider provider)

at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)

at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)

at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)’

TargetNullVaue to the Rescue

In the above example, the exception is thrown because of a type mismatch.  In WPF 3.0 and 3.5 I had a set of Nullable ValueConverters for my applications to handle this problem.

Another great feature introduced in .NET 3.5 Framework Service Pack 1 is the BindingBase TargetNullValue property.  This property can be used to handled the type mismatch problem when converting an empty string from a TextBox to Nothing (null) when the binding pipeline sets the target Nullable property.

Let’s have a look at the two below TextBoxes.

<TextBox
    Grid.Column="1"
    Grid.Row="1"
    Margin="0,11,11,11"
    VerticalAlignment="Top"
    Text="{Binding Path=NumberOfComputers,
            TargetNullValue={x:Static sys:String.Empty},
            StringFormat=\{0:D\}}" />

<TextBox
    Grid.Column="1"
    Grid.Row="2"
    Margin="0,11,11,11"
    VerticalAlignment="Top"
    Text="{Binding Path=Age, StringFormat=\{0:D\}}" />

These TextBoxes are both bound to Nullable properties.  The first TextBox takes advantage of the TargetNullValue property and works as expected.  The second does not.   The data binding pipeline will throw an exception when the second TextBox is changed to an empty string and it attempts to assign the value of String.Empty to the Target property.

Here is a potential problem.  If the exception gets thrown and swallowed because the code didn’t check for this, the user thinks they cleared a value but the property the TextBox is bound to never gets changed due to the exception being thrown.

Download

I’ve included a very simple project that you can download a play with.

After downloading the project, please change the extension from .doc to .zip.  This is a requirement of WordPress.com.

Download Sample Project (76KB)

Steps To Reproduce Issue

Launch included program using debug mode.

Ensure Visual Studio Output window is visible.

Set each TextBox to 7.

Go to first TextBox.  Clear field and press TAB.  Notice nothing is added to the Output window.

Go to second TextBox.  Clear field and press TAB.  Notice nothing an exception is added to the Output window.

Close

When binding to Nullable types, use the TargetNullValue property along with the StringFormat property to avoid type mismatch exceptions.

Hope this tip has helped you learn more about WPF!

Have a great day!

Just a grain of sand on the worlds beaches.


Support our Marines Overseas

November 2, 2008

marinesega

Many of you know I served in the Marine Corps after graduating from high school.  The training and experience of the Corps molded me for life.  I was blessed to have seen so much while in.  From carrying a rifle though the jungles in the Pacific to crewing a KC-130 on flights around the globe to molding Marine Recruits on the grinder at MCRD Parris Island, South Carolina.

The Marine Corps is an environment, a lifestyle where words like honor, commitment, loyalty, dedication, courage and faithfulness are core values that are lived out each day.  I love the Corps and miss it everyday.

Today I received an email from a retired Marine friend of mine, Gene Hetzel.  He passed along some information on supporting our Marines overseas this Christmas.

I emailed the unit Chaplain, Lt. Cullen and he sent me the following letter I want to share with you.

How to Support our Marines

Greetings from Iraq! We are the men of 1st Reconnaissance Battalion, United States Marines Corps. As we draw near to the holiday season, we are seeking support once again for our Marines and Sailors. As you can imagine, the holidays are difficult times to be away from family members. Our supporters play a big role in keeping the men’s morale high and impacting the effectiveness of the greater mission. Movies, Greeting Cards for the Marines and Sailors to send home, though seemingly insignificant, have a great affect on morale.

Below, please find a list of recommended items, but by no means consider this list exhaustive. We also included our Battalion’s web site. Visit the site regularly to stay abreast of things happening with 1st Recon.

Thank you for your support, thoughts, and prayers. We are very mindful of you and all that you do for the Marines and Sailors of 1st Reconnaissance Battalion.

Web Site: http://www.i-mef.usmc.mil/div/1reconbn/default.asp

Care Package Mailing Address:

LT DAVID J. CULLEN

1st RECON BN H&S CO

UNIT 40535

FPO AP 96426-0535

Suggested Care Items

  • Packets of sugar
  • Packets of creamer
  • Chocolate powder
  • Oatmeal
  • Beef jerky
  • Sunflower seeds
  • Protein bars
  • Hand warmers
  • Trial size deodorant
  • Socks
  • Phone cards 
  • DVD movies 
  • Toothbrushes
  • Toothpaste
  • Chap sticks
  • Greeting cards 
  • Travel size lotion
  • Baby wipes

Close

Thank you for your support of our Marines overseas.  As I was writing this the following verse came to mind:

Cast thy bread upon the waters: for thou shalt find it after many days. — Ecclesiastes 11: 1 (KJV)

Have a great day,

Just a grain of sand on the worlds beaches.


WPF CheckListBox – Two Versions XAML Only & Custom Control

November 1, 2008

Article and Code

Read the WPF CheckListBox article here

Background

In October of 2007 I wrote an article on Code Project entitled, A WPF Problem Solved Two Very Different Ways – Using XAML Only – Using A Custom Control.

I was at work yesterday and was replying to a forum post requesting information on a WPF CheckListBox.  I actually had trouble finding my article on my blog.  After finding it, I realize the title I selected was not a good “long term” blog post title.

At the time I was showing off the power of WPF and created two solutions to a problem Josh Smith was writing about in his article, The WPF Thought Process.

However, a year goes by, the title no longer makes sense and does not aid search engines in returning my article or blog post that is REALLY about WPF CheckListBoxes!

Moral of the Story

Name blog posts with titles that a year later will enable Internet users to find your awesome content.

So, this is a repeat blog post with the correct title to help others find the poorly named article.

Have a great day,

Just a grain of sand on the worlds beaches.

 


Follow

Get every new post delivered to your Inbox.

Join 245 other followers