Sunday, September 02, 2012

A Generic WCF Proxy Class

A couple of years ago, when I first started using WCF, it seemed like a real pain in the you-know-what to add Service References to my app in order to consume WCF Services. I wanted a base Proxy class that I could extend to be used for any kind of ServiceContract. The key to writing this class was the use of generics Here’s what I came up with, after much trial and error (be sure you have using System.ServiceModel and using System.ServiceModel.Channels):

public abstract class ProxyBase<T> where T : class
{
    #region Declarations
    public ChannelFactory<T> Factory = null;
    public T proxy { get; set; }
    public string EndpointName { get; set; }
    private string m_Certificate;
    public string Certificate
    {
        get { return this.m_Certificate; }
        set
        {
            try
            {
                this.m_Certificate = value;
                if (this.m_Certificate.IsNotNullOrEmpty() && Factory != null)
                {
                    EndpointIdentity Identity = EndpointIdentity.CreateDnsIdentity(this.m_Certificate);
                    if (Identity == null)
                        Console.WriteLine("Identity Is Null");
                    else
                    {
                        Uri AddressUri = Factory.Endpoint.Address.Uri;
                        Factory.Endpoint.Address = new EndpointAddress(AddressUri, Identity);

                        // not sure, but probably have to remove old EventHandler before recreating the 
                        // proxy and recreating the Channel.
                        ((ICommunicationObject)proxy).Faulted -= new EventHandler(ProxyBase_Faulted);
                        proxy = Factory.CreateChannel();
                        ((ICommunicationObject)proxy).Faulted += new EventHandler(ProxyBase_Faulted);
                    }
                }
            }
            catch (Exception ex)
            {
                Factory = null;
                proxy = null;
            }
        }
    }
    #endregion

    #region Constructors
    public ProxyBase() { }
    public ProxyBase(string endpoint)
    {
        // not the best error-handling, but good enough for now
        // TODO - make error-handling better
        //        Already handling faulted channels, but now need to do something for bad addresses?
        //        Because I *think* a bad address will cause an exception in the creation of the Factory.
        try
        {
            this.EndpointName = endpoint;
            Factory = new ChannelFactory<T>(endpoint);
            proxy = Factory.CreateChannel();
            ((ICommunicationObject)proxy).Faulted += new EventHandler(ProxyBase_Faulted);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error in Proxy for {0}, Endpoint: {1}\r\n{2)", typeof(T).Name, endpoint, ex.Message);
            Factory = null;
            proxy = null;
        }
    }
    public ProxyBase(string endpoint, string address)
    {
        // not the best error-handling, but good enough for now
        // TODO - make error-handling better
        //        Already handling faulted channels, but now need to do something for bad addresses?
        //        Because I *think* a bad address will cause an exception in the creation of the Factory.
        try
        {
            this.EndpointName = endpoint;
            Factory = new ChannelFactory<T>(endpoint);
            Factory.Endpoint.Address = new EndpointAddress(address);
            proxy = Factory.CreateChannel();
            ((ICommunicationObject)proxy).Faulted += new EventHandler(ProxyBase_Faulted);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Proxy for {0}, Endpoint: {1}, Address: {2}\r\n{3}", typeof(T).Name, endpoint, address, ex.Message);
            Factory = null;
            proxy = null;
        }
    }
    #endregion

    #region Methods
    public void Close()
    {
        if (proxy != null)
            ((IChannel)proxy).Close();
        if (Factory != null)
            Factory.Close();
    }
    #endregion

    #region Events
    private void ProxyBase_Faulted(object sender, EventArgs e)
    {
        Console.WriteLine("Proxy for {0}\r\n{1}", typeof(T).Name, ((IChannel)proxy).State.ToString());
        ((ICommunicationObject)sender).Abort();
        proxy = Factory.CreateChannel();
    }
    #endregion
}

Seems pretty simple. Notice that it’s an abstract class. You must sub-class it in order to use it. OK, so how do we construct the sub-class? Very simple also. First, you must have a few Interfaces defined, as you would normally have for any WCF service. Here is what I’m going to use for my example:

[ServiceContract(Namespace = "http://MyCompany")]
public interface IMessageService
{
    [OperationContract(IsOneWay = true)]
    void ProcessMessage(IMessage message);
}

[ServiceContract(Namespace = "http://MyCompany")]
public interface ISynchronousMessageService
{
    [OperationContract]
    bool ProcessMessage(IMessage message);
}

public interface IMessage
{
    string MessageToSend { get; set; }
    string MessageReceived { get; set; }
}
public class MyMessage : IMessage
{
    public string MessageToSend { get; set; }
    public string MessageReceived { get; set; }
}

All WCF Services need to have a ServiceContract and OperationContract, so there they are. I’ve also got an interface defined for the Messages I’m going to send, plus a MyMessage class that implements that IMessage interface.

Next, here is what my sub-classed Proxies might look like:

public class SynchronousProxy : ProxyBase<ISynchronousMessageService>, ISynchronousMessageService, IDisposable
{
    #region Constructors
    public SynchronousProxy(string endpoint) : base(endpoint) { }
    public SynchronousProxy(string endpoint, string address) : base(endpoint, address) { }
    #endregion

    #region Methods
    public virtual bool ProcessMessage(IMessage message)
    {
        try
        {
            if (proxy != null)
                return proxy.ProcessMessage(message);
            else
                return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception, ProcessMessage\r\n{0}", ex.Message);
            return false;
        }
    }
    public void Dispose()
    {
        this.Close();
    }
    #endregion
}
public class Proxy : ProxyBase<IMessageService>, IMessageService, IDisposable
{
    #region Constructors
    public Proxy(string endpoint) : base(endpoint) { }
    public Proxy(string endpoint, string address) : base(endpoint, address) { }
    #endregion

