.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

PropertyOf and INotifyPropertyChanged.PropertyChanged without strings

Posted By: Fabrice Marguerie     Posted Date: August 30, 2010    Points: 0   Category :ASP.Net
When coding applications using design patterns such as MVP (Model-View-Presenter) or MVVM (Model-View-ViewModel), you'll find yourself using data binding and the INotifyPropertyChanged interface all over the place. This means referencing properties quite a lot. For example, when you want to notify that the value of a property has changed, you can write NotifyPropertyChange("SomeProperty") where NotifyPropertyChange is a method that invokes the INotifyPropertyChanged.PropertyChanged event. The major inconvenience of using a string to reference a property name, as in NotifyPropertyChange("SomeProperty"), is that it's a very brittle approach. If the name of the property changes or the property is removed during some refactoring operation on the source code, then it's easy to forget to update all the "string references". Luckily, solutions exist to avoid this kind of issues. infoof => PropertyOf, FieldOf, MethodOf, ConstructorOf We don't have propertyof or infoof operators in C# (see 1, 2, 3 or 4), but we can use things such as PropertyOf thanks to expression trees. You can learn more about such an approach on the C# FAQ blog and Patrick Smacchia's blog. Here is the source code, derived from the above articles, that I use in a utility class: Snippet public static MethodInfo MethodOf<T>(Expression<Func<T>> expression){  var&

View Complete Post

More Related Resource Links

How to check for null/empty strings on dynamic objects?


What is the proper way to check for null or empty strings on dynamic objects? This is the only solution I've found so far:

if (admin.PasswordHash.GetType() == typeof(DBNull) || admin.PasswordHash == string.Empty)

If the field is null, the object returned is DBNull.Value, but if the field is empty string, it's return as a System.String object. This makes it impossible to do regular "admin.PasswordHash == DBNull.Value" check, as that will fail whenever the field has been set to empty string. Is my example the right (and only) way to go?

Protect It: Safeguard Database Connection Strings and Other Sensitive Settings in Your Code


Protecting application secrets, such as database connection strings and passwords, requires careful consideration of a number of pertinent factors such as how sensitive the data is, who could gain access to it, how to balance security, performance, and maintainability, and so forth. This article explains the fundamentals of data protection and compares a variety of techniques that can be used to protect application settings. The author discusses what to avoid, such as hiding keys in source code and the use of Local Security Authority. In addition, he presents some effective solutions such as the Data Protection API.

Alek Davis

MSDN Magazine November 2003

ActiveX and Visual Basic: Enhance the Display of Long Text Strings in a Combobox or Listbox


The combobox and listbox controls in Visual Basic have no built-in support for displaying text strings that are too long to fit in the visible area of either control. This article describes several techniques to improve the readability of long strings in each control. The first technique uses tooltips to display a combobox or listbox item. The other techniques, which use various Windows APIs, include adding a horizontal scrollbar for a listbox and determining the necessary width of the longest string given the font attributes of the text. The required steps are described for both comboboxes and listboxes.

John Calvert

MSDN Magazine December 2000

quotes in xml strings


I need to post an xml string to another website.  I can't create an xml file, because some of the content is dynamically created.  The two lines that are causing me problems are

sPostData = sPostData & "<?xml version='1.0'?>"
sPostData = sPostData & "<?qbmsxml version='4.1'?>"

The receiving site expects to see

<?xml version="1.0"?>
<?qbmsxml version="4.1"?>


<?xml version='1.0'?>
<?qbmsxml version='4.1'?>

The conversion from double quotes to single quotes isn't being accepted.  So how can I send the string so that the versions are surrounded by double quotes?

PropertyChangedEventHandler handler = this.PropertyChanged;

Ah yes the INotifyProperty interface defines the event in title of this post.   A well known pattern often is seen on the internet in using this Interface.  Josh Smith includes this pattern in his ViewModelAbstractBase class as shown here: Implementation of INotifyProperyChanged in ViewModel Abstract Base Class     #region INotifyPropertyChanged Members         /// <summary>         /// Raised when a property on this object has a new value.         /// </summary>         public event PropertyChangedEventHandler PropertyChanged;         /// <summary>         /// Raises this object's PropertyChanged event.         /// </summary>         /// <param name="propertyName">The property that has a new value.</param>         protected virtual void

XAML - ValueConverter Parameters and PropertyChanged callback

Hi I am trying to use a IValueConverter on the flowdocument of a richtextbox. However, ideally I'd like to be able to inject some dependencies into the converter on construction or perhaps with a setter of some sort. Previously I've been using an IoC to construct a formatter-type object and can obviously specify the constructor dependency quite easily. However, I was hoping to use XAML and the IValueConverter as much as possible, but specifying the converter in the Grid.Resources requires a parameterless constructor. Are there other ways in which I can do this or do I need to think about the problem differently. In addition, because you cannot bind to a RichTextBox, I have introduced an AttachedProperty. Here's some code     Public Shared ReadOnly DocumentProperty As DependencyProperty = DependencyProperty.RegisterAttached("Document", GetType(FlowDocument), GetType(RichTextBoxExtensions), RichTextBoxFrameworkPropertyMetaData) Private Shared Function RichTextBoxFrameworkPropertyMetaData() As FrameworkPropertyMetadata Dim metaData = New FrameworkPropertyMetadata metaData.BindsTwoWayByDefault = True metaData.AffectsRender = True metaData.PropertyChangedCallback = New PropertyChangedCallback(Sub(obj, e) If _recursionProtection.Contains(Thread.CurrentThread) Then Return Dim rtb = CType

