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!

Tuesday, September 30, 2014

Using Console in Windows Forms

Coincidences are funny things. I recently answered an MSDN forum question about displaying data in a Console window from within a Windows Forms application (see this thread: http://social.msdn.microsoft.com/Forums/en-US/38444d15-0e1d-4baa-baf7-a692f5a41074/console-error-after-freeconsole-is-called?forum=csharpgeneral ). I had never done this before, but it intrigued me enough to fiddle around with it and be able to come up with an answer to the guy's question.

So what was the coincidence? Two days after answering this question, I was working on a little test app for sending data to a TCP port. It was a WPF test app, with a button to click for sending the data. The button click event allowed you to find a file in order to read its contents and send that data on to an open TCP port. I used a separate class to open a port and listen for a connection to it. In that separate class, I wanted to display connection information and I really thought it best that it show up in a Console window instead of in a TextBox in my WPF form. I was going to create a separate Console app project just for this class when it dawned on me that it would be better/easier to use this "Console from a Form" concept that I had just messed with 2 days earlier. Awesome! And, it works fine from either WPF or WindowsForms.

Here are the details. This is not all that "robust" an implementation. I really only needed the Console for writing status information. No reading from it was necessary, nor did I need to close the Console and re-open another one later on. But, I put these capabilities in my sample that I will show you.

First, you need to use DLLImport for allocating and closing the Console. Then a method for creating the console, and lastly a method for testing these capabilities:

using System.Runtime.InteropServices; // for using DllImport attribute


// Declarations
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeConsole();


public static void CreateConsole()
{
    AllocConsole();
    // reopen stdout
    TextWriter writer = new StreamWriter(Console .OpenStandardOutput()) { AutoFlush = true };
    Console.SetOut(writer);


    TextReader reader = new StreamReader(Console .OpenStandardInput());
    Console.SetIn(reader);
    TextWriter errWriter = new StreamWriter(Console .OpenStandardError()) { AutoFlush = true };
    Console.SetError(errWriter);
}


private void TestAllocConsole()
{
    CreateConsole();
    Console.WriteLine( "This is the first line");
    Console.WriteLine( "Now enter something:");
    string s = Console.ReadLine();
    Console.WriteLine( "You entered: {0}", s);
    Console.WriteLine( "Hit Enter to close this Console and another will be opened." );
    Console.ReadLine();

    // This closes and releases the Console
    FreeConsole();
    // This re-creates a brand new Console instance
    CreateConsole();

    Console.WriteLine( "This is a brand new Console window!" );
    Console.WriteLine( "Enter something:");
    s = Console.ReadLine();
    Console.WriteLine( "You entered: {0}", s);
    Console.WriteLine( "Hit Enter to close this Console for good." );
    Console.ReadLine(); 


    FreeConsole();
}

There is one unsolved issue with the above functionality, and that is the use of Console.Clear(). If you issue a Console.Clear() after you have done a FreeConsole() and a CreateConsole(), it will crash (if you never issue a FreeConsole(), then the Console.Clear() has no problems and works fine). The guy who originally asked the question that started all this (his name is Dmitry), posted a new thread when he encountered this problem. In that thread, he has several ideas to try to workaround the issue. He came up with one workaround that seemed fine to me, but it was something that he wouldn't be able to use in his particular situation (read the thread, and you'll see why). You, dear Reader, may find a use for it, however. He will hopefully post another workable solution in the thread, if he finds one:  http://social.msdn.microsoft.com/Forums/vstudio/en-US/823a024a-05ba-43b7-a72e-220223085835/console-ioexception-error-on-consoleclear?forum=csharpgeneral

Friday, August 29, 2014

Revisiting REST Proxy

