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 … 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:

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);
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)
tempArray = new byte[BUFFER_SIZE];
byte[] temp = new byte[count];
Array.Copy(tempArray, 0, temp, 0, count);
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))
// 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();

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

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
string dataDecompressed = this.DecompressData(dataBytes);

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

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

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
dataDecompressed = this.DecompressGZip(dataBytes);

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:

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));

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
            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)];
            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

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: ). 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()
    // reopen stdout
    TextWriter writer = new StreamWriter(Console .OpenStandardOutput()) { AutoFlush = true };

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

private void TestAllocConsole()
    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." );

    // This closes and releases the Console
    // This re-creates a brand new Console instance

    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." );


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:

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 ( 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?