Slight imrpovement in CanWriteProperty

Slight imrpovement in CanWriteProperty

Old forum URL: forums.lhotka.net/forums/t/5140.aspx


triplea posted on Wednesday, July 23, 2008

I know this has been untouched for a long while but the possibility of a slight improvement occured to me today.
Assume a BO with a property MyProperty of type string. The setter would look like this:

set
{
   CanWriteProperty(
"MyProperty", true);
   if (value == null) value = string.Empty;
   if (_myProperty != value)
   {
       _myProperty = value;
       PropertyHasChanged(
"MyProperty");
   }
}

We have a form that has a textbox bound to that property and the form contains a readWriteAuthorization control. Assume that the current user (me) cannot edit that property so CanWriteProperty returns false so readWriteAuthorization sets my textbox as readonly. If i place the cursor in that (readonly) textbox and tab out of it without making any changes, the setter will throw a security exception and my cursor is forever stuck in the textbox, silently throwing the security exceptions on my output window but no other visible cueues to the user (who wouldn't be able to do anything anyway).
If I change CanWriteProperty so that an exception is not thrown then the code will continue check that the value is not null (if its a string like in the example above), no changes would have been made and will exit. But this doesnt seem right. Wouldn't it be better to do the following:

set
{
  
if (value == null) value = string.Empty;
  
if (CanWriteProperty("MyProperty", false) && (_myProperty != value))
   {
      _myProperty =
value;
      PropertyHasChanged(
"MyProperty");
   }
}

The error would be thrown should the flag be true whereas if its false then you dont run into issues changing a value you shouldnt if you forget to set the textbox to read only (e.g. via readWriteAuthorization).
All this in 3.0.4, not sure how this is handled within 3.5, will have to check that later but it might be relevant.

RockfordLhotka replied on Thursday, July 24, 2008

Added to my list of things to research.

justncase80 replied on Thursday, August 14, 2008

I noticed this exact same issue when binding to a property you don't have authorization to write to in Silverlight. I didn't consider not throwing an exception in the setter however... The solution I came up with was more like this:

set
{
  
if (value == null) value = string.Empty;
  
if (_myProperty != value && CanWriteProperty("MyProperty", true))
   {
      _myProperty =
value;
      PropertyHasChanged(
"MyProperty");
   }
}


Which will still throw the exception if you're not authorized to set the value but it won't bother to do anything if the values are exactly the same still.

Copyright (c) Marimer LLC