Error calling WCF service that is returning list.".Debugging resource strings are unavailable ......

Ok.this is just making me frustrated... Here is step by step of what I am trying to do (& not able to) 1. I am calling WCF service hosted in a SharePoint 2010 site from a silverlight app in same domain (So no cross doman I guess). 2. I use Linq to Sharepoint for querying the DB. 3. I am having a list "machines" in Sharepoint 2010 that is having a lookup column from Other list called "part" 4. My WCF method GetAllMachines() works perfectly well when it skips the lookup column "partname" & returns List of type machineitem. 5. But problem occurs when I add machineitemobject.parts.partsname in my Linq to Sharepoint query . My service gives the error not found Async_ExceptionOccurred] Arguments: Debugging resource strings are unavailable." 6. Note that return type of my Method is List<machinesitem> 7. The point to note here is that I use SPMETAL tool to generate the LINQ class that maps the lists . So When I try to query the lookup column it tries to add List item of the type class & that is what causing the error. Is it because I am not using datacontract in my service (but it returns the strings & all private members of machines list e.g. name,title etc) Is it making the attribute Serialisable will solve the error ??? I am kind of lost in it ...Plss help!!   Thanks

Subtracting from Strings

I am writing a windows form which requires putting all the words in a textbox in an array. Everything is fine except the backspace function. Obviously, when the user hits backspace, I want it to remove the last character typed; however, I keep getting errors when I subtract from a string... here's the code (it's in c++ but I'm fine if I get code samples in other programming languages from you) it is in a key down event handler for textBox1   if(e->KeyCode != Keys::Space && e->KeyCode != Keys::Back && e->KeyCode != Keys::ShiftKey) { input[j] += e->KeyCode.ToString(); } if(e->KeyCode == Keys::Back) { if(input[j] == "") { j--; } else { String^ theText = input[j]; int i = theText->Length - 1; input[j] = input[j] - theText[1].ToString(); } } if(e->KeyCode == Keys::Space) { j++; } //j is an int and input is a string array  

Simple Regex. Select 2 strings in a sentence

Hello,  I am a begginer in Regular expressions. I am trying to write a regex to print out a specific string in a sentence.  For example:  "We've found questions similar to yours" I would like to create a regex for the word "found" and "yours". whenever found is matched OR yours is matched print the word.  Basically i just need to know how the OR statement works in this case.  regex.match("found" OR "yours")  ??? Thank you -Klevis

Strings stripped of leading whitespace when using MTOM message encoding

Hello, I have a problem which I believe is actually caused by a bug in WCF 4 (.Net 4). I have a WCF service exposes two basicHttpBinding endpoints identical in everything but the message encoding used, one uses "text" and one "mtom" (i.e. the values for the messageEncoding attribute on the binding configuration). If I send a string with leading whitespaces to the "text endpoint" it is delivered to the service application code exactly as sent. If I send the string to the "mtom endpoint" it is stripped of the leading whitespaces before being handed over to the service application code. I have confirmed that the leading whitespaces are included in the message on the wire and using an IDispatchMessageInspector I have also confirmed that the whitespaces are still present after decoding the message (Message.ToString()). The whitespaces seem to disappear between this stage and when the message is deserialized. My current workaround is an IDispatchMessageInspector with the following AfterReceiveRequest method: public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { // Doing this roundtrip over MessageBuffer removes the problem // (i.e. leading whitespaces are not removed) request = request.CreateBufferedCopy(int.MaxValue).CreateMessage(); return null; } Am I missing something he

How to: Verify That Strings Are in Valid E-Mail Format

This is HALF answered in the MSDN library with an example function called IsValidEmail. Does anyone else think maybe it's time the example function (which developers are likely to copy-paste) was changed to closer represented what an email address can actually be? Sure, it matches joe.blogs@example.com, or joe-blogs@example.com... But how about joe.blogs+work@example.com, or joe.blogs+support@example.com, or e=mc^2@example.com, or many other valid email addresses? The page http://msdn.microsoft.com/en-us/library/01escwtf.aspx has been updated for each new release of VisualStudio/.NET, but even the VS 2010/.NET4.0 one isn't much better!

ViewModel PropertyChanged

Hi all In my Viewmodel i have this property: BusinessAnagrafica _businessAnagrafica; public BusinessAnagrafica BusinessAnagrafica {     get     {         return _businessAnagrafica;     }     set     {         if (value != _businessAnagrafica)         {             if (_businessAnagrafica != null) _businessAnagrafica.AnagraficaModel.Recapito.PropertyChanged -= OnAnagraficaChanged;             _businessAnagrafica = value;             if (_businessAnagrafica != null)             {                 if (_businessAnagrafica != null) _businessAnagrafica.AnagraficaModel.Recapito.PropertyChanged += OnAnagraficaChanged;             }         }     } } in my View i have a textbox with this binding: Text="{Binding BusinessAnagrafica.AnagraficaModel.Recapito.TextRecapito, ValidatesOnDataErrors=True, UpdateSource

Are these the same strings?

I just wanted to confirm. Let's say I have a method like this string GetValue() { string firstString = "Hello" ; return firstString; } Then somewhere else in the code I call this method. string secondString = GetValue(); My question is , are firstString and secondString the same string , or 2 different strings? I checked the memory addresses of both strings (using pointers) and they are the same, so my guess is that only one string is created but I want to be sure of that. thanks in advance.

INotifyPropertyChanged, explicit interface implementation and binding

Hello. Can I notify about explicitly implemented property change and what name should I provide to PropertyChanged? Or does WPF support onetime binding only for them?
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend