Saturday, April 25, 2015

Communicating With a Windows Service

As most of you are aware, a Windows Service cannot have a GUI (Graphical User Interface) … you can’t run Forms in the Service, you can’t popup a Dialog box and you can’t get input via a Console.ReadLine()!. If you did not previously know that about Windows Services , well … now you do!

There was an interesting discussion about this last month on the MSDN forums. See the thread here:

https://social.msdn.microsoft.com/Forums/en-US/d9917807-2530-4ec1-a40b-edcc564bb726/service-app?forum=csharpgeneral

In that thread, I went back-and-forth with a fellow named Andrew (who has since changed his user name to “Content Removed”). The end result was possibly a misunderstanding between the use of the acronyms GUI and UI, because user interaction *can* be achieved without a GUI. A Service can certainly communicate with other applications (GUI or not) via methodologies such as MSMQ or writing to / reading from TCP/IP, files or databases.

What I didn’t previously know about, and I thank Andrew for showing how to do it, was the ability to communicate with a Service via something called a “Custom Command”. The only values for a Custom Command that you can use are those between 128 and 255. Integers below 128 correspond to system-reserved values. I, personally, have not had the need to do this, but it is an interesting concept to keep in one’s “bag of tricks”. The rest of my blog post will show you how to do this. But first, let me point you to a previous blog post of mine that shows how easy it is to create Windows Services: http://geek-goddess-bonnie.blogspot.com/2013/10/easy-windows-services.html

In my blog post linked to above, you can see that I have a service host, called MyServiceHost, that inherits from System.ServiceProcess.ServiceBase. This is where you would override the OnStart() and OnStop() base methods to do stuff before and/or after starting/stopping your Services (you can “host” multiple Services here if you want to). The way to utiilze the interaction that Andrew was talking about, is to override a method called OnCustomCommand(), which takes an integer parameter (as mentioned above).

There are two parts to implementing this functionality. First, you have to add code to your MyServiceHost class. Something like this:

// You'll want to use enums for your commands, it's more readable
// Custom commands can be any value from 128 to 255
public enum ServiceCommands
{
DoSomething = 128,
DoThingTwo = 129,
// etc.
}

protected override void OnCustomCommand(int command)
{
// always run the base!!
base.OnCustomCommand(command);

if (command >= 128)
{
switch ((ServiceCommands)command)
{
case ServiceCommands.DoSomething :
// code to do something
break;
case ServiceCommands.DoThingTwo:
// code to do something else
break;
default:
// code, if you want, to indicate an invalid value
break;
}
}
}


So, that’s pretty easy, right? Next, you’ll need code to actually send those commands to your Windows Service. This code can be anywhere … it can be in a GUI application, another Windows Service, a Console app … it doesn’t matter where. All you need to know is the name of the Service (and, I believe the application needs to be running with Administrator rights). Here’s some sample code run from a Windows Form:

// Be sure you have referenced the System.ServiceProcess
// and be sure you have a using for it
using System.ServiceProcess;

// In your application, this is all you need to send commands
// to your Windows Service.
// My Service was installed as My.MessagingService
using (ServiceController srvController = new ServiceController("My.MessagingService"))
{
if (srvController.Status.Equals(ServiceControllerStatus.Running))
srvController.ExecuteCommand((int)ServiceCommands.DoThingTwo);
else
System.Windows.Forms.MessageBox.Show(@"The service is not running.");
}


That’s all there is to it. Happy coding!

Tuesday, March 31, 2015

Gotcha With Dictionary Copies