    #region Methods
    public virtual void ProcessMessage(IMessage message)
    {
        try
        {
            if (proxy != null)
                proxy.ProcessMessage(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception, ProcessMessage\r\n{0}", ex.Message);
        }
    }
    public void Dispose()
    {
        this.Close();
    }
    #endregion
}

And now, how do I actually use these proxy classes? You’d have the usual WCF stuff defined in the .config in the endpoint in the systemServiceModel tags:

  <system.serviceModel>
    <client>
      <endpoint name="MyEndpoint"
          address="net.tcp://MyComputer:666/MyMessageService"
          binding="netTcpBinding" bindingConfiguration="netTcpConfig"
          contract="MyApp.IMessageService"/>
    </client>
  </system.serviceModel>

And then in your code, you’d call the WCF service like this:

using (Proxy proxy = new Proxy("MyEndpoint"))
{
    MyMessage message = new MyMessage();
    message.MessageToSend = "MyTestMessage";
    proxy.ProcessMessage(message);
}

Wow, that’s pretty easy, isn’t it? No need to add ServiceReferences or anything like that. All you need to know are the Interfaces that the Services use and you’re good to go!

Saturday, August 11, 2012

MSDataSetGenerator Gone Wild

As regular readers of my blog may know, I’m big into Typed DataSets (but not the TableAdapters that can sometimes get generated with them. See my blog posts about this topic, starting with this one: http://geek-goddess-bonnie.blogspot.com/2010/04/create-xsd.html).

Two months ago I ran into a problem when the MSDataSetGenerator went crazy. I asked questions about it on the Forums and ended up discovering a workaround for it myself. Then, earlier this week it happened again and I couldn’t remember what my workaround was!!  I looked for my post from 2 months ago on the Forums and my workaround saved the day. I figured it was time to write a blog post about it.

Here’s an excerpt from my original forum post about what was happening:

In the past, I've not had any problems generating a Typed DataSet from my .xsd. (I'm using VS 2010). The project is set to .NET 4, but the MSDataSetGenerator refuses to generate TypedTableBase in the  Designer.cs file (still using DataTable).  I've tried everything ... deleting the Designer.cs, right-clicking the .xsd in the solution and "Run Custom Tool", deleted MSDataSetGenerator from the CustomTool property and then adding it back in,  etc.etc.etc.   Nothing works, it keeps generating DataTables  instead of the proper TypedTableBase.

The weird thing is that, as far as I know, the only time it's supposed to generate DataTable is if your project targets .NET 3.0 or lower. .NET 3.5 and above should generate TypedTableBase. But that’s not what was happening. But I finally figured it out … here’s my “Eureka” post from the forum:

Holy cow! This is strange! I typically add a DataSet by doing the following:

  1. Copy an existing .xsd file to my project's folder.
  2. Right-click the project in Solution Explorer and "Add Existing", choosing the .xsd
  3. Add the MSDataSetGenerator to the Custom Tool property if necessary.
  4. Generate the Typed DataSet

... I've been doing it this way for years (but haven't always been paying attention to what gets generated, because I haven't typically used LINQ with the DataSets until recently).

Someone mentioned to me that I should try adding DataSets a different way. Instead of "Add Existing", I should "Add New Item" and choose a DataSet item. Then I can copy/paste the xml into it. I tried that in my current problem project and guess what ... it generated the TypedTableBase!  And, lo and behold, the DataSet that refused to generate TypedTableBase was now doing it correctly too!!  Weird!!

So, I decided to test it in a brand new project. I closed the solution (but did not close VS). Created a new solution/project, copied an .xsd file, "Add Existing", generate ... still TypedTableBase (I was expecting it to be DataTable, since I didn't "Add New Item", DataSet). Hmmm ... maybe it was because I didn't start with a fresh Visual Studio? I shut it down, started up VS again, went through the process a second time with a brand new solution and created the DataSet with "Add Existing" ... this time ... DataTable, as I now expected it to do.

And again, as soon as I did "Add New Item", DataSet ... both DataSets again generated TypedTableBase.

But wait ... there's more! As soon as I shut down Visual Studio and started it up again, the DataSets again revert to generating DataTables instead of TypedTableBase (until I "Add New Item", DataSet, then it's fine again).

Sounds like a major bug to me .... anyone else see this behavior?

UPDATE (two years later, 12/30/2014):
I have been meaning to update this blog post ever since a reader commented with a much better workaround to the bug. Not everyone reads comments, so this great idea may have been missed by some. Here is the comment, written by Anonymous:

If you open up Visual Studio (2008 in my case) and you have not yet opened any xsd dataset in a *graphical* designer, the custom tool will generate the designer code the *old* way (derived from a normal DataTable). After you open an xsd - any xsd - for the first time in a graphical designer, from that point forward the custom tool will generate the designer code the *new* way (derived from TypedTableBase).

Just remember to *not* make your updates in the graphical designer, just open it and then close it. And that only has to be done once (each time you open a new instance of Visual Studio).



Saturday, April 14, 2012

Forms Handler

I frequently see forum questions about how to handle/manage an app that uses many Windows Forms (when you’re not using MDI forms). It’s pretty simple really if you use a custom FormsHandler. This is something I wrote years ago and it still works just fine. It could probably stand to be updated a bit, like instead of using an ArrayList, use a List<Form> … but I’ll leave that as an exercise for the reader.

First the FormsHandler class. Notice that it uses only static methods, so the class never needs to be instantiated.

using System;
using System.Collections;
using System.Windows.Forms;

namespace MyNameSpace.MyClasses
{
    public class FormsHandler
    {
        #region Declarations
        private static ArrayList list = new ArrayList();
        #endregion

        #region Methods
        public static void Add(Form o)
        {
            Form oForm = Find(o);
            if (oForm == null)
            {
                oForm = o;
                list.Add(o);
            }

            oForm.Show();
        }
        public static Form Find(Form o)
        {
            foreach (Form x in list)
            {
                if (o.GetType().Equals(x.GetType()))
                    return x;
            }
            return null;
        }
        public static void Remove(object o)
        {
            list.Remove(o);
        }
        public static bool Close()
        {
            int nCount = list.Count;
            while (list.Count > 0)
            {
                ((Form)list[0]).Close();
                if (list.Count == nCount)
                    return false;
                else
                    nCount = list.Count;
            }

            return true;
        }
        #endregion

