title: What's the right pattern? An observer between the viewmodel & service
body: <p>I am building a WP7 client app that talk to a web service (SOAP like) using Mvvm-Light.</p>
  
  <p>I have a ViewModel that both implements <code>INotifyPropertyChanged</code> and calls <code>RaisePropertryChanged</code> with the broadcast flag set.  </p>
  
  <p>Both my view (XAML) and my model (which does  HTTP requests to the web service) subscribe to property changes. XAML, obviously, because of <code>INotifyPropertyChanged</code>, and my model by calling </p>
  
  <pre><code>Messenger.Default.Register&lt;SysObjectCreatedMessage&gt;(this, (action) =&gt; SysObjectCreatedHandler(action.SysObject));
  </code></pre>
  
  <p>This pattern is not going to work, i'm afraid, because of the following:</p>
  
  <p>When I get data back from the web service I  set properties on my ViewModel (using <code>DispatcherHelper.CheckBeginInvokeUI</code>).  I actually use Reflection and my call looks like this:</p>
  
  <pre><code>GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =&gt; pinfo.SetValue(this, e.Response, null));
  </code></pre>
  
  <p>Here's the problem:  The resultant property set caused by that call to SetValue causes my property <code>set</code> to call <code>RaisePropertryChanged</code> causing me to send the data I just got from the server right back to it.  </p>
  
  <p><strong>EDIT - Adding more context Per Jon's suggestion</strong></p>
  
  <p>Here's some of my XAML. My GarageDoorOpener class has a GarageDoorOpened property
     </p>
  
  <p>On the home control server there are a bunch of garage door objects that have a boolean property representing whether they are open or not.  I can access these using HTTP POSTs of the form:</p>
  
  <p><a href="http://server/sys/Home/Upstairs/Garage/West" rel="nofollow noreferrer">http://server/sys/Home/Upstairs/Garage/West</a> Garage Door?f??GarageDoorOpened</p>
  
  <p>The the resultant HTTP body will contain either True or False.</p>
  
  <p>The same model applies to other objects in the home with other types (Strings, Integers, etc...).</p>
  
  <p>For now I'm just focusing on the garage door openers.</p>
  
  <p>The View Model for the garage door looks like this:</p>
  
  <pre><code>public class GarageDoorSensor : SysObject
  {
      public static new string SysType = "Garage Door Sensor";
      public const string GarageDoorOpenedPropertyName = "GarageDoorOpened";
      public Boolean _GarageDoorOpened = false;
      [SysProperty]
      public Boolean GarageDoorOpened
      {
          get
          {
              return _GarageDoorOpened;
          }
  
          set
          {
              if (_GarageDoorOpened == value)
              {
                  return;
              }
  
              var oldValue = _GarageDoorOpened;
              _GarageDoorOpened = value;
  
              // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
              RaisePropertyChanged(GarageDoorOpenedPropertyName, oldValue, value, true);
          }
      }
  }
  </code></pre>
  
  <p>The SysObject class this inherits from looks like this (simplified):</p>
  
  <pre><code>public class SysObject : ViewModelBase
  {
      public static string SysType = "Object";
      public SysObject()
      {
          Messenger.Default.Send&lt;SysObjectCreatedMessage&gt;(new SysObjectCreatedMessage(this));
          }
      }
  
      protected override void RaisePropertyChanged&lt;T&gt;(string propertyName, T oldValue, T newValue, bool broadcast)
      {
          // When we are initilizing, do not send updates to the server
          // if (UpdateServerWithChange == true)
  
          // ****************************
          // ****************************
          // 
          // HERE IS THE PROBLEM
          // 
          // This gets called whenever a property changes (called from set())
          // It both notifies the "server" AND the view
          //
          // I need a pattern for getting the "SendPropertyChangeToServer" out
          // of here so it is only called when properties change based on 
          // UI input.
          // 
          // ****************************
          // ****************************
          SendPropertyChangeToServer(propertyName, newValue.ToString());
  
          // Check if we are on the UI thread or not
          if (App.Current.RootVisual == null || App.Current.RootVisual.CheckAccess())
          {
              base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast);
          }
          else
          {
              // Invoke on the UI thread
              // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
              GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =&gt;
                  base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast));
          }
      }
  
      private void SendPropertyChangeToServer(String PropertyName, String Value)
      {
            Messenger.Default.Send&lt;SysObjectPropertyChangeMessage&gt;(new SysObjectPropertyChangeMessage(this, PropertyName, Value));
      }
  
      // Called from PremiseServer when a result has been returned from the server.
      // Uses reflection to set the appropriate property's value 
      public void PropertySetCompleteHandler(HttpResponseCompleteEventArgs e)
      {
          // BUGBUG: this is wonky. there is no guarantee these operations will modal. In fact, they likely
          // will be async because we are calling CheckBeginInvokeUI below to wait on the UI thread.
  
          Type type = this.GetType();
          PropertyInfo pinfo = type.GetProperty((String)e.context);
  
          // TODO: Genericize this to parse not string property types
          //
          if (pinfo.PropertyType.Name == "Boolean")
          {
              GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =&gt; pinfo.SetValue(this, Boolean.Parse(e.Response), null));
              //pinfo.SetValue(this, Boolean.Parse(e.Response), null);
          }
          else
          {
              GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =&gt; pinfo.SetValue(this, e.Response, null));
              //pinfo.SetValue(this, e.Response, null);
          }
      }
  }
  </code></pre>
  
  <p>My "model" is called PremiseServer.  It wraps Http POSTs and handles causing the server to be "queried" for the latest data every once and a while.  I plan on eventually implementing notifications, but for now i am polling.  It uses a bit of Reflection to dynamically translate the HTTP results into property sets.  At it's core it looks like this (i'm pretty proud of myself for this, although I probably should be ashamed instead).</p>
  
  <pre><code>    protected virtual void OnRequery()
      {
          Debug.WriteLine("OnRequery");
          Type type;
  
          foreach (SysObject so in sysObjects)
          {
              type = so.GetType();
              PropertyInfo[] pinfos = type.GetProperties();
  
              foreach (PropertyInfo p in pinfos)
              {
                  if (p.IsDefined(typeof(SysProperty),true))
                      SendGetProperty(so.Location, p.Name, so, so.PropertySetCompleteHandler);
              }
  
          }
      }
  
      protected delegate void CompletionMethod(HttpResponseCompleteEventArgs e);
      protected void SendGetProperty(string location, string property, SysObject sysobject, CompletionMethod cm)
      {
          String url = GetSysUrl(location.Remove(0, 5));
          Uri uri = new Uri(url + "?f??" + property);
          HttpHelper helper = new HttpHelper(uri, "POST", null, true, property);
          Debug.WriteLine("SendGetProperty: url = &lt;" + uri.ToString() + "&gt;");
          helper.ResponseComplete += new HttpResponseCompleteEventHandler(cm);
          helper.Execute();
      }
  </code></pre>
  
  <p>Note that OnRequery is not the only place I'll eventually be calling SendGetProperty from; it's just there for initialization scaffolding for now. The idea is that I can have a generic piece of code that gets a "message from the server" and translates it into a SysObject.Property.SetValue() call...</p>
  
  <p><strong>END EDIT</strong></p>
  
  <p>I need a pattern that will let me both bind to my data on the XAML side but also on my model side in a thread safe way. </p>
  
  <p>Suggestions?</p>
  
  <p>Thanks!</p>