Last week I found a little “gotcha” when I had the need to make a copy of an existing Dictionary object. The Dictionary class has a constructor that takes an existing Dictionary object and makes a copy of it to a new object (https://msdn.microsoft.com/en-us/library/et0ke8sz(v=vs.110).aspx), so I thought that was the perfect way to handle this. Unfortunately, I was wrong.

Here’s the scenario. I am listening to a TCP port, and storing the data as it comes in into a Dictionary<string, MyData>, either adding new items or updating existing ones. Since incoming data can arrive at a pretty fast rate, I didn’t want to process it as it came in, so at 1 minute intervals, I copy the Dictionary and process the copy, and the TCP Listener can go on grabbing data and putting it into the original Dictionary. We can test this with something like this:

// First, here's the data class
private class MyData
{
public int MyInt { get; set; }
public string MyString { get; set; }

public MyData(int start)
{
this.MyInt = start;
this.MyString = "Initialize ...";
}
public override string ToString()
{
return string.Format("{0}: {1}", this.MyString, this.MyInt);
}
}

// And a quick method to show the data:
private void PrintDictionary<T>(string message, Dictionary<string, T> test)
{
Console.WriteLine(message);
foreach (var key in test.Keys)
{
Console.WriteLine("{0}: {1}", key, test[key]);
}
}

// Now the testing begins
Dictionary<string, MyData> Orig = new Dictionary<string, MyData>();
Dictionary<string, MyData> Copy;

// put data in original
Orig.Add("a", new MyData(1));
Orig.Add("b", new MyData(2));
Orig.Add("c", new MyData(3));

// now let's make a copy
Copy = new Dictionary<string, MyData>(Orig);

this.PrintDictionary<MyData>("*** Original ***", Orig);
this.PrintDictionary<MyData>("*** Copy is the same ***", Copy);

Looks pretty simple, but unfortunately, that didn’t work as planned, because the Dictionary copy is actually a “shallow” copy instead of a “deep” copy. Nowhere in the documentation (link above) does it say anything about this being a shallow copy. Probably most of you know the difference between a shallow and a deep copy, but let me explain for those who might not.
  • A shallow copy will copy the original values to the copy.
    • If the values are references, only the references are copied.
    • If the values are primitive types, such as int or string, the actual values are copied.
  • A deep copy will copy the actual data to the copy.
    • If the values are references, the actual object is copied (a new instance, not just the reference to the existing object).
    • For primitive types, there’s no difference, since it copies the actual value of the object with either type of copy.

So what does this mean in plain English? For class types, such as the MyData class in the Dictionary I’ve defined in the above code snippet, a shallow copy means that Orig and Copy are both pointing to (referencing) the same data! If I make a change to an item in Orig, you’ll see the same change in Copy too. I needed a deep copy, meaning that changes to items in Orig did not affect the items in Copy.

Put this code after the above code snippet to see that the items in Orig do indeed point to the same items in Copy:

// now let's modify the original
MyData oldData = Orig["b"];
oldData.MyString = "Made a change";
oldData.MyInt = 42;

this.PrintDictionary<MyData>("*** Original After Modifying Existing Item ***", Orig);
this.PrintDictionary<MyData>("*** Copy changes ALSO!!! ***", Copy);

// Why did the copy change? Because when the original was copied,
// the copied class object did not actually get copied, only the
// reference (the pointer) to the class object was copied.
// So, when the original is changed, since the copy references the
// original, it appears to be changing too.

Once I discovered that the copy was not a deep copy, rather than research ways to change that behavior in the copy itself, for a quick fix I simply created a new MyData object when I needed to update an item in the Orig dictionary:

// I first got around this problem by creating a new class object instead of modifying existing
MyData newData = new MyData(666);
newData.MyString = "Brand New Instance";
Orig["b"] = newData;

this.PrintDictionary<MyData>("*** Original With New Item ***", Orig);
this.PrintDictionary<MyData>("*** Copy will NOT change ***", Copy);

I had needed a quick fix to my problem (I needed to get the code deployed), but I had some time to research this more while I was writing this blog post and found that there are a few other options. Here are some links to decent articles and other discussions:
 
 
I decided to make use of the ICloneable interface for MyData class and add an extension method for Dictionary. Here’s what I did:
 
// First, make MyData implement ICloneable
private class MyData : ICloneable
{
public int MyInt { get; set; }
public string MyString { get; set; }

public MyData(int start)
{
this.MyInt = start;
this.MyString = "Initialize ...";
}
// This protected constructor is just for the purpose of cloning/copying
protected MyData(MyData cloneFrom)
{
this.MyInt = cloneFrom.MyInt;
this.MyString = cloneFrom.MyString;
}
public override string ToString()
{
return string.Format("{0}: {1}", this.MyString, this.MyInt);
}

#region ICloneable Members

public object Clone()
{
// For classes that contain members that are more complex,
// utilize a protected constructor just for the purpose of cloning/copying
return new MyData(this);

// For this particular class, I could also have done this
// using MemberwiseClone, which does a shallow copy.
// Since my class has only primitive types, a shallow copy is fine.
//return this.MemberwiseClone();
}

#endregion
}

public static class Extensions
{
// An extension method for Dictionary. Notice that it is limited to TValue
// types that implement ICloneable.
public static Dictionary<TKey, TValue> Clone<TKey, TValue>(this Dictionary<TKey, TValue> source) where TValue : ICloneable
{
return source.ToDictionary(item => item.Key, item => (TValue)item.Value.Clone());
}
}

Now let’s test this using the following code:

Dictionary<string, MyData> Orig = new Dictionary<string, MyData>();
Dictionary<string, MyData> Copy;

// put data in original
Orig.Add("x", new MyData(1));
Orig.Add("y", new MyData(2));
Orig.Add("z", new MyData(3));

// now let's make a cloned copy, using the Dictionary Clone() extension method
Copy = Orig.Clone();

this.PrintDictionary<MyData>("*** Original ***", Orig);
this.PrintDictionary<MyData>("*** Copy created from Clone of Orig ***", Copy);

// now let's modify the original
MyData oldData = Orig["y"];
oldData.MyString = "Made a change";
oldData.MyInt = 42;

this.PrintDictionary<MyData>("*** Original After Modifying Existing Item ***", Orig);
this.PrintDictionary<MyData>("*** Copy will NOT change!!! ***", Copy);

Yay! It works! This is much “cleaner” than my quick-and-dirty original solution to the problem, which I’ve already deployed, so I’m not going to change it now. Next time I need to make a change to that particular bit of code, I think I’ll refactor it to make use of ICloneable. I like it.

Happy coding!

Saturday, February 28, 2015

Easy-Peasy Connection Strings

I frequently see questions on the Forums about what a developer’s database connection string should look like. The main site that everyone recommends for that is http://www.connectionstrings.com/ … this is a good site and usually very helpful. The only problem is that sometimes people still can’t figure out what their connection string ought to be. So, here’s another suggestion that’s pretty easy to do.

  • Create a new file text file (the easiest place to put that is on your desktop), and change the extension from .txt to .udl
  • Double-click the file and a “Data Link Properties” window opens. By default it opens to the second tab, the “Connection” tab. If you click on the Provider tab, you will see that it defaults to using the Provider for SQL Server. Change that if you’re not using SQL Server.
  • Back on the Connection tab:
    1. Select a server name from the dropdown list. If you don’t see your server there, click the Refresh button. If it’s still not there, then you’re not getting to it via your network and you won’t be able to test the connection. Optimally, it’s best to do this on a machine that has access to the machine that has the database server on it.
    2. Enter your login info, either Integrated security or username/password (check the “Allow saving password” box to save the password in the connection string … you’ll get a warning about saving the password to a file, but that’s OK) .
    3. Select the database.
    4. You can click the “Test Connection” button if you want to, but if you can see a list of databases in Step 3, then you’ve already got a valid connection.
  • You can still do the steps above (except for #4) without actual access to the database server by typing in the server name and database name without picking from a list, and the connection string will be valid (provided that you’ve hand-typed those values in correctly).
  • There are two other tabs on this window, usually you won’t need them.
    • The Advanced tab has a few more options that you usually won’t need to bother with, but take a look if you wish.
    • The All tab will show all the properties that can go into the connection string, the ones you just entered plus others. Make changes here if you wish (double-click an item to edit it), but it’s usually not necessary.
  • Now that you’re done, click OK to save it.
  • To get the actual connection string, right-click on the file, and “Open with” Notepad. Use the string shown (except that you don’t need the “Provider=XXX” part of it).

That’s it! It’s pretty painless …

Happy coding!  =0)

Saturday, January 31, 2015

Compress / Decompress

Our software utilizes a message bus type of architecture to send messages between different  integrated systems. The messages are sent compressed and encrypted, and on the receiving end, they are decompressed, decrypted and then dealt with. We developed this architecture about 6 years ago and it works pretty darn good.

So, today I’m going to talk about the compress/decompress methods. I’ll save the Encrypt/Decrypt for another time, since that is a bit more complicated. What prompted me to write about this was an MSDN forum thread I read, where people were suggesting using the GZipStream class for this functionality. When we first developed our Compress/Decompress methods, we did NOT use GZipStream, so I was curious as to which methodology was better … both in the amount of compression and in the amount of time it took. Here’s the MSDN forum thread: https://social.msdn.microsoft.com/Forums/vstudio/en-US/22df4c05-9959-4188-9d8b-a755ccd9a8cc/maximal-compressing-of-xml?forum=csharpgeneral

Here’s our set of classes:

// be sure you have
//using System.Collections;
//using System.IO.Compression;
protected byte[] CompressData(string xml)
{
if (xml == null)
xml = "";

byte[] temp = Encoding.UTF8.GetBytes(xml);
MemoryStream ms = new MemoryStream();
DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
ds.Write(temp, 0, temp.Length);
ds.Flush();
ds.Close();
return ms.ToArray();
}
protected string DecompressData(byte[] data)
{
const int BUFFER_SIZE = 10;
byte[] tempArray = new byte[BUFFER_SIZE];
ArrayList tempList = new ArrayList();
int count = 0, length = 0;

MemoryStream ms = new MemoryStream(data);
DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress);

while ((count = ds.Read(tempArray, 0, BUFFER_SIZE)) > 0)
{
if (count == BUFFER_SIZE)
{
tempList.Add(tempArray);
tempArray = new byte[BUFFER_SIZE];
}
else
{
byte[] temp = new byte[count];
Array.Copy(tempArray, 0, temp, 0, count);
tempList.Add(temp);
}
length += count;
}

byte[] retVal = new byte[length];

count = 0;
foreach (byte[] temp in tempList)
{
Array.Copy(temp, 0, retVal, count, temp.Length);
count += temp.Length;
}

return Encoding.UTF8.GetString(retVal);
}