        #region Properties
        public static ArrayList List
        {
            get { return list; }
        }
        #endregion
    }
}

Whenever you open a form, no matter where you open it from, all you do is add it to the ArrayList, like this:

Form oForm = new MyForm();
FormsHandler.Add(oForm);

All your Forms should have this in their ClosedHandler() method:

protected virtual void ClosedHandler(object sender, EventArgs e)
{
    FormsHandler.Remove(this);
}

When you close your Main Form, you want all others to Close (but to execute their own Closing methods) ... do it like this:

// This is a menu item that exits the application

private void menuItem4_Click(object sender, System.EventArgs e)
{
    System.ComponentModel.CancelEventArgs ee = new CancelEventArgs();
    this.ClosingHandler(sender, ee);
}

// This is the ClosingHandler that will execute normally if you close the app
// by clicking on the "X"

private void ClosingHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (!FormsHandler.Close())
        e.Cancel = true;
    else
        Application.Exit();
}

Notice that the FormsHandler.Close() method will iterate through each Form contained in its list and attempt to close that Form. If it can successfully close all the Forms, then it will return true, otherwise it will return false.

Thursday, February 16, 2012

WCF And Certificate Security

Our application is a messaging system, relying on WCF to send messages around to other computers. We have our WCF services hosted as a Windows Service. The predominate scenario for the use of this system would be on computers within a domain or series of trusted domains and so Windows security seemed to be the easiest way to implement this.

For both netTcpBinding and wsHttpBinding, no security tags were needed, because the defaults were what we wanted. The default for netTcpBinding is Security=”Transport” and clientCredentialType=”Windows”. The default for wsHttpBinding is Security=”Message” and clientCredentialType=”Windows”. This works great between computers on the same domain or on trusted domains.

Well, as luck would have it, our first customer doesn’t trust anybody. The various agencies that needed to “talk” together, don’t have trust between their domains and refuse to grant any trust. So, we were back to square one with trying to figure out how best to handle the security with a deadline looming in 4 short weeks!

We decided that Certificates were the way to go, but  trying to find out how to implement them was a nightmare! Google all you want, but all you’ll find are incomplete examples. We struggled with this for a week. Every time we found something promising, and tried to implement it, there was always some important piece left out of the puzzle and nothing worked. Finally, Gary found this blog:

http://notgartner.wordpress.com/2007/09/06/using-certificate-based-authentication-and-protection-with-windows-communication-foundation-wcf/

Wow! Everything worked! Finally! No missing puzzle pieces! Our thanks go out  to Mitch Denny for his very complete and informative blog post!

Wednesday, November 23, 2011

NAS Gone Bad

Today’s post is not about my usual topic (.NET programming), but about the solution I used when my NAS (Network Attached Storage) went bad. It was a Western Digital My Book World Edition with a 1 TB Caviar Green SATA WD10EADS 5-1/4 inch drive (the one with the white light). The thing is, I was pretty sure my drive (and therefore my data!) was just fine. It’s just that the enclosure and all the electronics that make it “network attachable” was the part that went south. Or so I hoped.

I took it apart (did I mention that I *hate* doing hardware stuff!!) and got the drive out. I thought I bookmarked a link to a video showing how to take it apart, but I guess I didn’t bookmark it and I can’t find the same video at the moment. Google for it though, you’ll find some “how-to” for taking the drive out of the enclosure. If you’re a whiz at hardware, you probably don’t even need a how-to video. It’s not rocket-science … even I could do it! ;0)

Then I hooked it up to a SATA-to-USB converter and plugged the USB into my laptop. At this point, Windows Explorer would not assign a drive letter, but I could see the drive with the Disk Management utility. It was listed as having a Healthy but Unknown partition.

After a little more Googling, I discovered that the drives that get put into these NAS devices are just about always formatted to some kind of Linux format … not readable by Windows!! Grrrr …. now I have a lot more Googling to do!

I found lots of discussions on the topic … apparently some of these NAS devices (not just Western Digital) give up the ghost on a regular basis! You can buy NAS devices that are disk-less … in other words, they’re just the enclosure with all the electronics for making it network attachable and you supply your own drive (I assume an unformatted drive). Which means that if Western Digital sold the same enclosure disk-less for this particular model, then I could just buy the enclosure, pop in my drive and be back in business!!!   Unfortunately, I couldn’t find one and I suspect that they don’t exist for my model. Grrrr …. back to the drawing board!

I found a ton of links talking about how to create a Linux boot disk and boot your machine to Linux and enter in a whole bunch of gibberish Linux commands and it may (or may not) do the trick. There were like 20 steps in some of these how-to discussions! And I know absolutely nothing about Linux. I really did not want to mess with this! So, I kept looking …

Then I found a nifty little driver that could allow a Windows machine to be able to read a Linux formatted drive! Because it’s a driver, it would work seamlessly with Windows. This was just what I was looking for! And it’s free! I downloaded it (Ext2 Driver for Windows). It will work for both Ext2 and Ext3 formatted drives. It installed just fine on my computer. Unfortunately, it didn’t do the trick … why? Because my drive wasn’t formatted with Ext2 or 3!!  More Googling showed me that it was probably an XFS formatted drive. Arrggghhh!!! Will it never end?!?!?!

One more round of Googling and I finally found a solution! It wasn’t free, but it was only about $30. I could live with that if it worked (UFS Explorer). It’s a utility that can read all kinds of partition formats and there was a free trial download (limited to copying files smaller than 64KB) … so I downloaded it to take it for a testdrive. If it worked, I would buy it. You can only read/copy from the drive …  you can’t write to it. But I intended to copy all the files off of the drive, then reformat it to NTFS and install it directly on my machine (yuck … more hardware stuff). Luckily I already had a 2 TB USB drive and I had plenty of room on that drive. The trial showed that it copied the small files flawlessly, so I plunked down the $30 and bought it. It also worked flawlessly, copying every single one of my files off of the XFS partition!  Wow! Disaster averted!

