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!

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
}

Thursday, October 17, 2013

Easy Windows Services

I have seen a lot of questions on the Forums about Windows Services. The questions run anywhere from “How can I debug my Service?” to “How can I see the MessageBox my Service is showing?” (hint – you can’t do that last one, it’s not possible to use any UI features in a Windows Service).

So, what’s the secret to making Windows Services easy? Well, first of all, begin by hosting your Service(s) in a Console Application. The transition from tinkering with it while you’re developing, to deploying it as a Windows Service, is made a lot easier this way.

Your Console Application project will contain 4 files: app.config, Program.cs, Services.cs and ProjectInstaller.cs. You could, in a real application, have separate files for the Services and for the ServiceHost. I’ve simplified by putting it all in the same file.

The Program.cs starts everything running (as is normally the case with any Console app):

namespace ConsoleApplication1
{
    class Program
    {
        static MyServiceHost oService;

        // Be sure to add a System.ServiceProcess reference and using
        static void Main(string[] args)
        {
            if (Environment.UserInteractive == false)
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new MyServiceHost()
                    // others may be added as follows, we only have one
                    // , new MyOtherHost()
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                if (ConfigurationManager.AppSettings.Count > 0)
                {
                    oService = new MyServiceHost();
                    oService.Start();
                    Console.ReadLine();
                    oService.Stop();
                }
                else
                {
                    Console.WriteLine("Config file is missing ...");
                    Console.ReadLine();
                }
            }
        }
    }
}

Notice in the above code we check to see whether or not we’re running interactively. A Console application would be interactive, a Windows Service would not. You should be able to see how that works from looking at the above code.

Next, the Services and ServiceHost classes:

namespace ConsoleApplication1
{
    // Service classes are just regular classes, that have only one requirement:
    // They must implement a Start and Stop method.
    public class MyServiceOne
    {
        public void Start()
        {
            // startup code here
        }
        public void Stop()
        {
            // stop code here
        }
    }
    public class MyServiceTwo
    {
        public void Start()
        {
            // startup code here

        }
        public void Stop()
        {
            // stop code here
        }
    }

    // Make sure that you add a reference to System.ServiceProcess in your project references
    // I've got threading in this class, be sure to also add a reference to System.Threading
    public partial class MyServiceHost : System.ServiceProcess.ServiceBase
    {
        // This Windows Service can host as many Service classes as you want
        static MyServiceOne ServiceOne;
        static MyServiceTwo ServiceTwo;

        private Thread SqlThread;
        private bool EndLoop = false;
        private string ConnectionString;

        public MyServiceHost()
        {
            this.CanStop = true;
            this.CanShutdown = true;
            this.CanPauseAndContinue = false;
        }
        protected override void OnStart(string[] args)
        {
            // In the case of my Services, I use SqlServer. I need to be sure it's up and running
            // before my Services start. How could this not be the case? Well, machines could have been
            // rebooted because of Windows Updates or for other kinds of maintenance. Whether or not 
            // SqlServer is on the same machine as your Services really doesn't matter. Your Services
            // could start before SqlServer starts. I handle this possiblity by waiting for SqlServer
            // to start first. This is done in the DoWork() method.
            ThreadStart threadStart = new ThreadStart(DoWork);
            this.SqlThread = new Thread(threadStart);
            this.SqlThread.Start();
        }
        protected override void OnStop()
        {
            if (this.EndLoop == false)
                this.EndLoop = true;
            
            // Notice this interesting tidbit (it applies to my app, but depending on what 
            // your services do, it may also apply to yours ... so, consider this just an FYI):
            // When I start my services (in the StartService() method), I start ServiceOne and then ServiceTwo
            // When I stop them, I stop them in the opposite order, first stop ServiceTwo and then ServiceOne.
            if (ServiceTwo != null)
                ServiceTwo.Stop();

            // Sleep for a second if you need a bit of time between service's stopping
            System.Threading.Thread.Sleep(1000);

            if (ServiceOne != null)
                ServiceOne.Stop();
        }
        protected override void OnShutdown()
        {
            // There may be a bug in the .NET Framework in that this method
            // is not being called on system shutdown for SYSTEM account services.
            // Not sure when/if it will be fixed, but I'm putting code here to stop
            // stuff on the off-chance that it will be called eventually.
            if (ServiceTwo != null)
                ServiceTwo.Stop();
            System.Threading.Thread.Sleep(1000);
            if (ServiceOne != null)
                ServiceOne.Stop();
        }
        protected void DoWork()
        {
            this.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; ;
            if (string.IsNullOrEmpty(this.ConnectionString))
            {
                Console.WriteLine("No MyConnectionString or No Config File.");
                return;
            }

            while (this.EndLoop == false)
            {
                if (this.SqlServerIsRunning())
                {
                    this.StartService();
                    EndLoop = true;
                }
                else
                {
                    if (Environment.UserInteractive)
                        Console.WriteLine("Waiting for SQL Server ...");
                    Thread.Sleep(30000); // 30 seconds
                }
            }
        }
        protected bool SqlServerIsRunning()
        {
            bool IsConnected = false;

            try
            {
                using (SqlConnection conn = new SqlConnection(this.ConnectionString))
                {
                    conn.Open();
                    IsConnected = true;
                }
            }
            catch
            {
            }

            return IsConnected;
        }
        protected void StartService()
        {
            ServiceOne = new MyServiceOne();
            ServiceTwo = new MyServiceTwo();

            ServiceOne.Start();
            ServiceTwo.Start();
        }