In June I published a blog post about creating a class for easily consuming data from RESTful web services (http://geek-goddess-bonnie.blogspot.com/2014/06/proxy-class-for-consuming-restful.html). Since then, I've had the need to use credentials to access a REST service, so my class has had to change a bit. Not much, but I thought it was enough to warrant a new blog post, so here it is. Basically all I did was add UserName and Password properties, plus another constructor like this:

public ProxyBaseREST(string baseAddress, string userName, string password) : this(baseAddress)
{
    this.UserName = userName;
    this.Password = password;
}

And the GetJSON() method was modified slightly to add the credentials to the WebClient:

WebClient WC = new WebClient();
if (!string.IsNullOrEmpty(this.UserName) && !string.IsNullOrEmpty(this.Password))
    WC.Credentials = new NetworkCredential(this.UserName, this.Password);

And the rest is the same as in my earlier post. Pretty easy, eh?

Thursday, August 14, 2014

FileSystemWatcher Improvements

A few months ago, I needed the capability to receive files, process them, and send the processed data to another part of the application. We send information around to various parts of our application by a queuing mechanism. This could be implemented with MSMQ (which is how we did it in version 1 of our app) or by mimicking a queue in database tables (version 2). The queuing mechanism isn't important to this post though, so I won't go into any detail about that.

For my first cut of a FileListener class, I simply used the System.IO.FileSystemWatcher class directly in my code. The code handles the Created event and sends only the filename of the file through to the queuing process in that event handler. The queuing process then pops the filename off the queue, opens and reads the file (simply by calling the File.ReadAllText() method), munges the data from the file and sends the data off to another queue processor. Here's a working example of that, with the queuing process not fleshed out at all, but supplemented by Console.WriteLine()'s so you can follow the progress:

public class MyFileListener
{
    protected FileSystemWatcher Watcher = null;
    protected string FilePath = @"F:\CompletePathToDirectory";
    protected bool ErrorProcessingFileName = true;


    // simulating queuing mechanism with a fake QueuingClass
    QueuingClass QueueManager;


    public MyFileListener()
    {
        this.QueueManager = new QueuingClass();
        this.Watcher = new FileSystemWatcher();
        this.Watcher .Path = this. FilePath;
        this.Watcher .EnableRaisingEvents = true;
        this.Watcher .Created += new FileSystemEventHandler(Watcher_Created);
        this.Watcher .Error += new ErrorEventHandler(Watcher_Error);
        Console.WriteLine( "Waiting for files to be deposited in {0}" , this.FilePath);
    }
    private void Watcher_Created(object sender, FileSystemEventArgs e)
    {
        using (TransactionScope scope = new TransactionScope(TransactionScopeOption .Required, new TransactionOptions() { IsolationLevel = IsolationLevel .ReadCommitted }))
        {
            try
            {
                this.CreateAndSendMessage(e .FullPath);
                scope .Complete();
            }
            catch (Exception ex)
            {
                this.ErrorProcessingFileName = true ;
            }
        }
    }
    private void Watcher_Error(object sender, ErrorEventArgs e)
    {
        this.ErrorProcessingFileName = true ;
    }


    private void CreateAndSendMessage(string filename)
    {
        Console.WriteLine( "Sending FileName {0} To Queue" , filename);
        // put code here to send the file to your queuing mechanism
        // for demo purposes, I'm going to simulate sending to a queue
        this.QueueManager .SendMessageToQueue(filename);
    }
}
public class QueuingClass
{
    private string Message;


    public void SendMessageToQueue(string message)
    {
        this.Message = message;
        this.PopMessageOffQueue();
    }
    protected void PopMessageOffQueue()
    {
        try
        {
            string filename = this. Message;
            if (File .Exists(filename))
            {
                string fileData = File. ReadAllText(filename);


                this.ProcessFileDataAndSend(fileData);


                if (File .Exists(filename))
                    File.Delete(filename);
            }
        }
        catch (FileNotFoundException ex)
        {
            // we can go ahead and eat this exception ... it means the file was processed and/or deleted in another thread
            Console.WriteLine( "File Already Removed: " + ex.FileName);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex .Message);
        }
    }
    protected void ProcessFileDataAndSend(string FileData)
    {
        Console.WriteLine( "Here is the data retrieved from file {0}:\r\n{1}" , this.Message, FileData);
        // This is where you'd process the data from the file
        // and send the processed data off to another queue
        // which I won't bother simulating here.
    }
}