Now, all that’s left to do is reformat the 1 TB and stick it in my machine. But, since that’s hardware stuff, I’ll procrastinate on that task just a little bit longer.  =0)

Saturday, October 08, 2011

XmlSerializer and Implemented Interfaces

Here’s the scenario:

  1. Get some data from calls to a third-party API.
  2. Serialize that data to XML.
  3. Use XSLT to Transform that XML into a common set of classes.

The API utilizes Interfaces for all the objects it returns and it would have been nice if I could have simply used either XmlSerializer or DataContractSerializer on the objects I received, but of course nothing is simple. Suffice it to say that it doesn’t work, for either serializer.

So, I’ve spent the last day or two working on implementing my own classes from the various third-party Interfaces for the objects I need. Basically, I’ll be using the API to get some data. Then I’ll have to copy the data into my own classes and then serialize it to XML.

Theoretically, creating classes that implement on Interface should be easy (simply right-click on the Interface and choose “Implement Interface”. But, nooooo … even though I’m using Visual Studio 2010, it still generates properties the same way it did before the “invention” of automatic properties. In other words, instead of generating a property like this:

public int VehicleID { get; set; }

The property gets generated like this:

public int VehicleID
{
    get
    {
        throw new NotImplementedException();
    }
    set
    {
        throw new NotImplementedException();
    }
}

When you’re talking about implementing a ton of properties, you don’t want to have to fix each of these manually. I knew I could find a way to generate these Interface properties differently, but I had forgotten all about code snippets. Had the old “slap on the forehead” moment when I read this blog post, written by Daniel Cazzulino, about how to do this:

http://blogs.clariusconsulting.net/kzu/how-to-replace-default-interface-property-implementation-expansion-with-automatic-properties/

Duh! Why hadn’t I remembered how to do that myself? Gettin’ old I guess. =0(

But wait, there’s more. Some of these Interface properties did NOT have setters and so they get generated with only the get. While this doesn’t cause a problem with DataContractSerializer, the XmlSerializer will not work unless you have both getters and setters. Daniel mentions, in an update at the end of his blog post, how to take care of this, by producing private setters for the generated property:

public int IncidentID { get; private set; }

Unfortunately, because I’m copying data to my own classes, my class needs to have a public setter. In my case, this doesn’t really matter as far as the functionality of these classes, because I’m only using them so I can serialize the data to XML, so I don’t care that the “set” is exposed publicly.

The two serializers produce very different XML. The task I will tackle next week is to see if that matters when I use that XML for my XSLT Transformations. For those interested, I’ll probably post the results of what happens with that little experiment next week.

Friday, September 30, 2011

DISTINCT - LINQ versus DataSet

Wow, it’s been way too long since the last time I wrote a blog post. I’ve been busy, but that’s really no excuse. In my last post in April, I wrote about using LINQ with Typed DataSets. I did some benchmark comparisons with Selects and LINQ was considerably faster. Today I’m going to compare the DISTINCT capabilities of LINQ versus DataSets.

As before, I’m using the same set of data … a DataTable containing 270,000 rows. I’ve filled the DataTable such that there’s a random number of duplicates in the rows, but it seems that the DISTINCT values always fall between 4750 and 4800 rows.

There are some interesting results. When selecting DISTINCT values, over all columns in the DataTable, it definitely is best to use the old DataSet methods rather than LINQ. And, also surprising, is that the old-style 2.0 Typed DataSets (and likewise, plain old vanilla DataSets, not Typed) are actually faster than newer 3.5 Typed DataSets (refer to my last post, linked to above, that explains what is the difference between the two).

// ds20 is a 2.0 Typed DataSet (a regular DataTable)
// ds35 is the 3.5 Typed DataSet (a TypedTableBase) 
DataTable dt20 = ds20.Personnel.DefaultView.ToTable(true);
DataTable dt35 = ds35.Personnel.DefaultView.ToTable(true);

// Note that if you MUST use the DataRowComparer.
// If you don't you get all rows returned ... it won't find the duplicates.
DataTable dtLinq20 = ds20.Personnel.AsEnumerable()
    .Select(row => row).Distinct(DataRowComparer.Default)
    .CopyToDataTable();

// note that the only difference in syntax between
// 2.0 and 3.5 is that you don't use .AsEnumerable()
DataTable dtLinq35 = ds35.Personnel
    .Select(row => row).Distinct(DataRowComparer.Default)
    .CopyToDataTable();

Benchmarking results show that the DefaultView.ToTable() is 7 times faster than LINQ for ds20 (and 8.5 times faster for ds35). The DefaultView.ToTable() is only slightly faster for ds20 than ds35 ( not significantly though) and with LINQ, ds20 is about 1.5 times faster than ds35. Most peculiar!

  • ToTable (ds20):    77,937,500 ticks
  • ToTable (ds35):    90,718,750 ticks
  • LINQ (ds20):       554,656,250 ticks
  • LINQ (ds35):       781,218,750 ticks

But, there’s where the superiority of the DefaultView.ToTable() ends. Once you start looking for specific columns to be distinct, LINQ is faster. Let’s look at the one column scenario: First, the DataSet code (since all code for the DataSet methods are exactly the same for ds20 as for ds35, I’ll only show one):

DataTable dt20 = ds20.Personnel.DefaultView.ToTable(true, "firstname");

Pretty straightforward … nothing fancy. The benchmark times for both ds20 and ds35 are almost identical.

But now, the LINQ gets trickier. Unfortunately, you’ve got to create the resulting DataTable (including the column) before you can “fill” it from the LINQ query. If there’s a workaround for this, I sure haven’t found it. Here are the two LINQ queries:

// note that you have to create the DataTable first, 
// AND add the column!
DataTable dt = new DataTable();
dt.Columns.Add("firstname");
DataTable dtLinq20 = ds20.Personnel.AsEnumerable()
    .Select(row =>
    {
        DataRow newRow = dt.NewRow();
        newRow["firstname"] = row.Field<string>("firstname");
        return newRow;
    })
    .Distinct(DataRowComparer.Default).CopyToDataTable();

// note that there are 3 differences in syntax for ds20 & ds35:
// 1) as before, you don't use .AsEnumerable()
// 2) you must check for null
// 3) you can use the typed column syntax (row.firstname)
DataTable dt = new DataTable();
dt.Columns.Add("firstname");
DataTable dtLinq35 = ds35.Personnel
    .Select(row =>
    {
        DataRow newRow = dt.NewRow();
        newRow["firstname"] = row.IsfirstnameNull() ? "" : row.firstname;
        return newRow;
    }).Distinct(DataRowComparer.Default).CopyToDataTable();

Now for the benchmark numbers.  LINQ is more than 5 times faster than the DefaultView.ToTable() … (5.25 times faster for ds20 and 5.5 for ds35).

  • ToTable:     15,406,250 ticks
  • LINQ (ds20):    2,937,500 ticks
  • LINQ (ds35):    2,781,250 ticks

As more columns get added, the LINQ advantage becomes diminished. At some point, the DefaultView.ToTable() methodology becomes preferable. I suspect that that point depends both on the number of columns you wish to have distinct, as well as the number of rows that you are processing. The syntax for the DefaultView.ToTable() becomes slightly different when you have more than one column. Here it is:

DataTable dt20 = ds20.Personnel.DefaultView
    .ToTable(true, new string[] { "firstname", "lastname" });

The LINQ syntax doesn’t change, you just keep adding the columns:

DataTable dt = new DataTable();
dt.Columns.Add("firstname");
dt.Columns.Add("lastname");
DataTable dtLinq35 = ds35.Personnel
    .Select(row =>
    {
        DataRow newRow = dt.NewRow();
        newRow["firstname"] = row.IsfirstnameNull() ? "" : row.firstname;
        newRow["lastname"] = row.IslastnameNull() ? "" : row.lastname;
        return newRow;
    }).Distinct(DataRowComparer.Default).CopyToDataTable();

In the case above, of two columns, LINQ was just slightly under 5 times faster.

So, just for giggles, I thought I’d benchmark half the columns. My DataTable has 32 columns, so I tried a distinct on the first 16 columns in my DataTable. And now, it seemed, that we were back to having DefaultView.ToTable() being superior by about 7 times (turns out I was wrong … keep reading). Now, my curiosity got the better of me … I wasted some more time trying to find “the sweet spot” … the number of columns where the performance was about equal. After all, I was a math major in college and I love to play with numbers!

But, as I played more with this, I discovered something very interesting. The time it takes for LINQ depends on the order of the columns!!! In other words, if the first column in your list doesn’t have a lot of distinct values (mine had 7), but the next one in your list does (mine had 4700+), it will take a lot longer. If you swap the column order of those two columns, BAM! Very fast! Instead of the LINQ query being 7 times slower than the DefaultView.ToTable(), it was now 2.25 times faster!

Curiously, this doesn’t seem to matter with the DefaultView.ToTable() … it benchmarked the same amount of time with the columns in any order!

  • ToTable:                                                        42,750,000
  • LINQ (original order of 16 columns):    305,375,000
  • LINQ (swapped order of columns):         19,125,000

I suspect that my very first test, the one with all the columns,suffered from this anomaly … in other words, the LINQ query was so very much slower because that problem column (the one with only 7 distinct values) happened to be the first column in the DataTable. and the syntax of that query didn’t specify columns.

After discovering this quirk, I went back and re-ran the LINQ query that used only 2 columns, but I did it this time with these two particular columns where I noticed this problem. Sure enough, with only a two column distinct query, if the columns were in the wrong order, the query slowed to a crawl … becoming 14.5 times slower than the DefaultView.ToTable()!!!  Wow!

So, what’s the takeaway from this little experiment? Good question … I guess it’s that the data makes the difference. If you’re pretty sure about the data in the columns not being too lopsided, distinct-wise, then LINQ is clearly faster for probably all scenarios except the one including all columns (I did not test this, it’s only a guess … the most columns I tested were half). However, if you’re not certain of the distinctness of the data in your columns, perhaps it’s best to stick with the tried-and-true DefaultView.ToTable() method.

Wednesday, April 06, 2011

LINQ With DataSets

Today's blog post is going to be about using LINQ with DataSets. As anyone who reads my blog regularly (or various forum posts) might already know, I've been a big fan of Typed DataSets since the very beginning of .NET (all the way back to the pretty buggy 1.0 version). However, LINQ is fairly new to me. LINQ *itself* is not new to me ... it has been around for a few years now and I've certainly been aware of it. But I haven't utilized it much because, until .NET 3.5, there was no real support for Typed DataSets and that's really all I wanted to be able to use if for. Sure, you could still use LINQ with both regular DataSets and Typed DataSets ... as long as you used .AsEnumerable() ... but you couldn't take advantage of the Typed nature of a Typed DataSet, so I didn't see any point in messing around with it.

I've recently begun using it more with Typed DataSets because, surprisingly to me, for some things it seems to be faster. Since .NET 3.5, Typed DataSets have been getting auto-generated slightly different than they have in the past (and I'm not talking about the TableAdapter generation, which I despise ... see my blog post about avoiding that fiasco: http://geek-goddess-bonnie.blogspot.com/2010/04/create-xsd.html).

Prior to 3.5, the DataTable definition in a generated Typed DataSet looked something like this:

public partial class PersonnelDataTable : global::System.Data.DataTable, global::System.Collections.IEnumerable
{
// rest of the code here
}


The minor difference is this:

public partial class PersonnelDataTable : global::System.Data.TypedTableBase<PersonnelRow>
{
// rest of the code here
}


TypedTableBase is derived from DataTable, so really nothing changes. But, it allows the DataTable to be used in LINQ queries without specifying .AsEnumerable(), allows us to use the Typed column name properties of the DataRows in our LINQ queries *and* it's also much faster.

As I already mentioned above, LINQ *can* easily be used with regular DataSets/DataTables (it's use is NOT limited to Typed DataSets), but I am not including examples of that in this blog post. As with the 2.0 Typed DataSets, all that is needed is to use .AsEnumerable() with the DataTable, so the code will be almost identical.

So, let's see a few examples.

First, let's look at a typical use for a DataSet, selecting some rows. Using LINQ with a Typed DataSet ends up being quite a bit faster than using the DataTable.Select() method. In all my tests, I used a DataTable containing 270,000 rows. The Select in this test, selected 30,000 of those rows. I also did comparisons between 2.0 DataTable and 3.5 TypedTableBase, just for the heck of it.

// ds20 is a 2.0 Typed DataSet, which uses plain a plain old DataTable

DataRow[] dsSelect20 = ds20.Personnel.Select("lastname = 'Berent'");

DataRow[] linqSelect = ds20.Personnel.AsEnumerable()
.Where(row => row.Field<string>("lastname") == "Berent")
.Select(row => row).ToArray();


The above are your only two choices when using untyped or 2.0 Typed DataSets. Benchmark timing results show that LINQ is about 6 times faster than the old DataTable.Select() method:

  • Select:  5,625,000 ticks
  • LINQ:      937,500 ticks

If you're using 3.5 Typed DataSets, you have a few more options with LINQ. Generally, your LINQ statement will look like this:

// ds35 is a 3.5 Typed DataSet, which uses the new TypedTableBase class for it's DataTable

DataRow[] linqSelectLastName = ds35.Personnel
.Where(row => row.lastname == "Berent")
.Select(row => row).ToArray();


Note the differences: you don't need Personnel.AsEnumerable() and you can use the typed row column names, row.lastname. There is one caveat though to the above syntax. If any row in the Personnel table contains DBNull.Value in the lastname column, the above syntax will throw an exception. You must also check for the null, so the actual statement will need to be this:

DataRow[] linqSelectLastName = ds35.Personnel
.Where(row => row.IslastnameNull() == false && row.lastname == "Berent")
.Select(row => row).ToArray();


You could also use the untyped syntax of the column and then you don't need to check for DBNull, but I like to take advantage of the typed nature of a Typed DataSet. That is the purpose of them, after all. =0) Also, using the untyped syntax is slightly slower, but probably not significantly so.

DataRow[] linqSelectUntypedLastName = ds35.Personnel
.Where(row => row.Field<string>("lastname") == "Berent")
.Select(row => row).ToArray();


Incidentally, my data *does* contain DBNull.Value in the lastname column, so that my benchmark timing tests are valid. The timing for the DataSet.Select() yields roughly the same results either way, but the LINQ is about 1.5 times faster with the TypedTableBase than with a regular DataTable, making LINQ about 9 times faster than a regular DataSet.Select()!!  Here are the results using a 3.5 Typed DataSet:

  • Select:                            5,937,500 ticks
  • LINQ:                                625,000 ticks
  • LINQ (untyped syntax):      781,250 ticks

So, I think that I'll wind up this post for now. There are plenty of other uses of LINQ that I should compare with old DataSet/DataTable functionality, but I think I'll save that for another post. This one is long enough!

Until next time ... happy coding!

Sunday, January 30, 2011

Passing Data Between Forms

There are several different approaches one could make to "pass" information, such as a DataSet, from one Form to another. I see this question asked a lot on the forums, so here's a quick summary. You could use one of these approaches, or combine several of them so that the developer has the flexibility to use whichever approach is appropriate. I'm going to show 3 different solutions to the problem:

First, let's assume we have a MainForm, and it instantiates and shows Form1, and needs to pass a DataSet to it.

1) Form1 can have a DataSet parameter in its constructor:

public class Form1 : Form
{
private DataSet oData;
public Form1(DataSet ds)
{
this.oData = ds;
InitializeComponent();
}
}

// called from MainForm like this:
Form1 oForm = new Form1(this.dsCustomer);
oForm.Show();

2) Form1 can expose its DataSet field as a public Property:

public class Form1 : Form
{
public DataSet oData {get;set;}
public Form1()
{
InitializeComponent();
}
}

// called from MainForm like this:
Form1 oForm = new Form1();
oForm.oData = this.dsCustomer;
oForm.Show();

3) Another option is to use Interfaces. For example, say that your Form1 allows the user to make some changes to the data in the DataSet and you'd like to have MainForm automatically reflect those changes ... even while you're still working in Form1.