And here is a set of classes using GZipStream:

protected byte[] CompressGZip(string xml)
{
byte[] raw = Encoding.UTF8.GetBytes(xml);
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return memory.ToArray();
}
}
protected string DecompressGZip(byte[] data)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream stream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))
{
stream.CopyTo(memory);
// use the commented code instead of CopyTo() for .NET prior to 4.0:
//const int size = 4096;
//byte[] buffer = new byte[size];
//int count = 0;
//while ((count = stream.Read(buffer, 0, size)) > 0)
// memory.Write(buffer, 0, count);
}
return Encoding.UTF8.GetString(memory.ToArray());
}
}

I started with a small set of data, but increased it several times over the course of testing this. The largest string length tested was 1,654,202 bytes, which compressed down to 113,180 bytes. Both sets of classes compressed the data to about the same size (with ours always 24 bytes smaller than the GZipStream, no matter how large the original data was).

Compression times were about the same for either method. But decompression times were about twice as fast with the GZipStream method … but still, we’re talking 40 milliseconds vs 20 milliseconds. Here’s the code I used to benchmark this:

private void CompareCompressionAlgorithms()
{
// get some data
string data = this.GetSomeData(); // write this method to get data however you want to
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();

stopWatch.Start();
byte[] dataBytes = this.CompressData(data);
string dataCompressed = Convert.ToBase64String(dataBytes);
stopWatch.Stop();

Console.WriteLine("DeflateStream Class:");
Console.WriteLine("Data Length: {0}", data.Length);
Console.WriteLine("Compressed Bytes Length: {0}", dataBytes.Length);
Console.WriteLine("Compressed String Length: {0}", dataCompressed.Length);
Console.WriteLine("Total Milliseconds: {0}", stopWatch.ElapsedMilliseconds);

// let's check the Decompress now
stopWatch.Restart();
string dataDecompressed = this.DecompressData(dataBytes);
stopWatch.Stop();

Console.WriteLine("Decompressed Length: {0}", dataDecompressed.Length);
Console.WriteLine("Total Milliseconds: {0}", stopWatch.ElapsedMilliseconds);

// Compare to using GZipStream
stopWatch.Restart();
dataBytes = this.CompressGZip(data);
dataCompressed = Convert.ToBase64String(dataBytes);
stopWatch.Stop();

Console.WriteLine("GZipStream Class:");
Console.WriteLine("Compressed Bytes Length: {0}", dataBytes.Length);
Console.WriteLine("Compressed String Length: {0}", dataCompressed.Length);
Console.WriteLine("Total Milliseconds: {0}", stopWatch.ElapsedMilliseconds);

// now check the Decompress
stopWatch.Restart();
dataDecompressed = this.DecompressGZip(dataBytes);
stopWatch.Stop();

Console.WriteLine("Decompressed Length: {0}", dataDecompressed.Length);
Console.WriteLine("Total Milliseconds: {0}", stopWatch.ElapsedMilliseconds);

}

