Insidious ByRef Legacy Code Issue

April 24, 2012

The ByRef in the title should give you a hint that this is about legacy VB.NET code.

One of my duties at my new job is to maintain our legacy VB.NET codebase until we deploy our WPF software. When I use the term legacy it should not be taken in a negative manner. Our legacy code runs our company everyday and does it very well.

If you don’t know, VB.NET has a powerful but insidious property on Microsoft.VisualBasic.DateAndTime module called Today. Well, this little beast is a read-write property to the system date.

Yesterday I got a report of an exception that we have never seen before, System.Security.SecurityException; user does not have permission to change the system date.

Over the last few weeks we have been moving from Windows XP to Windows 7 with UAC set at the Default level (as it should be.) We are running in a different, more secure computing environment. The user that reported the issue was upgraded yesterday morning.

After researching the problem it turns out that we had several method calls within our legacy application that were passing Today ByRef. Yes, you guessed it; this caused a call to update the system date each time these methods were executed and returned. In reality no real damage was done; however under Windows 7 with UAC turned on, it caused the above security exception.

Solution

I found every instance of Today in the code and changed it to, Date.Today which is the read-only syntax.  You can also use Today.Date.

If you are maintaining legacy code that you didn’t write and have an unexplained issue, looking at method calls that are passed ByRef might help. 

If you have Today in your VB.NET code, take a look and make sure it’s not being passed ByRef and make sure you code is not mutating it.

Have a great day,

Just a grain of sand on the worlds beaches.


Glimpse for Silverlight – Viewing Exceptions and Binding Errors

June 8, 2009

GlimpseOnLoad

Introduction

After my previous blog post, “Troubleshoot Silverlight 3 Data Bindings” I got some feedback and while in Phoenix I upgraded the code and have decided to call this Glimpse.

This initial release of Glimpse is a proof of concept project.  As I spend more time working with Silverlight 3, I’ll add more instrumentation views (Mole for Silverlight anyone?)

What is cool about Glimpse is that it can be used for local debug or deployed release builds.  It takes a single line of code to crank it up.

BTW:  I have not had a chance to make the UI pretty in Blend yet.  So go easy on Karl’s Moletones UI.

Glimpse Viewer Control

The Glimpse Viewer Control is hosted inside a Floatable WindowTim Heuer has a great post on how he modifed the default Silverlight ChildWindow so that it can be modal or non-modal.

I took Tim’s implementation and added the ability to set the location of the Floatable Window.  My code is in the Download section below.

Launching Glimpse

GlimpseLaunching

Glimpse is launched with a single line of code, passing the Application object and a string name for the Silverlight control.  If you have more that one Silverlight control on a web page, the name helps to know what control that Glimpse is providing information for.

In the above code, I’m testing if the current build is a DEBUG build. If so, launch Glimpse.  In your applications you can use other techniques for determining if Glimpse should be launched.

If your MainPage object throws an exception during object construction, Glimpse will display an Exception Viewer that will show you the exception and any inner exceptions.

To demonstrate this feature, you can uncomment the code in the MainPage constructor and then run the demo application.

GlimpseObjectConstructionException

Load Exception Viewer

The above code has outer and inner exceptions.  This viewer will display the outer exception and all nested inner exceptions.

GlimpseExceptionViewer

Application Unhandled Exceptions

When your Silverlight application has an application unhandled exception, the Glimpse Viewer Control will display a red ellipse on the right with a number indicating the number of unhandled exceptions.

  • Click the Expand button to display the Glimpse Viewer information
  • To return to contracted mode, click the Contract button
  • To clear the list of exceptions, click the Clear Exceptions button

GlimpseControlUnhandledExceptionNotification

GlimpseUnhandledException

Data Binding Exceptions

When your Silverlight application has an binding validation exception, the Glimpse Viewer Control will display a red ellipse on the left with a number indicating the number of exceptions.

In the below image, the Birthday field has text that can’t be converted into a date.

GlimpseDataBindingException

Pressing the Expand button displays the data binding validation exception.  This will also show any inner exceptions if they are present.

Notice the (Added) text on the left and field on the right.  This is the ValidationErrorEventAction property for the ValidationError.  When the validation error is cleared, the text will display “(Removed)”.

GlimpseDataBindingExceptionDetial

Bindings with no Source

The below image shows the Path with a typo, an “x” has been added to the correct property name “FirstName”.  This will cause a binding failure.

GlimpseNoBindingXAML