First, let's define the Interface:

public interface IDisplayCustomer
{
CustomerDataSet dsCustomer {get;set};
void DisplayCustomer();
}

MainForm would then be defined like this:

public class MainForm : Form, IDisplayCustomer
{
public CustomerDataSet dsCustomer {get;set;}
public void DisplayCustomer()
{
// code here to do stuff with this.dsCustomer
}

...

// then code elsewhere to instantiate and show Form1:
this.dsCustomer = new CustomerDataSet(); // or other code to fill the dataset
Form1 oForm = new Form1(this);
oForm.Show();
}

And Form1 would look like this:

public class Form1 : Form
{
private CustomerDataSet oData;
private IDisplayCustomer CallingControl;

public Form1 (IDisplayCustomer callingControl)
{
this.CallingControl = callingControl;
this.oData = callingControl.dsCustomer;
}

public void DoStuff()
{
// code to do stuff with this.oData
...
// and then redisplay in calling form
this.CallingControl.DisplayCustomer();
}
}

UPDATE:
After getting asked about this a lot, I've decided to add a 4th idea to be considered, expanding on the above 3rd example, which used an Interface. See my new post about that here: Redux

Thursday, December 23, 2010

TransactionScope and SqlServer

Well, here it is, almost the end of the month, and as usual I’m behind in my blog posting. It seems that I’m lucky to get one post a month this past year. But this month, being almost the end of December, I should at least wish all my readers “Happy Holidays”.