Bottom line is that both methods work about the same, so choose whichever one you like.

Happy coding!

Tuesday, December 30, 2014

Updated Old Post About MSDataSetGenerator

I want to post about the fact that I updated an old post about some crazy MSDataSetGenerator behavior. The update was to include a better workaround that was suggested to me by one of my readers. The update is at the bottom of the post: http://geek-goddess-bonnie.blogspot.com/2012/08/msdatasetgenerator-gone-wild.html

Sunday, November 30, 2014

XAML Data Binding Faux Pas

This post is more appropriate to a Tweet maybe, except it can't be done in 140 characters. It's just that I wasted all Saturday afternoon trying to figure out why the data binding worked on one Store App page and not another. I even started to wonder if the XAML data binding worked differently in WPF than it worked in Windows Store Apps. As it turned out, there's no difference ... I was just being an idiot and not seeing the forest for the trees! Doh!

Now, to be honest, I haven't done all that much WPF either, but I understand the MVVM concept and this is the architecture I was using for this particular Store App. Also, since I have been playing with designing cross-platform apps with Xamarin, I also had to be cognizant of that fact when designing the Shared projects for Model and ViewModel. For that reason, I was not using ObservableCollections in my Model (I forget now which platform had problems with that), but just a plain old List. My ViewModels obviously had to implement INotifyPropertyChanged, which they did, but here's where I goofed.