The below viewer provide information on all broken bindings in the host Silverlight control.  Binding errors are resolved each time the “Bindings with no Source” tab is selected.

GlimpseNoBindings

From Here

I have two projects that I want to launch on my blog, then I’ll take any feedback and add more views to the Glimpse Viewer Control.

What is nice about this approach is that you can launch Glimpse on a deployed production Silverlight control that needs some debugging love on a remote server in addition to using it during Silverlight control development.

Downloads

After downloading the below project, you must change the file extension from .doc to .zip, this is a requirement of WordPress.com.

Glimpse Control and Demo Project (61KB)

Karl’s Floatable Window  (22KB)

Have a great day,

Just a grain of sand on the worlds beaches.


Troubleshooting Silverlight 3 Broken Bindings

June 3, 2009

This post has been replaced by a much better approach.

Please view Glimpse for Silverlight – Viewing Exceptions and Binding Errors

Have a great day,

Just a grain of sand on the worlds beaches.


Updated: Input Validation – UI Exceptions & Model Validation Errors

December 29, 2008

I have completely rewritten the Input Validation – UI Exceptions & Model Validation Errors example code and post.

While in NY City with my great friend and MVVM Master Josh Smith we spoke a lot about the MVVM layers and when it is appropriate to put code in the View code behind file.

Since the Validation.ErrorEvent is a UI RoutedEvent it makes sense to handle this event in the View code behind and for this code to call directly to the ViewModel.

The resulting code is much simpler.  I had also added a Sequence Diagram to make understanding the data binding pipeline easier when a UI Control attempts to set a value on the Model it’s bound to and their is a type mismatch.

I hope you like and can learn more about WPF  and MVVM from this article and sample code.

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.


Fort Knox Business Objects ( yes / no )

April 20, 2008

I’ve spent the last week at the Microsoft 2008 MVP Summit.  It was a fantastic learning and sharing experience.  Microsoft took excellent care of us the entire week.  Spending time with other MVP’s and meeting my friends from all over the globe was priceless.

I also spent a good deal of time out of the classroom with members from four different teams.  It was during these times that we had some very healthy,  animated discussions on topics that we are both passionate about.  In the end, we shook hands and parted with deep respect looking forward to our next discussion.

I don’t know about the readers of my blog, but I like passionate discussions.  I like to listen to other developers explain their approaches to problem solving and their solutions.  After the flamethrowers are put back in the armory, I then like time to think about why the other side was presenting their point of view.  Many times the “why” never comes out in the dialog.  That developers life experience normally does not get presented as part of a discussion on the .NET Framework.  So I like to marinade on the facts and work backwards to try to get inside the other persons world to understand why they want to adopt this solution.  This is known as inductive study.  By asking questions of the facts presented, you can many times determine context and then come to an understanding or appreciation of the process that lead to their solution.

The Scenario

I spent several hours talking about the concept of business objects throwing exceptions in the property setters if the value did not pass the validation rules for that property.  If you have read my latest article, WPF Business Application Series Part Three you know that I strongly favor using the IDataErrorInfo interface for business object validation broken rule notification as opposed to throwing exceptions from property setters.

I thought long and hard about the discussions and came to this conclusion, you either favor the Fort Knox or Shopping Cart approach to business object validation.  One is a controlling paradigm the other a trusting relationship.  One takes a very granular approach the other a holistic approach to business object validation.

In discussions, business object validation is normally centered around UI binding scenarios.  This is only one scenario and I would strongly argue that more validation takes place in the business layer processing of objects than direct UI binding.  So proponents of throwing exceptions as a form of broken validation rule notification, must take a step back and look at this notificaiton business from a much higher perspective than just a UI binding scenario.

I realize that there are two schools of thought here.  One states, an object should never be in a invalid state.  The other, allows for temporary broken rules, but verifies object state prior to any actual use of the invalid object.  This notion of absolute control or pure objects is an illusion that does not play well with real world business objects and today’s computer users.  Of course application scope and requirements must dictate how and when business rules are enforced.  As an architect I don’t want the platform to force me to write objects in a certain way just to utilize it, especially when there is no payback and only complicates development and code maintenance.  Framework developers are not responsible for my data, me and my developers are.

WPF is one example of permitting developers to choose a broken validation rule notification technique that suits their application.  It allows developers to use exceptions or IDataErrorInfo for broken validation rule notification to the class binding to it.