Now, on to today’s topic. This may be old news; after all, TransactionScope has been around since 2.0, but I hadn’t been using it back then. I’ve just really started utilizing it during the past year and recently discovered some interesting gotchas.

First, let’s start with a little snippet of code:

using (TransactionScope scope = new TransactionScope())
{
try
{
// transactional stuff in here, perhaps calls to SQL Server

...

scope.Complete();
}
catch (Exeception ex)
{
// do whatever you need to here, we will NOT complete the transaction
Console.WriteLine("*** ERROR " + ex.Message);
}
}

Now, this is all well and good … or so you think. But, there is one little gotcha here …. and that is that when TransactionScope is instantiated without any parameters, the default for its IsolationLevel is Serialized … the most restrictive that there is. On the other hand, for Transactions in SQL Server, the default IsolationLevel is ReadCommitted and, for the most part, that is what you typically will want to use.

In my case, I’m doing a lot of writing to the database, in lots of different threads. If I don’t mess with the TransactionScope, then IsolationLevel.Serialized will severely slow things down, because the database tables, in effect, get locked … because Serializable prevents new data from being added. Wow, not really what I intended!

Well, OK, so I guess we can change the above snippet to this:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions(){IsolationLevel = IsolationLevel.ReadCommitted}))
{
try
{
// transactional stuff in here, perhaps calls to SQL Server

...

scope.Complete();
}
catch (Exeception ex)
{
// do whatever you need to here, we will NOT complete the transaction
Console.WriteLine("*** ERROR " + ex.Message);
}
}