I had two XAML pages: a NameSearchPage and a NameDetailPage, and consequently two ViewModels: NameSearchViewModel and NameDetailViewModel. The Search stuff had been done a couple of months ago and had been working fine ... I had to put it all aside to do "real work" and I finally got back to "playing" with it over the long Thanksgiving weekend. I wanted to add the Detail page and all the plumbing for that.

So, I got it all done, but every time I chose a Name, and the Person object got passed to the Detail ViewModel when navigating to the Detail page, the Detail page would only display the limited data from the Person object that was passed in! The ViewModel was correctly hitting the server to obtain more information, and that information was correctly being filled in the Person object, but was not being updated on the Detail page. Even though I looked at everything a million times and I knew I was implementing the INotifyPropertyChanged.

What prompted me down the wrong path for troubleshooting the problem was that I couldn't figure out why, when debugging, the PropertyChanged event was always null, meaning that nothing was subscribing to the event! The data binding on the Detail page should have automatically subscribed to that event. This is why I thought that perhaps there was something subtly different between the XAML for my Search page and my Detail page and that subtle difference might cause it to work in WPF but not in a Store App. I started to create a new solution using WPF instead of Store Apps to test this hypothesis, but scrapped that as being too much work. Back to Googling ...

My mistake, probably, was doing a little too much copy/paste from the Search classes to the Detail classes. Something in the reading I did with all my Googling prompted me to check one more thing in my Detail ViewModel. Yes, I had implemented INotifyPropertyChanged:

#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged( String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged( this, new PropertyChangedEventArgs (info));
    }
}
#endregion

But, I had forgotten the most important part in the definition of my class, I forgot to actually specify INotifyPropertyChanged:

public class NameDetailViewModel : INotifyPropertyChanged

I had looked at that class so many times, and my eyes had jumped right over the missing part every time! What an idiot!! Without the INotifyPropertyChanged specified for the ViewModel, the data binding of WPF (and Store Apps, etc.) never subscribes to the PropertyChanged event, because it doesn't know that there is one!

It is all is now finally working, and I'm happy about that. Except for the part about wasting an entire Saturday afternoon!!

Tuesday, October 14, 2014

Intro To IoC

You can find lots of DI / IoC frameworks (Dependency Injection / Inversion of Control) , both open-source and not. The problem I had was finding something simple enough for what we needed. Here's the scenario:

I am currently playing around with some cross-platform POCs (Proof Of Concept). I wanted to cover all the platforms, so we're looking at Android, iOS, Windows Phone and Windows Store apps. Using Xamarin, building cross-platform applications is pretty nice, because you can re-use almost all your code in Shared Projects, and just segregate out the platform-specific stuff. The platform-specific projects would then contain minimal code ... only what's different for that platform. Xamarin works great for the first 3, but it currently doesn't do Windows Store apps (but that's not a problem, because you're still going to have to treat the Windows Store project as a platform-specific project anyway).