Fort Knox Shopping Cart
fort-knox ethical_shopping_cart-vob
  • Throws exceptions when a validation rule is violated in a property setter.  Guards each property setter with a machine gun, sounding general quarters any time a value does not pass all the rules. 
  • The Fort Knox approach to shopping, would have the store manager walking with you.  Each time you add an item to the cart, the manager would be running your credit card and possibly forcing you to submit to a polygraph.  Your every movement would be recorded on video and watched real time by a security guard, waiting like a cat ready to pounce on its prey at the first sign of weakness.
  • This approach makes validation rules that are dependent on two or more properties, very difficult to implement since the order that the property must be set can now become a factor when trying to avoid an exception being thrown.
  • Follows a passive validation model that maintains a listing of each broken rule in the object and provides a means to query an individual property or the entire object for its validation status.   
  • The Shopping Cart approach to object validation allows the user to shop the store, place items in the cart and then check out.  In the above example the shopper can get feedback on items and their total as they shop, but are not prevented from adding the item to the cart.
  • This approach only cares about the checkout process and not the act of placing an item in the cart as opposed to the Fort Knox approach that won’t let you place a second item in the cart until the first item is paid for. 

Fort Knox Business Layer Problem

The Fort Knox approach can kill business layer code like LINQ queries that attempt to populate that object and the data is invalid for one reason or another.  I’ll use two examples to illustrate this problem.

If you have validation rules that are dependent on one or more property values, developers will now have to write code to set property values in a certain order to avoid an exception being thrown.  This is a crazy requirement and is contrary all .NET class design documentation.  Can you imaging having to wrap EVERY piece of code that sets a property with a try catch block.  Again, what about LINQ queries that are tying to populate objects and unnecessary exceptions are being thrown by property setters.  This makes writing maintainable code MUCH harder and with ZERO payback.  When code is changed over time, a field added, we have to factor in usless exception handling and be cognasent of the order in which property setters are called or change.

I was speaking to one of the team PM’s on Friday.  When I asked him about a certain issue his response was, “stuff happens.”  I agree with him, stuff does happen.  The Fort Knox approach does not allow for (actually tries to prevent) temporary invalid object state.  This all comes full circle to the Fort Knox developers that some how get this false sense of security from exceptions being thrown, as opposed to developers checking an object’s Error property or other properties that expose object state and collections of broken validation rules.  Any developer can read and learn this programming pattern from Rockford Lhotka’s CSLA, Microsoft’s Validation Application Block or Karl Shifflett’s Lightweight Business Object Declarative Programming.

Using the Fort Knox approach does not guarentee a valid object either.  The developer could go through the pains of catching exceptions, but the object is still invalid if it does not pass all the validation rules.

In reality both approaches do allow for tracking broken rules since the developer is free to write any code in each setter and then throw the required exception.  My biggest problem is having to code around what should be a reporting problem.  However, this still means that all business layer processing code would have to be on the look out for a broken validation rule exception each time a setter was accessed as opposed to business layer code checking the object validation state as a whole, prior to persisting or moving an object to another tier.

Close

I welcome your feedback on this topic.  Please comment on your approach to business object broken validation rule notification.  Good discussions lead to better programming techniques and educate all who participate.

Have a great day!

Just a grain of sand on the worlds beaches.


WARNING: After Installing The New Framework 3.5 SDK, my VS2008 XAML Intellisense No Longer Works – UPDATED

February 14, 2008

Warning – Work Around

Microsoft has released a workaround for this at:  http://blogs.msdn.com/windowssdk/comments/7850578.aspx

Problem 

I updated my work computer and both my desktop and laptop at home with the new Framework 3.5 SDK.  Now XAML Intellisense no longer works  in Visual Studio 2008.

I have been working with the Microsoft SDK Team for the last 5 hours.  They have logged a bug report and are currently building a clean test machine so that they can troubleshoot this issue.

I spent the last hour on the phone with the Team and want to post the following information at their approval:

  • If you have not installed the new Framework 3.5 SDK on VS2008, do not install it yet.  Give Microsoft time to sort this out.
  • If you have installed the new 3.5 SDK on VS2008 and your XAML Intellisense is broken, you can run the Visual Studio 2008 Repair function and this will correct the problem.
    • Please note.  I’m not sure how this will affect your system in the long run.  Microsoft is working on the problem and will release their findings.

Please note:  I did try removing the new 3.5 SDK from my home desktop system, but this did not fix the problem.  I must now run the Visual Studio 2008 Repair to get the XAML Intellisense back. 

 Just a grain of sand on the worlds beaches.


Follow

Get every new post delivered to your Inbox.

Join 167 other followers