Wow, that’s messy, but it’s necessary.

But wait, there’s more!!  If your current transaction is operating under another ambient transaction (“ambient” is like a parent transaction … I don’t know why they didn’t use the same terminology), the IsolationLevel has to be the same! An exception is thrown if it’s not! So, you’ve got to remember to use this same syntax every time you instantiate a TransactionScope! Yuck!

But, fortunately, there’s a better idea. It’s much easier and cleaner to use a Utility class with static methods for this sort of thing:

public class Utils
{
/// <summary>
/// The reason for this method to return a TransactionScope is because the default IsolationLevel
/// when not specified is Serializable, which is the most restrictive level and will cause all kinds
/// of deadlock problems with Sql Server!!
///
/// We can add more overloads later if we want more options.
/// The TransactionScoope that gets returned here is Required and IsolationLevel.ReadCommitted.
/// </summary>
/// <returns></returns>
public static TransactionScope GetTransactionScope()
{
return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions(){IsolationLevel = IsolationLevel.ReadCommitted});
}
}

And now, we make sure that all our developers know to always use this method when creating a TransactionScope, like this:

using (TransactionScope scope = Utils.GetTransactionScope())
{
try
{
// transactional stuff in here, perhaps calls to SQL Server

...

scope.Complete();
}
catch (Exeception ex)
{
// do whatever you need to here, we will NOT complete the transaction
Console.WriteLine("*** ERROR " + ex.Message);
}
}

Happy Coding and Happy Holidays!

Saturday, November 20, 2010

ForceBind

There are situations in a Windows.Form where the value of a control (such as the value in the .Text property of a TextBox) does not get propagated to its databound object. This can happen as the result of a MenuItem click or a ToolBar button click because these controls do not cause the current control (the ActiveControl, which is the TextBox in my example) to lose focus, thus not forcing the control's value into its databound object. You need something that will force this for every control you have. It can get complicated.

I have a method that I have named ForceBind() in most of my controls (those that have it implement an Interface I have created for this type of behavior). If the control is a container object that implements that Interface (such as a Panel, UserControl, etc.) it will call the ForceBind() method of *it's* ActiveControl (if *that* control implements the Interface).

The actual ForceBind() method is pretty complicated in my controls and relies on the fact that I have a DataBind() method on my controls that tell it which DataTable and DataColumn I am binding that control to. However, I've done a little experimenting and I see that we can find other ways of finding those fields.

I realize that nowadays, most people use a BindingSource rather than Binding directly to a DataTable or DataView. I have not updated my classes yet to differentiate between the various binding DataSources, but in the code I will show below, it is not all that difficult to add that functionality. I leave that as an exercise for the reader …

Here's the ForceBind() method for MyTextBox (along with the code for determining the m_BoundTable, m_BoundColumn and m_BoundProperty fields):

private DataTable m_BoundTable    = (DataTable)this.DataBindings[0].DataSource;
private string m_BoundColumn = this.DataBindings[0].DataBindings[0].BindingMemberInfo.BindingMember;
private CurrencyManager oCurrency = (CurrencyManager)this.BindingContext[m_BoundTable];

public virtual void ForceBind()
{
if (this.DataBindings.Count == 0)
return;

int nRow = -1;
if (this.m_BoundTable != null && this.m_BoundColumn != "")
{
if (this.oCurrency != null)
nRow = this.oCurrency.Position;

if (nRow >= 0)
{
object oValue = this.Text;

System.RuntimeTypeHandle handle = System.Type.GetTypeHandle(this);
System.Type eType = System.Type.GetTypeFromHandle(handle);

ConvertEventArgs e = new ConvertEventArgs(oValue, eType);
this.ParseHandler(this, e);

DataRow row = this.m_BoundTable.DefaultView[nRow].Row;
if (row[this.m_BoundColumn] != e.Value)
{
try
{
row[this.m_BoundColumn] = e.Value;
}
catch (Exception)
{ }

this.OnValidated(new EventArgs());
}
}
}
}

You would call this method whenever there's the possibility of an ActiveControl not losing its focus, say in your own base class for your ToolBar Buttons, for example.

Sunday, October 31, 2010

Multi-Tier Applications