OK, now that I've got that plug for Xamarin out of the way, what issues was I having that I needed an IoC? Let's look at Web Services ... some of the platform-specific projects could only use a Web Service Reference, some could only use a Service Reference. The issue I ran into is that I couldn't put any generated web reference code into the Shared Projects, because what compiled OK for one platform wouldn't compile OK for another platform. So, what you do is use an IoC in the Shared Projects and the Android app could then create its web service reference object & add it to the IoC and the Windows Store app could create its service reference object add it to the IoC.  Then, in the Shared Project that actually needed to call the various web service methods, it just grabbed the instance out of the IoC and everybody's happy!

At first I was thinking, "Well, why do I need an IoC? Can't I just pass the reference to the web service object in the constructor of the Shared class?" Well, yes, I could do that. But here's why my husband, Gary, gets paid the big bucks ... he explained to me that IoC is better because it's more flexible. Think about these cross-platform apps ... what kinds of things are going to be platform-specific? Well, as it turns out, just about everything you might need to use: such as access to GPS, voice recognition, accelerometor, device orientation; just to name a few. These are the kinds of things that could be put into the IoC ... you can see how this could quickly get out of hand if we had to add a bunch of these object to the various class constructors! Not a pretty sight!!!

So, next we tried looking for some already existing IoC frameworks. The problem I had was still a cross-platform incompatibility. Xamarin has a built-in IoC, but since I needed to also target Windows Store apps, I couldn't use the Xamarin IoC. I tried several others, including TinyIoC, but nothing I tried would compile in all the platforms. So, back to the drawing board. We came up with a pretty simple IoC Dependency Manager and I can share the code with you here. I simply didn't need all the bells and whistles of a more complex IoC framework, this simple class suited my purpose just fine. Something more complex is beyond the scope of this blog post (and, anyway, I haven't written anything more complex)!

Here's the code:

public class DependencyManager
{
    private Dictionary<Type , object > DependencyManagerList { get; set; }
    private static DependencyManager m_DependencyManager;
    private static object m_lock = typeof( DependencyManager);
    public static DependencyManager Current
    {
        get
        {
            lock (m_lock)
            {
                if (m_DependencyManager == null)
                    m_DependencyManager = new DependencyManager();
                return m_DependencyManager;
            }
        }
    }
    private DependencyManager()
    {
        this.DependencyManagerList = new Dictionary<Type , object >();
    }
    public void Register<T>( object o)
    {
        if (!DependencyManagerList.ContainsKey( typeof(T)))
            DependencyManagerList.Add( typeof(T), o);
    }
    public object Resolve<T>()
    {
        if (DependencyManagerList.ContainsKey( typeof(T)))
            return DependencyManagerList[ typeof(T)];
        else
            return null;
    }
    public void Remove<T>()
    {
        if (DependencyManagerList.ContainsKey( typeof(T)))
            DependencyManagerList.Remove( typeof(T));
    }
}

Couldn't be much simpler than that, eh?

Here's an example of how to use it.

First, you need to use an Interface, since that's what the "Type" is in the Dictionary key for the DependencyManagerList. Here's mine (the "Message" in the code below is a class, I'm not actually going to define it here in the sample code, it's not necessary):

public interface IServiceClient : INotifyPropertyChanged
{
    Dictionary<string , Message > Messages { get; set; }
    void GetMessage( Message msg);
    object Data { get; set; }
    string Json { get; set; }
}

In the App.xaml.cs, you have a declaration for the IoC:

protected DependencyManager ioc = DependencyManager.Current;

... and in the OnLaunched event of the App, you'd register the ServiceClient object like so (note that I'm not including the code for the ServiceClient class, because it's not relevant to showing how this works ... but it MUST implement the IServiceClient Interface):

NameSearchStore.Classes.ServiceClient o = new NameSearchStore.Classes.ServiceClient ();
ioc.Register< IServiceClient>(o);

Now, in my ViewModel, where I need to use this ServiceClient, I declare it using the Interface:

protected IServiceClient Client;

And get the instance in the constructor of the ViewModel (it doesn't have to be ViewModel, it can be any class, but I'm using MVVM):

this.Client = (IServiceClient)DependencyManager.Current.Resolve<IServiceClient>();

Then, to call a method on the WebService, you just use the Interface methods, such as:

Message msg = new Message();
// more code here for setting up the msg info
this.Client.GetMessage(msg);

Enjoy and happy coding!