All you have to do to use this MyFileListener class is create an instance of it. Then drop a file (or multiple files) into the directory you've specified and watch the fun. I've just used a Console application to run this ... you can do it however you want to, obviously.

private void TestFileListener()
{
    MyFileListener Listener = new MyFileListener();
}

But, there's a problem with using the Created event when you're attempting to process a large file. The Created event is fired when the file first starts to get copied to the directory you're listening to, not when the file has finished being copied. By attempting to read the file as soon as the Created event is raised, problems arose with blocking file access (the system sending the files couldn't complete the sending of the files, because presumably my trying to read it at the same caused file access issues). I even had the built-in delay of the queuing process (since the file isn't actually being read until it is "popped" off the queue).This ended up working OK for small files (there was enough of a delay), but not larger files. So, I needed to come up with a better idea.

So, I created my own class, sub-classed from FileSystemWatcher and used that instead. The difference being that I create a new event that I call FileReady and fire it when I know the file  copy has completed. How do I know when that happens? In a try/catch, I try to do a File.Open with FileShare set to None. If I can't open the file, then I know it's not done being copied yet and I keep trying until I can open it (at which point I fire the FileReady event). Here's the code for this new class:

public class MyFileWatcher : FileSystemWatcher
{
    public event FileSystemEventHandler FileReady;


    public MyFileWatcher()
    {
        this.Created += new FileSystemEventHandler(Watcher_Created);
    }
    private void Watcher_Created(object sender, FileSystemEventArgs e)
    {
        System.Threading.ThreadPool.QueueUserWorkItem((n) => { WaitForFileReady(e); });
    }
    private void WaitForFileReady(FileSystemEventArgs e)
    {
        while (true)
        {
            try
            {
                using (FileStream fs = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    break;
                }
            }
            catch (FileNotFoundException ex)
            {
                return;
            }
            catch (Exception ex)
            {
                System.Threading.Thread.Sleep(100);
            }
        }
        OnFileReady(e);
    }
    protected virtual void OnFileReady(FileSystemEventArgs e)
    {
        if (this.EnableRaisingEvents && FileReady != null)
            FileReady(this, e);
    }
}

In order to utilize this in the MyFileListener class, simply replace the FileSystemWatcher with the MyFileWatcher and handle the FileReady event instead of the Created event (the code inside the event handler will be exactly the same). Here are the changes to make:

// the declaration
protected MyFileWatcher Watcher = null;
// the MyFileListener constructor
this.Watcher = new MyFileWatcher();
this.Watcher.FileReady += new FileSystemEventHandler(Watcher_FileReady);
// the new event handler name
private void Watcher_FileReady(object sender, FileSystemEventArgs e)

I hope this post helps you successfully implement your next application's needs … Happy Coding!

Thursday, July 31, 2014

Visual Studio 2013, Hyper-V And VMWare

We are big into doing all our development work on VMs and have been using VMWare for almost 5 years now. We've got a fantastic VMWare ESXi server with loads of RAM, CPUs, disk space and a lot of VMs. It's a great setup.

In January, I got a new Dell Venue 11 Pro with Windows 8.1. The thing is a bit buggy, but Dell is slowly taking care of some of those issues ... but I like having a nice small tablet for portability reasons. The resolution could be better, not so damn small for my aging eyes ... but that's why I use two external monitors!!

A few months later, I thought that now that I have a Win 8 machine, I should go ahead and load up Visual Studio 2013. I was not going to be doing any actual development on my Venue, but it's always good to have VS available locally (not on a remote VM) to be able to look at or test something quickly, while I'm away from my network (and my VMs are inaccessible). While in the process of doing that, I figured I'd go ahead and install everything. I thought that perhaps I might want to take a look at Windows Phone apps and see what that was all about ... you never know when you might come up with the next killer phone app (although I have never written any phone apps and, in fact, I do not as yet even own a smart phone). Unfortunately, when you install the stuff for Windows Phone, it also installs Hyper-V and I don't think that it asked me or warned me about that ... it just went and did it. Kinda pissed me off a little bit.

Why is that a problem, you might ask? Well, it didn't interfere with my development work at all ... all my development VMs are accessed via RDP. However, I did have a few other things virtualized that weren't work related ... like my old desktop computer that was starting to have issues. My Quicken and TurboTax were on there and it was easy enough to create a VM. I didn't want to put these types of personal VMs on our work ESXi server, so I put it on a USB drive and then I didn't care if my old desktop died or not (in fact, I shut it down and have not started it up since). I have been doing my Quicken and TurboTax from the VM ever since. But ooops! Along comes Hyper-V and now I can't open my VM with VMWare Player anymore! Damn!

So, now what? A bunch of Googling commenced and I eventually found that I could disable Hyper-V easily enough. I ended up following the advice at this link : http://empiricalmusing.com/Lists/Posts/Post.aspx?ID=25

Basically, here are the steps:

  1. Open Hyper-V manager and "stop service" on the right panel,

  2. Then at an elevated command prompt, run the following command:

          bcdedit /set hypervisorlaunchtype off

This will disable Hyper-v at an elevated command prompt

To enable Hyper-v to use Hyper-V again, at an elevated command prompt, type:

bcdedit /set hypervisorlaunchtype auto

You'll probably have to reboot in order for changes to take effect.

Sunday, June 29, 2014

Proxy Class For Consuming RESTful Services

About 2 years ago, I wrote a blog post about using generics to create an easy-to-use WCF proxy class (click here: A Generic WCF Proxy Class).

A few months ago, I had the need to consume several RESTful web services that made use of JSON. Wanting to make is as easy to use as ProxyBase, the generic WCF proxy class that I posted 2 years ago, I decided to write another base class for RESTful web service access. I call it ProxyBaseREST.

There are several things you will need to add to your project references that aren't normally added when you create a new class library project (and also remember to put using statements for them at the top of your class). One is System.Net, because we'll need to make use of the WebClient, which lives in that namespace. Since we'll also be dealing with JSON, you need a JSON library. I've made use of Json.NET (the assembly is called NewtonSoft.Json.DLL), which is widely used. It's free open-source and you can download it here: https://json.codeplex.com/ And, two more, System.Xml and System.Xml.Linq, since we'll be converting JSON to either XNode or XmlNode.

So, here's the class I wrote:

public class ProxyBaseREST
{
    #region Declarations and Constructor

    protected string BaseAddress;
    protected string Parameters = "";

    public ProxyBaseREST(string baseAddress)
    {
        this.BaseAddress = baseAddress;
    }

    #endregion

    #region Methods

    protected string GetJSON()
    {
        try
        {
            WebClient WC = new WebClient();
            WC .Headers["Content-type" ] = "application/json";
            //string CallString = this.ParseParameters();

            Stream stream = WC.OpenRead( this.BaseAddress + this .Parameters);

            StreamReader reader = new StreamReader(stream);
            string json = reader.ReadToEnd();
            stream .Close();

            if (json == "[]")
                json = "" ;
            return json;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error in Web Service call: {0}{1}" , this.BaseAddress, this.Parameters);
            Console.WriteLine(ex.Message);
            return "" ;
        }
    }
    protected string GetDeserializedJSON(string rootNode)
    {
        string json = this.GetJSON();
        string xml = "";
        try
        {
            xml = this .DeserializeAsXNode(json, rootNode);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Deserializing JSON RootNode '{0}' in Web Service call: {1}{2}", rootNode, this.BaseAddress, this.Parameters);
            Console.WriteLine(ex.Message);
            xml = "" ;
        }

        return xml;
    }
    protected string DeserializeAsXNode(string json, string rootNode)
    {
        if (string.IsNullOrEmpty(json)== false)
        {
            XNode node = JsonConvert.DeserializeXNode(json, rootNode);
            return node.ToString();
        }
        else
            return "" ;
    }
    /// <summary>
    /// Used for mal-formed JSON that lacks a root node
    /// </summary>
    /// <param name="json"></param>
    /// <param name="rootNode"></param>
    /// <returns></returns>
    protected string GetDeserializedJSON(string json, string rootNode)
    {
        string xml = "";
        try
        {
            if (string.IsNullOrEmpty(json) == false)
            {
                string RootAndJson = "{\"" + rootNode + "\":" + json + "}";
                System .Xml.XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(RootAndJson, rootNode);
                xml = myXmlNode.OuterXml;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Deserializing JSON RootNode '{0}' in Web Service call: {1}{2}", rootNode, this.BaseAddress, this.Parameters);
            Console.WriteLine(ex.Message);
            xml = "" ;
        }

        return xml;
    }

    #endregion
}

You'll note that the ProxyBaseREST class makes use of a couple of JsonConvert static methods to convert the JSON format to an XML string. You can change this if you'd like to return XNode or XmlNode, but I prefer strings because I typically use XML to fill a DataSet, which is easily done with an XML string. You can obviously change the methods to return whatever kind of XML you would normally use in your applications.

Now all you have to do is create a sub-class of ProxyBaseREST, add the methods you need to call and you're done. Here's a sample Proxy:

public class MyProxy : ProxyBaseREST
{
    #region Declarations and Constructor

    // constructor
    public MyProxy(string baseAddress) : base(baseAddress)
    {
    }

    #endregion

    #region Methods

    public string GetDataNoParms()
    {
        this.Parameters = "GetData";
        string xml;

        // use one or the other of these two methods
        // comment out (or remove) the one you don't want, obviously

        // this returns a string that is formatted into XML
        xml = this.GetDeserializedJSON("root"); // this "root node" can be called anything

        // this returns a string in the JSON format, just as you've received it from the web service call
        xml = this.GetJSON();

        return xml;
    }
    public string GetDataWithParms(string CustomerName, int CustomerID, bool PreferredCustomer)
    {
        string parms = string.Format("CustomerName={0} CustomerID={1} PreferredCustomer={2}", CustomerName, CustomerID, PreferredCustomer);
        this.Parameters = "GetData?params=" + parms;
        string xml;

        // same two choices as above
        xml = this.GetDeserializedJSON("root");
        xml = this.GetJSON();

        // And here's another situation. You might have mal-formed JSON returned from the web service. 
        // This is fine for just returning the JSON, maybe. But, if you need to serialize it
        // to XML, you'll need to do something extra.
        // The ProxyBaseREST class has a method for that as well, use it in conjunction with the GetJSON() method:
        xml = this.GetDeserializedJSON(this.GetJSON(), "root"); // this "root node" can be called anything

        return xml;
    }

    #endregion
}

And then, you'd make web service calls like this:

public class TestingMyProxy
{
    #region Declarations

    // In real-life, you'd get the address from the appSettings in your config file.
    protected string WebServiceAddress = @"http://192.168.1.161:7777/"; 
    protected MyProxy myProxy;

    #endregion

    #region Constructor

    public TestingMyProxy()
    {
        this.myProxy = new MyProxy(this.WebServiceAddress);
    }

    #endregion

    #region Call Proxy Methods

    public void TestProxyMethods()
    {
        Console.WriteLine("---  GetDataNoParms  ---");
        Console.WriteLine(this.myProxy.GetDataNoParms());
        Console.WriteLine("--- GetDataWithParms ---");
        Console.WriteLine(this.myProxy.GetDataWithParms("CustomerBob", 12345, true));
    }

    #endregion
}