Reading the MSDN forums, I can’t count the number of times I see posters putting all their eggs in one basket, so to speak. Their UI forms contain their Business logic AND their Data Access logic. Their DataSets are defined in the same UI project. Microsoft and Visual Studio, unfortunately, makes this too easy to do … what with all the drag-and-drop stuff from the Server Explorer directly onto a Form designer. I’m sorry, but this is really a great big no-no!!!

These activities should be broken up into multiple tiers, or layers. To simplify, think of three different projects/dlls in your solution. MyUI, MyBiz, and MyDataAccess (I'd actually throw in a 4th one, MyWebService, but let's not complicate matters at this point. Oh wait, I'd have a separate DataSet project too, but as I said, let's keep it simple for now). In your MyUI project, you'd have all the different forms that you plan to use in your UI. The same for MyBiz and MyDataAccess projects, all the different Biz classes and DataAccess classes.

So, to start, your form would be similar to this (to get your data when the form first opens):

using MyCompany.MyApp.Business.MyBiz;

namespace MyCompany.MyApp.WinUI.MyUI
{
public class MyForm : MyBaseForm
{
private long CustomerKey;
private MyDataSet dsData;
private CustomerBiz oBiz;

public MyForm(long key)
{
this.CustomerKey = key;
InitializeComponent();
this.FillData();
}

public void FillData()
{
// To simplify, I'm directly calling a Biz class.
// In reality, I use a Web Service here instead
// which in turn calls the Biz class.

oBiz = new CustomerBiz();
dsData = oBiz.GetCustomer(this.CustomerKey);
}
}
}

Now in your MyBiz project, you'd have a Biz class:

using MyCompany.MyApp.DataAccess.MyDataAccess

namespace MyCompany.MyApp.Business.MyBiz
{
public class CustomerBiz
{
private MyDataSet dsData;

public MyDataSet GetCustomer(long CustomerKey)
{
CustomerAccess oDA = new CustomerAccess();
this.dsData = oDA.GetCustomer(CustomerKey);

// if you have other Biz things to do to this customer
// do it here before returning the DataSet

return this.dsData;
}
}
}

And, lastly, in your MyDataAccess project, you'd have this class:

namespace MyCompany.MyApp.DataAccess.MyDataAccess
{
public class CustomerAccess
{
public MyDataSet GetCustomer(long CustomerKey)
{
// Here's where you'd put all the SqlCommand and DataAdapter stuff
// and fill your DataSet.

return dsData;
}
}
}

Now, that's the "simple" version, just to get the concept. Let's take it a step further:

We have 4 "layers" ... UI, Web Services, Business, Data Access.

These are more than 4 projects, because each layer is further broken down by module. Let's take the DataAccess layer as an example:

As in all our layers, there are DataAccess parent classes from which all DataAccess classes inherit. These parent classes have all the basic functionality needed for DataAccess and we consider it part of our "framework" ... it has it's own project. See my 3-part DataAccess series for more info about this:

http://geek-goddess-bonnie.blogspot.com/2009/09/dataaccess-part-i.html
http://geek-goddess-bonnie.blogspot.com/2009/10/dataaccess-part-ii.html
http://geek-goddess-bonnie.blogspot.com/2009/10/dataaccess-part-iii.html

Each module in our app has a separate DataAccess project. So, we'll have a DataAccess.Personnel project and a DataAccess.Inspection project, etc. and the classes in those projects inherit from the parent classes in the "framework" project. (As you probably know, these separate projects become separate .DLLs).

The Business layer got a little more complicated, but the architecture of it is the same. We actually have 2 Business layers ... server-side and client-side. The server-side classes remain on the server where they are accessed from the Web Services. The client-side classes are brought down to the client from the server to be used by the UI classes, but they can also be used on the server.

So, that's it in a nutshell. I think it's a good start, to get you thinking about how you should structure your application.

Saturday, October 23, 2010

Exception Handling

Today’s post is about having “global” Exception handling at the Application Level. What I mean by that is handling an exception at the very "top" of an application, in your MainForm, in case exception handling as been missed by the developer in other modules, forms or whatever. Something like this will do it:

[STAThread]
static void Main(string[] args)
{
// Creates an instance of the methods that will handle the exception.
CustomExceptionHandler eh = new CustomExceptionHandler();

// Adds the event handler to to the event.
Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

Application.Run(new MainForm());
}

// Creates a class to handle the exception event.
internal class CustomExceptionHandler
{
// Handles the exception event.
public void OnThreadException(object sender, ThreadExceptionEventArgs t)
{
DialogResult result = this.ShowThreadExceptionDialog(t.Exception);

// Exits the program after displaying message to the user.
// In Development mode, the developer will have more options (Abort/Retry/Ignore).
if (result == DialogResult.OK || result == DialogResult.Abort)
Application.Exit();
}

// Creates the error message and displays it.
private DialogResult ShowThreadExceptionDialog(Exception e)
{
DialogResult retval;
string msgUser = "An error occurred please contact the adminstrator with the following information:\n\n";
string msgDev = "An unhandled exception occurred (Abort/Retry/Ignore buttons are only displayed to Developers) \n\n";

string msgTrace = "Error: " + e.Message + "\n\n";
if (e.InnerException != null)
msgTrace += " " + e.InnerException.Message + "\n\n";
msgTrace += "Error Method: " + e.TargetSite + "\n\n" +
"Stack Trace: " + e.StackTrace;

if (System.Diagnostics.Debugger.IsAttached)
retval = MessageBox.Show(msgDev + msgTrace, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation);
else
retval = MessageBox.Show(msgUser + msgTrace, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);

return retval;
}
}

You'll notice that in my example, I only allow the user to Retry or Ignore if they're the developer and debugging. I assume that in such a case, the developer will want to see right off the bat what went wrong and where, but if this happens to a real user, it's typically NOT a good idea to allow them to continue, as it may easily lead to further corruption of data. You can also expand on this class to add error-logging or whatever you wish.