        // These 2 methods are only used when not runnning as a Service, for testing from a Console window.
        public void Start()
        {
            this.OnStart(null);
            Console.WriteLine("Services Started");
        }
        public void Stop()
        {
            Console.WriteLine("Services Stopping ...");
            this.OnStop();
        }
    }
}

OK, well, that was pretty painless, right? Go ahead and run this Console application. If you’d like to expand on ServiceOne and ServiceTwo to actually do something, go ahead and spin off some new threads or something … whatever your services might have to do. You can set breakpoints in Visual Studio and debug to your heart’s content. You’ll notice that as soon as you hit the Enter key in the Console window, the service will stop.

Now, that’s all there is to hosting a Service in a Console Application. Once you’ve got it all debugged and you’re ready to go, you’re going to want to install your service as a Windows Service. This is also not too difficult. You’ll have to add an Installer class to your project. You can right-click your project, “Add New Item” and choose “Installer Class” … however, that adds some stuff that you’ll just have to take out anyway (it adds a Designer.cs class and you really don’t need that). Instead, just right-click and add a new class and copy my Installer class as a starting point and it’s much easier. Here it is:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;

namespace ConsoleApplication1
{
    [RunInstaller(true)]
    public partial class MyServiceInstaller : System.Configuration.Install.Installer
    {
            #region Declarations

        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller2;

        public string ServiceName
        {
            get { return this.serviceInstaller1.ServiceName; }
            set { this.serviceInstaller1.ServiceName = value; }
        }
        public string ServiceAccount
        {
            set
            {
                switch (value.ToLower())
                {
                    case "user" :
                        this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;
                        break;
                    case "localservice" :
                        this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
                        break;
                    case "networkservice" :
                        this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService;
                        break;
                }
            }
        }
        public override string HelpText
        {
            get
            {
                return base.HelpText + 
                    "\r\n\r\nSpecific to My Messaging: \r\n\r\n" +
                    "/ServiceName=[servicename] \r\n" + 
                    " Use if installing multiple My Messaging Services. \r\n" +
                    " Defaults to My.MessagingService if switch not used.\r\n\r\n" +
                    "/ServiceAccount [User] |  [LocalService] | [NetworkService] \r\n" + 
                    " Use if not installing under the System account. \r\n\r\n";
            }
        }
        private bool DebugIt = false;

        #endregion

        #region Constructor

        public MyServiceInstaller()
        {
            //InitializeComponent(); // do our own

            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Manual;
            this.serviceInstaller1.ServicesDependedOn = new string[] { "Message Queuing", "Distributed Transaction Coordinator" };
            // 
            // serviceProcessInstaller1
            // 
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            // 
            // ProjectInstaller
            // 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
                this.serviceProcessInstaller1,
                this.serviceInstaller1});
        }

        #endregion

        #region Methods

        protected override void OnBeforeInstall(IDictionary savedState)
        {
            base.OnBeforeInstall(savedState);
            this.SetPropertiesFromCommandLineSwitches();
            this.SetDebugService();
        }
        protected override void OnBeforeUninstall(IDictionary savedState)
        {
            base.OnBeforeUninstall(savedState);
            this.SetPropertiesFromCommandLineSwitches();
            this.SetDebugService();
        }
        private void SetPropertiesFromCommandLineSwitches()
        {
            // command line switches: /ServiceName= /ServiceAccount= (and /debug= but not really using debug right now)
            // See HelpText property in the Declarations and the ServiceName and Service account properties

            string name = this.Context.Parameters["ServiceName"];
            if (string.IsNullOrEmpty(name))
                this.ServiceName = "My.MessagingService";
            else
                this.ServiceName = name;

            string account = this.Context.Parameters["ServiceAccount"];
            if (string.IsNullOrEmpty(account) == false)
                this.ServiceAccount = account;

            if (this.Context.Parameters.ContainsKey("debug"))
                this.DebugIt = true;
        }
        private void SetDebugService()
        {
            if (this.DebugIt)
            {
                this.serviceInstaller2 = new System.ServiceProcess.ServiceInstaller();
                this.serviceInstaller2.ServiceName = "My.Debug.Service";
                this.Installers.Add(this.serviceInstaller2);
            }
        }

        #endregion
    }
}

Next, we’ll need just a few lines of code to execute via a Command line. It’s easiest to create two batch files, one for installing and one for uninstalling. The .NET Framework has an Install Utility called “InstallUtil.exe”, located in the c:\Windows\Microsoft.NET\Framework folder. If you have multiple versions of the .NET Framework installed on a machine, you must make sure you use the correct InstallUtil, depending on the .NET version you’ve targeted in your project properties. It’s easy to do with batch files. Here’s a batch file to install the above Service:

@echo off

REM change if yours is a different path
set INSTALL_UTIL_HOME=C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

set PATH=%PATH%;%INSTALL_UTIL_HOME%


echo .
echo .
echo Installing Service My.MessagingService
echo .
echo .
installutil My.MessagingService.exe

echo .
echo Done.
echo .
pause

To uninstall, your batch file will be essentially the same except you’d echo Uninstalling Service, and you’d use the /u parameter:

@echo off

REM change if yours is a different path
set INSTALL_UTIL_HOME=C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

set PATH=%PATH%;%INSTALL_UTIL_HOME%


echo .
echo .
echo Uninstalling Service My.MessagingService
echo .
echo .
installutil /u My.MessagingService.exe

echo .
echo Done.
echo .
pause

That’s all there is to it. Have fun and happy coding!  =0)