Category Archives: .Net

The Hashtable Demystified

After reading yesterday’s post, one of my coworkers asked me “so what exactly is a hash and how does it work”. Fair question, in my post I concentrated more on how to use the dictionary than what it was, so it does deserve a little explanation.

When you enter a Key as part of the Key/Value pair, you use something human readable like “ArcaneCode”. While good for people, it’s very inefficient for the computer. Thus the .Net Framework runs your key through a sophisticated algorithm called a “hash”.

The output of this hash algorithm is a number, and that number is what the framework uses for the true key to your data. Thus “ArcaneCode” might produce a hash of 1234. It’s very fast for the computer to find your data when it can compare numbers, hence the usefulness of a hash.

The pseudo code below shows the general process a hash table goes through when retrieving your data.

  1. Key is passed in.
  2. Key is converted to a hash.
  3. The collection is searched for a matching hash.
  4. If found, the value in the dictionary associated with the hashed key is returned.

Hashes are unique, no two strings will ever yield the same hash value. Additionally, they are case sensitive. “ArcaneCode”, “ARCANECODE”, “arcanecode” and “aRCANEcODE” all produce different hash values.

The concept of hash tables are not unique to the .Net Framework, many languages have them, it’s just .Net hides the ugliness and makes them easy to use.

Dictionaries in C#: The Hashtable

About a week ago I began talking about collections in C#, and discussed two special cases, the Stack and the Queue. Another group of specialized collection classes are dictionaries. Dictionaries operate off of a key / value system, where you lookup your information, your value, based on a key you create. The key can be a string, number or other type of data, but it must be unique within the dictionary. Just like in your traditional printed dictionary, you can’t have two entries for the same key.

The most basic type of Dictionary is the Hashtable. The hashtable has the basic functionality for putting entries into the dictionary collection, getting a value based on a key, looping through them, and updating or removing them.

Getting data into the hashtable is pretty easy. First make sure to include a using reference to System.Collections, then simply create a hashtable variable, and finally call the Add method, passing in the key and value.  

      Hashtable myHash = new Hashtable();

 

      myHash.Add(“ArcaneCode”, “arcanecode.wordpress.com”);

 

To read or update the data stored in the value, you can treat the hashtable as if it were a simple array, using the key where you’d normally put the index.

 

      Console.WriteLine(myHash[“ArcaneCode”]);

      myHash[“ArcaneCode”] = “Here I’ve changed the value.”;

      Console.WriteLine(myHash[“ArcaneCode”]);

 

      Console.Read();

 

Hashtables are great for storing data where you have a good primary key you can quickly reference things by. In our example, I’ve stored strings as the value part of the key / value pair, but you can use any type of object for the value, including classes you create.

The examples so far assume you will always want to retrieve a single item out of your hashtable. However, we all know there are times when you will want to iterate over the entire collection. To do this, it’s necessary to understand how your key / value pair is storied.

In keeping with the spirit of OOP, what is actually stored in the hashtable collection is another object of type DictionaryEntry. The dictionary entry object has two essential properties, the Key and the Value, both of which are the generic object type. Here’s an example of how to loop over the myHash collection.

      // Clear out the previous items

      myHash.Clear();

 

      // Now add some new items.

      // Note we use an int as the key this time.

      myHash.Add(1, “Item one”);

      myHash.Add(2, “Item two”);

      myHash.Add(3, “Item three”);

 

      // Loop over the list, writing out the value

      foreach (DictionaryEntry myEntry in myHash)

      {

        Console.WriteLine(myEntry.Value);

      }

 

      Console.Read(); // Wait for user to press a key

 

Note we cycle through a list of DictionaryEntry objects, and each time through get the Value property. If we wanted to get the key, it would be a simple matter of replacing the Value property call with a call to Key.

If you are in a situation where you are not sure of the data types being used in the keys or the values, you should append a .ToString() after a reference to the Key or Value so as not to generate run time errors when displaying. In the above example, we’d have needed to use Console.WriteLine(myEntry.Key.ToString()); since our keys were integers (1, 2, and 3).

As you can see, the hashtable makes it easy to look up values when you have a specific key, yet at the same time is still flexible enough to allow you to iterate over your entire collection when you need to.

Collections in C# – The Stack

Yesterday we looked at the Queue class. The queue is used when you need a first in, first out (FIFO) way to read through your collection. Sometimes though you need to read so that the first item you retrieve is the most recently added item, much like the computer’s stack, or a Pez candy dispenser (http://www.pez.com).

With the stack class, the most recently added item is the first one you pull out. Stacks have a count property and peek method, much like it’s cousin the queue. However, the stack uses push and pop to get items on and off the stack. Let’s take a look.  

      Stack myStack = new Stack();

      myStack.Push(“1. Carl Franklin”);

      myStack.Push(“2. Richard Campbell”);

      myStack.Push(“3. Mark Miller”);

      myStack.Push(“4. Kimberly Tripp”);

      myStack.Push(“5. Billy Hollis”);

 

      while (myStack.Count > 0)

      {

        Console.WriteLine(myStack.Pop());

      }

      Console.ReadLine();

 

[Picture of Stack Output Example 1]

 

As you can see, the pop operation removed the items from the collection in the reverse order from which they were loaded. In other words, the last item on is the first one you’ll be pulling off.

The peek method works just like it does with the queue. Modifying the while loop above thusly:  

      while (myStack.Count > 0)

      {

        Console.WriteLine(“Peek: “ + myStack.Peek());

        Console.WriteLine(“Pop : “ + myStack.Pop());

      }

 

Produces this output:

 

[Picture of Stack Output Example 1]

 

Stacks are handy when you want to keep track of objects that need to be handled in the reverse order, say for creating and disposing. Like queues, stacks enforce reading your data in a specific order. Whenever you have a requirement to read in a LIFO order, the stack class will add the extra safety you need to make your applications work as you designed.

Collections in C# – The Queue

Most .Net developers are familiar with the ArrayList collection. The ArrayList has become a stable in most .Net applications, replacing in most cases the array. But did you know there are other types of collections?

This will begin a series discussing some of the other types of collections available in C#, and how to use them. Most are pretty straight forward, it’s just a matter of getting to know them. We’ll start things off with the queue.

A queue is a type of first in – first out, or FIFO collection. Unlike an array list, you must read things in order. Queues are very structured, you can’t go sifting or randomly plucking data out of the middle of the collection. OK, I can see you out there, scratching your head and asking “well why would I want to use a queue if it’s not as flexible as an arraylist?”

In a way you’ve answered your own question. Because queues are very structured, you can ensure that your application (or consumers of your application) can’t violate your intent.

Queue’s are simple, they have a grand total of three methods and one property. The property, Count, is almost self explanatory. It tells you how many items are in the Queue.

To get data into the queue, use the Enqueue method. Using the Dequeue method will return the next item, removing it from the collection. What if you want to see what the next item is, but don’t want to remove it? You can use the final method, Peek. Let’s take a look at a sample, done as a Console application.  

      Queue myQueue = new Queue();

      myQueue.Enqueue(“1. Carl Franklin”);

      myQueue.Enqueue(“2. Richard Campbell”);

      myQueue.Enqueue(“3. Mark Miller”);

      myQueue.Enqueue(“4. Kimberly Tripp”);

      myQueue.Enqueue(“5. Billy Hollis”);

 

      Console.WriteLine(“Count = “ + myQueue.Count.ToString());

      while (myQueue.Count > 0)

      {

        Console.WriteLine(myQueue.Dequeue());

      }

      Console.WriteLine(“Count = “ + myQueue.Count.ToString());

 

      Console.ReadLine();

 

This routine prints the following output to the command window:

[Pic of Queue Output Example 1]

 

As you can see, the Dequeue method returned the items in the same order they were loaded in. There’s really not much to explain, you load objects into the queue using Enqueue (in this case strings), and remove objects using Dequeue.

I also mentioned a Peek method. This allows you to look at the next item without removing it. Here I’ve modified the while loop to first show the next item on the queue using peek, then actually remove it.

 

      while (myQueue.Count > 0)

      {

        Console.WriteLine(“The next DNR person is:” + myQueue.Peek());

        Console.WriteLine(“Dequeuing them……..:” + myQueue.Dequeue());

      }

 

[Pic of Queue Output Example 2]

 

There are several instances where you may want to use a queue over an array list. Perhaps you are processing messages, or are reading through a list where it’s important you read them in order, say a list of transactions from a database. Data that needs to be processed chronologically could be placed on a queue.

Any time you have data that must be processed in the order in which it was loaded, use a queue. The rigidity of the queue will add an extra layer of safety to your application, ensuring data is read in the order in which you intended.

Arcane Thoughts: Designing for Use

Last week I traveled on business, and the hotel I stayed in had some interesting features that got me to pondering the dilemma of design versus usability. In the bathroom the sink looked like a piece of furniture. Four wooden legs held up a black marble table, atop of which was a large white bowl which was in fact the sink.

Visually, this was quite pleasing, the colors worked well, the contours were pleasing to my eye. The issue came when I tried to actually use the area. There was virtually no counter top area to work with. I had a very tiny space to put my contact lens stuff and my shaving kit. Further, there was no place to sit the hand towel while I was scraping my whiskers or putting my eyeballs in. This was a classic case where the builder went with a design that was visually pleasing over one that was usable.

Another conflict I found was the frosted glass that divided the bathroom from the bedroom. Where the frosted glass pane was located, if someone got up during the night to, well you know, and turned on the light, the light would hit right in the face of the person remaining in the bed. (Since I was alone it was a non issue, but if I’d been with my wife it could have been a problem.) In this case it was something with a design that looked good having negative side effects when put into use.

Lest you think I’m all whiny, there were some good points to the place, such as the closet. When I opened the closet door, the light came on. Didn’t have to think about it, didn’t have to fumble for a switch, it just worked. Simple yet very effective and pleasing.

My point on this post is not to complain about hotel rooms but to get you to think about design versus usability when it comes to your applications. How many websites have you been to that were confusing or hard to use, but visually stunning.

A good example of a bad example is Brown University. (http://www.brown.edu/). If you try to put your mouse over a menu item in an area that is collapsed, that area pops up to show a pretty picture. You then have to slide your mouse up to be able to click on the item you were just hovering on a second ago, before the page helpfully slid the menu up to show you a pretty picture you probably don’t care about. Visually, the effect is cool and the page looks nice, but if you are trying to actually click on a menu option it sucks.

On the other hand, let me mention my favorite site, Google (http://www.google.com). Yes, I said Google. It’s simple, not too much being thrown at you, and it’s obvious what I’m supposed to do (type something in and click Search). Like the light in my hotel room’s closet, it just works.

Windows Presentation Foundation (WPF) included in the new .Net 3.0 Framework gives us some powerful new tools for designing beautiful applications. Like all new technologies, this can be a double edged sword. I hope this post gets you to spend some time thinking about the user experience. Be sure the pretty pictures and cool effects don’t actually get in the way of getting the job done. Spend some time actually using your app. Key in data, do searches, etc. In short, be sure your program isn’t so pretty it’s ugly.

IEnumerator in C#

In yesterday’s post I mentioned the IEnumerator interface. To be honest it probably was not the best example to cite for an interface, since it is implemented in a non-standard fashion. However, it’s also the interface you will probably want to implement the most often, so I thought it worth showing you a quick example.

For today’s lesson I will continue to use the Employee example I’ve shown over the last few days. The only change I need to make is to the Employee’s class declaration, for easy coding I want it to have a public scope. In looking back I hadn’t put a scope qualifier on the class declaration, and when you omit a scope the compiler defaults to internal.

  public class Employee : IPersonM, IPersonP

 

Now that’s done, let’s create a class that will hold multiple employees. We’ll call it Employees (plural) and have a method to add employees to it. Internally we’ll store the individual Employee objects in a generic List<T> collection.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  public class Employees

  {

    private List<Employee> _employees = new List<Employee>();

 

    public void AddEmployee(Employee emp)

    {

      _employees.Add(emp);

    }

 

    public IEnumerator<Employee> GetEnumerator()

    {

      foreach (Employee emp in _employees)

      {

        yield return emp;

      }

    }

 

  }

}

 

Before I explain the details, let’s look at how to use the new collection.

 

      Employees myEmployees = new Employees();

 

      Employee emp1 = new Employee();

      emp1.FirstName = “Carl”;

      emp1.Lastname = “Franklin”;

      myEmployees.AddEmployee(emp1);

 

      Employee emp2 = new Employee();

      emp2.FirstName = “Richard”;

      emp2.Lastname = “Campbell”;

      myEmployees.AddEmployee(emp2);

 

      Employee emp3 = new Employee();

      emp3.FirstName = “Mark”;

      emp3.Lastname = “Miller”;

      myEmployees.AddEmployee(emp3);

 

      string everyone = “”;

      foreach (Employee emp in myEmployees)

      {

        everyone += (emp.FullName() + Environment.NewLine);

      }

 

      MessageBox.Show(everyone, “Everyone”);

 

As you can see this is pretty straight forward, it created 3 employee objects and called the AddEmployee method to add them to our collection. The code then enters a foreach loop retrieving each individual Employee object from the collection of Employees.

What makes this work is the IEnumerator interface. By having the Employees class have a GetEnumerator method that returns an IEnumerator, we enable it to be used anywhere that an IEnumerator can be used, such as a foreach loop.

The only other thing to explain would be the new keyword yield. Each time through the loop the yield will exit the loop and return to the calling routine. The next time through the foreach loop, the GetEnumerator picks right back up at the yield statement, and loops to the next item in our internal List.

To your method, he yield keyword is sort of like sleep mode is to the computer. It pauses, then returns control to the calling routine. When you return, you re-enter the routine right where you left off, with all the routines and variables just as you left them. Not unlike powering up your computer again from sleep mode.

What makes this a little different is that the method GetEnumerator is what implements the IEnumerator interface. Normally, interfaces are implemented by the entire class, not just a single method.

While not the best example of a standard interface, it does demonstrate the power of extending an existing .Net interface. In this example it suddenly allowed your class to be used by a foreach loop. Take advantage of the built in .Net interfaces to make your own classes even more powerful and fit into the .Net environment.

More OOP: Interfaces in C#, Part 2

Yesterday I introduced you to Interfaces in C#. There’s a bit more about interfaces I wanted to share. With a normal class, it can only inherit from one base class. However, it can implement multiple interfaces.

By the way, this seems like a good time for a little lesson in terminology. A class inherits from another class, but it implements one or more interfaces.

Let’s look at our IPerson interface from yesterday. For various reasons our architect has decided it should actually be implemented as two interfaces, one with the properties and another with the method. (For demo purposes I left both interfaces in the same file, in real life I would have each in it’s own file.)

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  public interface IPersonP

  {

    string FirstName { get; set;}

    string Lastname { get; set;}

  }

 

  public interface IPersonM

  {

    string FullName();

  }

 

}

 

Now we need to modify our Employee class to implement both methods.

 

  class Employee : IPersonP, IPersonM

 

Notice all it took was separating the interface names with commas. If we were also inheriting from a base class, we would list it first. Yes, you can both inherit from a single base and implement one or more interfaces for a class.

Finally, we need to make a quick update to our ShowName, since the old IPerson has been replaced with an M and P version:  

    private void ShowName(IPersonM per)

    {

      MessageBox.Show(per.FullName(), “ShowName Method”);

    }

 

You need to be careful when designing your interfaces, not to get too focused. In the above example, what if in the ShowName method you need to also access the FirstName property? Can’t do it with the code as it is now since IPersonM knows nothing about those properties. Instead you’d have to pass in an Employee, in which case we’ve limited our functionality. The ShowName would no longer be able to accept a Contractor or Vendor (assuming we ever created them).

So, we know that a good time to use an interface is when you have a base set of properties and methods, but not code, that you wish to share among classes so that you can treat them as the same generic type. What other times might you wish to use interfaces?

In his book Programming .Net Components (http://shrinkster.com/ly6) Juval Lowy has an entire chapter devoted to interface based programming. When writing a class library (i.e. a dll) Mr. Lowy suggests only exposing interfaces. Why? This leaves you totally free to redesign even your base classes.

Even further, Juval advocates placing all of your interfaces into their own class library. Because it’s fairly quick to create interfaces, it allows both the user interface team and the class library team to get to work, both referencing the same interface dll.

A final reason for using interfaces is to extend your class so that it is compatible with items in the .Net Framework. .Net exposes a slew of interface types, and you can implement any of them in your classes.

A common example is the IEnumerator interface. If you were to implement the IEnumerator interface in your class, you could then use your class anywhere you would use an enumerator in .Net, such as in a foreach construct.

Hopefully by now you’ve seen the power of an interface, and will begin using them in your own applications.

More OOP: Interfaces in C#, Part 1

During our discussion on OOP (see my posts for the last few days) one of the key concepts was the base class. The base class was a place where we could put code that would in turn be used by the classes that descend from the base.

The use of the base class allows us to take advantage of polymorphism, the ability to treat a lot of specific child classes as if they were the same less specific, more generic type (the base). Notice a point I made a moment ago. The base class contains code, that will be inherited.

What if you have a situation where you want a common base, but you don’t have any code that will be reusable by it’s descendants? Interfaces step in to fill the need.

One classic example given in every book is the Shape. You never have “a shape”, instead you have rectangles, squares, circles, triangles and more.

An example from the real world might be the concept of lunch. Every day my coworkers and I go out for lunch. Lunch has a common method called Eat, yet the implementation varies depending on the type of food we pick. With Mexican we can eat chips and tacos with our hands. For Oriental we use chopsticks. For Italian, better use that fork. We have the common concept of Eat, but the implementation for each food type is so different we probably won’t be able to share any code.

Implementing an interface in C# is not difficult. Drawing back on our Employee example from the last few days, let’s say in your company you wanted to define a new type called “Person”. You will never have a “Person” object, instead you will always create an Employee, Contractor, Volunteer, and the like. To implement this, let’s create a Person interface.

First, right click on your solution and select Add, New Item, and select Interface from the long list. Set the scope to public.  

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  public interface IPerson

  {

    string FirstName { get; set;}

    string Lastname { get; set;}

    string FullName();

  }

}

 

There’s several areas I need to draw your attention to. First, after public we used the keyword interface. This is the signal to the compiler that this is a declarations only, and has no code.

Next is the name, you see I put the letter I in front of Person. A long standing tradition is to name all of your interfaces with the letter I in front, and it’s a tradition I’d suggest you stick to.

Notice the FirstName and Lastname areas, this is how we declare there will be properties with a get and set. The FullName line is how we specify there will be a method with the name FullName. Note too there is no scope qualifier in front of any of the return types (in this case they are all string). Because this is an interface, all items must have a pubic scope.

Now we need to actually use the interface. Let’s modify our Employee class to implement the Iperson interface. All it takes is a modification to our class declaration.

  class Employee : IPerson

 

Indicating the Employee class will now implement the Iperson interface carries certain connotations. It means we must implement all of the properties and methods the Iperson interface declares. Since we already have FirstName, Lastname, and FullName we are in good shape. However, if we had not we would have to create those properties or methods we were missing.

Now, via polymorphism we can treat the Iperson just as if it were a base class. Let’s modify the ShowName method from yesterday to use an interface instead of a base class.  

    private void ShowName(IPerson per)

    {

      MessageBox.Show(per.FullName(), “ShowName Method”);

    }

 

This now makes the ShowName more functional for us. In the future, if we do implement a Volunteer or Contractor they too could be used in the ShowName method.

Using interfaces will allow you to further extend the power of polymorphism. In addition it gives you a way to create base classes in situations where you have no common code to put in the base.

Tomorrow: More on Interfaces.

 

Object Oriented Programming Pillar #3: Polymorphism

The third plank of OOP is a concept called Polymorphism. In my last post we went over Inheritance. Inheritance allows us to go from something generic, like an Employee, to something more specific, like a Manager or Peon. Polymorphism allows us to go in the reverse direction, treating something specific as something more generic.

Why would you want to do this? In our example, payroll would be a perfect example. Let’s first create our Peon class. We’ll also be using the Manager and Employee classes we have been using over the last few days.  

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  class Peon : Employee

  {

    public Peon(): base()

    {

    }

 

    public override string FullName()

    {

      string retval;

 

      if (base.FirstName.Length > 0)

        retval = base.FirstName.Substring(0, 1) + “. “ + base.Lastname;

      else

        retval = base.FirstName + ” “ + base.Lastname;

 

      return retval;

    }

  }

}

 

As you can see, Peon is pretty simple, I called the base constructor so I wouldn’t wind up homeless (see yesterday’s comments) and overrode the FullName method just because I could.

Now what we want is a routine that will call a method common to every Employee object. Here’s one I whipped up.  

    private void ShowName(Employee emp)

    {

      MessageBox.Show(emp.FullName(), “ShowName Method”);

    }

 

In the real world, we would probably be doing something here like call a “PayEmployee” method. PayEmployee is something we would do for all employees, regardless of whether they are a manager or a peon. For this example I’m just calling the FullName method, since we’ve been using it the last few days. Now we need to create our various objects and pass them to ShowName.

 

      Employee emp1 = new Employee();

      emp1.FirstName = “Carl”;

      emp1.Lastname = “Franklin”;

      this.ShowName(emp1);

 

      Manager mgr1 = new Manager(); 

      mgr1.FirstName = “Richard”;

      mgr1.Lastname = “Campbell”;

      this.ShowName(mgr1);

 

      Peon peon1 = new Peon();

      peon1.FirstName = “Mark”;

      peon1.Lastname = “Miller”;

      this.ShowName(peon1);

 

Here you can see I’ve created one Employee, one Manager, and one Peon object. But I can pass all three of them to the same ShowName method and treat them like Employees. Why? Because they are all descended from (or are) the Employee class. Polymorphism makes all this work.

You should note something very important here. If you actually run the program, you’ll see the following message boxes appear, in this order:

[Pic of Employee FullName]

ShowName with Employee

[Pic of Manager FullName]

ShowName with Manager

[Pic of Peon FullName]

ShowName with Peon

 

Do you see it? Even though within the ShowName method we are treating everything like an Employee, the compiler was smart enough to know they were not all Employees. Instead, it called the overridden method in the child class (Manager and Peon), not the one in the base class. This behavior is very important to understand. On one hand, it’s what makes Polymorphism so powerful, but if you are not expecting it, you can get bit.

Because this can get confusing, let’s see if I can relate this to a real world example. I have a wife and two daughters. Their base class might be “family member”, but their specific classes are wife (Ammie), daughter 1 (Raven) and daughter 2 (Anna).

On days where I might work from home, I can send family member a message (i.e. yell) “get daddy a Jolt cola”. The base implementation is open refrigerator, get soda, bring to daddy (that’s me). My wife Ammie just uses the base implementation of the “get daddy a Jolt cola” method.

My oldest daughter, Raven isn’t quite tall enough to reach the sodas on the top shelf, so she has to override the “get daddy a Jolt cola” method by adding a step to stand on a stool so she can reach them.

My youngest daughter, Anna is even shorter still, so her override calls for her to stand in a chair in order to reach the soda.

Now, in all three cases I simply call the “get daddy a Jolt cola” method of the “family member” object. When the individual object (Ammie, Raven or Anna) executes the “get daddy a Jolt cola” method, they each use their individual implementation to do so.

So where are some situations where Polymorphism would come in handy? Yesterday you may recall I said my classes in my Database Layer (often referred to as the DL) all descend from a common base class.

Within my program then, I can take all of my database objects and pass them into a “CloseConnection” method. The CloseConnection method does what it says, closes any database connections before exiting the program. Because of Polymorphism, it doesn’t matter what type of data object I’m dealing with (Purchase Order, Employee, Work Order, etc) they all need to close, and this lets me do it in an easy, consistent manner that’s easy to update and maintain.

Another real world example: I created a special combo box control to which I added some additional features. My new combo was descended from the standard combo box in the toolbox.

I then turned around and created four new combo boxes from my special base class combo. Each one was bound to a specific type of data, and I used these over and over in my application. Each one though had some common methods, such as Load and Reset.

When my form loaded, I passed each combo box to a method to load them. All this method did was called the load method for each box, and because I’d overridden the load method it called the correct Load for each type of combo box.

Over the last few days I’ve written on the basics behind Object Oriented Programming, using C# to demonstrate. You should understand I’ve only scratched the service as far as power and flexibility go, OOP is a big subject. But hopefully what I’ve discussed here will serve as a starting point for your OOP journey.

Object Oriented Programming Pillar #2: Inheritance

The second pillar of OOP is Inheritance. But if you read the title of today’s blog, you probably already guessed that. Inheritance allows us to both reuse and extend code, plus allow you to easily make changes to a class and have them ripple through to the decedents.

Take a look at the Employee class from yesterday. When I think of employees in a company, I can think of at least two kinds, Managers and Peons (like me). Both are types of employees, but both have some things different. Inheritance allows us to reuse the best parts of employees, but add special functionality as well.

Let’s create a new class, called Manager. Here’s what I coded:

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  class Manager : Employee

  {

    // Constructor, call the base

    public Manager(): base()

    {

    }

 

    // Meaningless work, just like a real manager would do.

    public void MakeHairPointy()

    {

      string myPointyHairOrder = “Write me a program by last week.”;

    }

 

  }

}

 

The first thing you may notice is the : Employee after the class Manager. This tells the compiler that the Manager class is descended from the Employee class. Any methods, properties, and events available in the Employee class are now automatically available in the Manager class.

Next you see a line that says public Manager(). This is the constructor for the class. In here you can put code that you want to execute when the class is created. Perhaps this is setting some defaults for class variables, creating other classes, or a variety of other items. I don’t need to do anything, so I’ve just left it blank.

After the Manager() you see the : base() construct. This tells the compiler “hey, before you run the constructor in Manger, go run the constructor in your base class, employee, then come back and run the Manager’s constructor”. Even though I don’t currently have any code in Employee’s constructor, one day I might. Plus if I’m following good encapsulation then I don’t know whether or not Employee has a constructor, nor do I care.

Using the base() keyword is not only common practice but a good idea. If you don’t, you’ll likely wind up on the side of the road, homeless holding a sign that reads “Will code() for food;”.

Enough on constructors, let’s look at a sample that uses our new Manager class.  

      Manager mgr1 = new Manager();  //Constructor runs here!

      mgr1.FirstName = “Arcane”;

      mgr1.Lastname = “Code”;

      mgr1.MakeHairPointy();

      MessageBox.Show(mgr1.FullName(), “Manager FullName Dialog”);

Even though you won’t find them in the code for the Manager class, you see I am calling FirstName, LastName, properties and the FullName method. The Manager inherited these from Employee.

Imagine you had not one or two types of employees, but fifty? Then imagine your boss wanted you to make a change to the FirstName property, so that if the length were only one character it automatically put a period at the end of the first name? Now you begin to see the power of inheritance.

You make your change to the Employee class, which is known as the base class. Recompile, and you are done. That change is automatically reflected in all of the child classes that inherit from the base Employee class.

What if you have a situation where you want to implement something in the base class in a slightly different way? You have the power to override the base classes implementation of that method. That’s a fancy way of saying you can create a method with the same name in your descended class, with your new code. But there’s a big “if” you need to know about. (Isn’t there always?)

When you create a method in a base class, you must use the virtual keyword in the method declaration. This flags the compiler that it’s OK to override in child classes. Without the virtual keyword, the compiler will produce errors and fail. So let’s fix our employee classes FullName method so we can override it later.  

    public virtual string FullName()

    {

      string returnValue;

      returnValue = _firstname + ” “ + _lastname;

      return returnValue;

    }

 

All that was really needed was to slip the virtual keyword between the scope and the return type. Now we are ready to rewrite this method in our Manager class. 

 

    public override string FullName()

    {

      return “Oh great one “ + base.FirstName + ” “ + base.Lastname;

    }

 

Now when I run my code, I will see the rewritten FullName for the manager appear.

 

[OOP Demo 2 Picture]

 

Note too the use of the base.FirstName and base.LastName. Through the keyword base, you can access any of the non-private properties and methods of the base class. I could just have easily have done:

 

    public override string FullName()

    {

      return “Oh great one “ + base.FullName();

    }

 

If you take some time to plan your code architecture (see my post https://arcanecode.wordpress.com/2007/02/07/arcane-thoughts-the-passion-of-the-programmer/ or http://shrinkster.com/lvw) you can probably come up with many good relationships where you can go from abstract to something more concrete.

A real world example, in my database layer I descend all data handling classes from a base class that has common properties / methods such as the connection string and a connection object. This lets me write the connection “goo” once and use it over and over.

Don’t forget that at their heart, forms and toolbox items are classes as well, and you can inherit from them. A common technique is to override all of the common controls and use your version in your applications. The technique is slightly different so I will defer discussion on inheriting graphical stuff until another day.

A classic story I heard on DotNetRocks (http://www.dotnetrocks.com) is the lead developer who gets a call three days before their 300 form application is due to go to production. “Oh by the way” says the customer, “we forgot to mention it but it’s a requirement that all text boxes force their letters to uppercase.”

Even though they had not tweaked the text boxes previously, they had still made a decision lo those many months ago to inherit from the base text box and use the new one in their project. Because of that, they made a quick change to one routine in their custom text box, and all 300 forms were fixed in less than half an hour.

Inheritance can be an incredibly powerful tool when used correctly, but as my favorite hero Spider-Man used to say, “with great power comes great responsibility”. Make sure your inheritance chain is well thought out, lest you feel trapped in a spider’s web of your own making.

Object Oriented Programming Pillar #1: Encapsulation

I was working with an IT person who was new to .Net and Object Oriented Programming (OOP). Since these were new concepts to my coworker, I thought they might be new to others as well and as such thought it’d be a good idea to spend a little time discussing them.

OOP has three basic concepts: Encapsulation, Inheritance, and Polymorphism. Let’s start today by going over the first, encapsulation. Encapsulation is a little like Las Vegas. What happens in a class, stays in a class.

Instead of reading the word encapsulation, instead substitute “self contained”. Your classes should be like a little black box. You can rewire the inside all you want, as long as the end results to the outside world look the same. Let’s look at an example, a simplified version of the classic employee class.

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  class Employee

  {

    private string _firstname;

    private string _lastname;

 

    public string FirstName

    {

      get

      {

        return _firstname;

      }

      set

      {

        _firstname = value;

      }

    }

 

    public string Lastname

    {

      get

      {

        return _lastname;

      }

      set

      {

        _lastname = value;

      }

    }

 

    public string FullName()

    {

      return _firstname + ” “ + _lastname;

    }

  }

}

 

I’ve kept it very simple, two properties and one method, FullName. Here’s a simple example of creating (aka instantiating) an employee object out of the employee class, loading it’s properties, then calling the FullName method.

 

      Employee emp1 = new Employee();

      emp1.FirstName = “Arcane”;

      emp1.Lastname = “Code”;

      MessageBox.Show(emp1.FullName(), “FullName Dialog”);

 

Now let’s suppose, for whatever reason we need to rewrite the FullName method. In my example, we’ll pretend like a new coding standard has emerged that says you can never return a calculated value (like we did in the first write) but instead place it into a variable before returning it. This allows us to view the final result in the method quite easily.

We can do so, without having to change the routine (above) that called it. Here’s a new version of FullName.

 

    public string FullName()

    {

      string returnValue;

      returnValue = _firstname + ” “ + _lastname;

      return returnValue;

    }

 

When you run the application again, it still works. The routine that creates the emp1 object doesn’t know, and doesn’t care how you wrote the FullName routine. As long as you don’t change the method’s signature, you are free to rewrite FullName to your hearts content. That’s the beauty of encapsulation.

Arcane Thoughts: The Passion of the Programmer

One of my favorite bloggers is Jeff Atwood, and his Coding Horrors blog (http://www.codinghorror.com/blog/). Why? He’s passionate not just for code, but for coding.

I see a lot of people who are good at writing code. They know the syntax, can knock out some code, and get the application completed. Then there are people like Atwood, Steve McConnell, Paul Sheriff or Carl Franklin. These guys are passionate about the process of writing code.

When I speak of process, I’m talking about more than just writing, but the design of the code, how much reuse can you achieve from your existing components, do you do test driven development, waterfall, how often do you have code reviews, and more. This is the stuff that doesn’t help you write code, it helps you write better code.

Yesterday I had a root canal. I spent more than three hours in the dentists chair. Since there wasn’t much opportunity for stimulating conversation, I brought along my PDA and listened to some old DotNetRocks (http://www.dotnetrocks.com) episodes. In one of the episodes (http://www.dotnetrocks.com/default.aspx?showNum=104) Carl and Richard were interviewing Paul Sheriff on architecture.

During this episode, somewhere between the root canal and fitting a new crown, I realized that the coders who are passionate tend to also be architects, whether they realize it or not. They care about things like code reuse, good design, and adhering to standards.

If you are interested in learning more about architecture, I would recommend taking a look at the Patterns and Practices libraries at Microsoft. (http://msdn.microsoft.com/practices/). This is a collection of tools, e-books, and articles designed to not only recommend ways to architect your code, but the tools to get it done. Be sure to check out the “Getting Started” link on the upper left, it’s a good place get started on the road to not getting the job done, but getting the job done right.

VS Add-In: Oracle Developer Tools for Visual Studio.Net

I found a useful and important add-in for those who deal with Oracle databases using Visual Studio. Oracle Developer Tools for Visual Studio.Net. ODT for VS adds an Oracle Explorer, similar to the Data Explorer built in to VS. It has an incredible amount of functionality built in.

I already mentioned the Oracle Explorer, which gives you a tree that lets you examine your tables (and columns), views, stored procedures, packages, sequences, and all of the other objects Oracle supports.

There’s a plethora of designers and wizards that will allow you to create and alter the aforementioned objects. They work by generating SQL that you can preview before it’s applied.

The feature I find most useful is the PL/SQL editor. Right inside VS I can now write my stored procedures. But what’s really powerful is I can set a breakpoint, and step from my VB.Net or C# code right into the stored procedure, step through the stored procedure, then back into my application. THAT is useful.

You can obtain ODT for VS directly from Oracle, at no cost. http://www.oracle.com/technology/tech/dotnet/tools/index.html or http://shrinkster.com/lry.

I did run into one issue after the install. Oracle installs it’s ODP driver and creates a new Oracle home for your machine. In order to make the connections I had to copy my tnsnames.ora, ldap.ora, and sqlnet.ora files from my old oracle home to the one for 10.2, by default it’s in C:\oracle\product\10.2.0\client_1\network\ADMIN. I found this solution and some other interesting tidbits at the FAQ: http://www.oracle.com/technology/tech/dotnet/col/odt_faq.html or http://shrinkster.com/ls0.    

I’m not going to regurgitate a lot of how to here, instead I’ll refer you to a good article on the Oracle site, at http://www.oracle.com/technology/oramag/oracle/06-sep/o56odp.html or http://shrinkster.com/lrz. This article has the basics to get you up and running.

If you work with Oracle databases, this is a must have add-on for your Visual Studio environment.

Delegates Made Easy in C#

During my discussion of SQL Server Compact Edition, I mentioned Delegates. I thought I’d take a moment to cover what a delegate is, and how you can effectively use them in your application.

Let’s say you send an employee to the mall, and tell him “OK, when you get to the mall I will tell you which store to go in, because right now I haven’t decided yet.” A delegate is somewhat like that. You can tell your application that you are going to call a method with a certain signature, but you will tell it the name of the method at run time instead of compile time. (The signature, in case you haven’t heard the term, is the name and return type of the method plus the list of the data types of the parameters you pass.)

Let’s create a simple example. Create a new windows form app. Put on a label, a text box, and two buttons. When done, it should look something like this:

Now add a class, and name it “TheDoSomethingClass”. Once it’s created, we’ll need to put a declaration at the class level:  

    public delegate void DoDelegate(string msg);

 

We are creating a new variable type called DoDelegate. It’s descended from a Delegate, and has one parameter. It has to be pubic, so we can later create a variable of the DoDelegate type.

Next, we’ll add one method to the class, and pass in our delegate type.  

    public void DoSomething(DoDelegate doit)

    {

      for(int i=0; i < 3000;i++)

      if (doit != null)

      {

        doit(“Count=” + i.ToString());

      }

    }

 

This method has one parameter, “doit”. Notice that doit is of type DoDelegate. I created a little loop, just so we can see some action. Next, I check to see if the doit variable is null. This is very important, traditionally a delegate is never required but optional for use in your class. Thus you should always check to see if it’s null before attempting to use it. In the next line we actually call the doit method, and pass in it’s parameter, in this case a single string.

Now let’s look at how to use our delegate. Let’s return to our form, and add a new method. This method will be called ShowInLabel, accept a single string which it will display in the label control. I also added a DoEvents, just to get the label to update immediately.  

    private void ShowInLabel(string theMessage)

    {

      label1.Text = theMessage;

      Application.DoEvents();

    }

Now for the final step which ties everything together. In the click event for the button next to the label, we need to add two lines of code. The first line will instantiate a new object from our TheDoSomethingClass class. The second line will call the DoSomething method.  

    private void btnLabel_Click(object sender, EventArgs e)

    {

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      dsc.DoSomething(

         new TheDoSomethingClass.DoDelegate(ShowInLabel));

    }

 

Notice something important: in the second line we create a new variable of type DoDelegate. Perhaps if I do it in 3 lines it will make it slightly clearer.

 

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      TheDoSomethingClass.DoDelegate myNewDoDelegate

        = new TheDoSomethingClass.DoDelegate(ShowInLabel);

      dsc.DoSomething(myNewDoDelegate);

 

As part of the constructor, we pass it the name of a method that has the same signature as the delegate. In this case, ShowInLabel has the same signature (one parameter, a string) as the delegate was declared with. The Delegate’s signature and the signature of the method you want to assign to it must match or you’ll get an error.

Now let’s flex our power a little. Create another method with a different name, but the same signature. This one we’ll call ShowInTextBox, and like the other we have to have one string as a parameter. In this method we will update the text box instead of the label with the passed in message.  

    private void ShowInTextBox(string theMessage)

    {

      textBox1.Text = theMessage;

      Application.DoEvents();

    }

Now in the click event for the button associated with the text box, we’ll repeat the code from the other button with one exception. In the constructor, we’ll pass in the name of the new method.  

    private void btnTextBox_Click(object sender, EventArgs e)

    {

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      dsc.DoSomething(

        new TheDoSomethingClass.DoDelegate(ShowInTextBox));

    }

DoDelegate method what so ever, yet it was able to call a completely different method.

You can also store the delegate, in case you want to use it for several methods in your class, or manipulate it a bit easier. Put this code in your class (note I squished down the get/set to save a bit of space, I don’t normally code that ugly.) I added a private variable to hold our delegate, a property get / setter, and a new method that will take advantage of it.  

    private DoDelegate _TheDelegate;

 

    public DoDelegate TheDelegate

    {

      get

      { return _TheDelegate; }

      set

      { _TheDelegate = value; }

    }

 

    public void DoSomethingElse()

    {

      for (int i = 0; i < 3000; i++)

        if (_TheDelegate != null)

        {

          _TheDelegate(“Count=” + i.ToString());

        }

    }

Now to call it, all we have to do is go back to our form and add this code to a button click event:

      TheDoSomethingClass dsc = new TheDoSomethingClass();

      dsc.TheDelegate

        = new TheDoSomethingClass.DoDelegate(ShowInLabel);

      dsc.DoSomethingElse();

      dsc.TheDelegate

        = new TheDoSomethingClass.DoDelegate(ShowInTextBox);

      dsc.DoSomethingElse();

Note here I changed the delegate between calls, I could have also coded more methods that used the same call. Also note if I had tried calling DoSomethingElse before assigning a delegate, the program would have run just fine I just wouldn’t have been shown any messages, thanks to the if ( _TheDelegate != null) statement.

Now that I’ve shown you how a delegate works, let’s take a moment to discuss some times when you might want to use it. The first example I can think of is to support an add in architecture. You can dynamically load DLLs at run time, and when you do you can query it to see if it supports a certain delegate type, perhaps one for communicating a message like our example. If so, you can assign that delegate to the message handler for your particular app. Not only does this mean you can use multiple add-ins with the same app, it also means you could support multiple apps with one add-in.

Here’s another example from my personal experiences. I have a winforms app that can connect to multiple database. (Each of our sites has it’s own database.) Most users only need to connect to one, so I save the database they were last connected to in the settings file. When the user reloads the app, I reconnect to the same database.

When my app loads, there are a lot of lists of values I retrieve to populate drop down combos. During load, however the only form visible is my splash screen. Using delegates in my load routine I have all progress messages from my data layer displayed on the splash screen.

During the course of using my program, the user can choose to hook to a different site, and hence a different database, which means I have to reload all those lists of values again. This time though, I don’t have the splash screen up. True, I could show it again, but it would look really goofy.

Instead, in my load routine I instead pass a delegate to the data layer that instead will display progress messages on the status bar control at the bottom of the form.

The beauty of this is that the data layer has no clue where or if it is displaying messages, nor should it have to care. I can also reuse this data layer DLL in other apps down the road, should the need arise, and take advantage of the status messages it provides.

In my example I have kept it simple and used a single parameter for my delegate. Know that you are not restricted; you can use multiple parameters if you wish. The important thing to remember is your signatures must match. The return type and number of parameters for your delegate (DoDelegate) must match the signature of the methods you assign to it (ShowInLabel, ShowInTextBox).

When designing your classes, especially those destined for DLL libraries that could get multiple use, consider adding some delegates as a way to inform your consumer of the progress of your methods.

There you go, a short step by step for delegates in C#. If you think of some new uses for delegates, drop a comment and let us know.

Loading a SQL Server Compact Edition Table From a DataTable in C#

Of all the situations you can be in using SSCE, I think one of the most common will be to pull data from a larger database provider and populate a table in your local SSCE database. While SSCE does have some nifty replication support, it only works with SQL Server. Like many of you I have to support data coming from many different places, such as Oracle, Access, and XML to name but a few.

The easiest way to pull the data is to get it into an ADO.Net DataTable, but what then? I sure didn’t want to have to create the insert statements by hand each time, plus I wanted to be able to reuse my routines. Being a lazy individual, I wanted a routine I could pass any DataTable into and push the data into my SSCE table.

I started with a blank class, and created a few class level variables. One was out of a SqlCeConnection which I named _connection. I also had two strings to hold the database name and password. Next, I created a “ConnectionString” method, identical to what I described a few days ago.

    private string ConnectionString()

    {

      return string.Format(

        “DataSource=\”{0}\”; Password='{1}'”

        , this._CacheDatabase

        , this._Password);

    }

 

I then created an Open method, which is pretty simple:

 

    public void Open()

    {

      if (_connection == null)

        _connection = new SqlCeConnection(this.ConnectionString());

 

      if (_connection.State == ConnectionState.Closed)

        _connection.Open();

    }

 

OK, now for the grand finale.

 

 

    public void Populate(DataTable myDataTable

      , string tableName)

    {

      // If the datatable has no rows, we’re wasting

      // our time, get outta dodge.

      if (myDataTable.Rows.Count == 0)

      {

        return;

      }

 

      // Make sure database is open for business

      this.Open();

 

      // Use a string builder to hold our insert clause

      StringBuilder sql = new StringBuilder();

      sql.Append(“insert into “ + tableName + ” (“);

 

      // Two more, one for the list of field names,

      // the other for the list of parameters

      StringBuilder fields = new StringBuilder();

      StringBuilder parameters = new StringBuilder();

 

      // This cycles thru each column in the datatable,

      // and gets it’s name. It then uses the column name

      // for the list of fields, and the column name in

      // all lower case for the parameters

      foreach (DataColumn col in myDataTable.Columns)

      {

        fields.Append(col.ColumnName);

        parameters.Append(“@” + col.ColumnName.ToLower());

 

        if (col.ColumnName !=

          myDataTable.Columns[myDataTable.Columns.Count

                 – 1].ColumnName)

        {

          fields.Append(“, “);

          parameters.Append(“, “);

        }

      }

      sql.Append(fields.ToString() + “) “);

      sql.Append(“values (“);

      sql.Append(parameters.ToString() + “) “);

 

      // We now have our Insert statement generated.

      // At this point we are ready to go through

      // each row and add it to our SSCE table.

      int rowCnt = 0;

      string totalRows = myDataTable.Rows.Count.ToString();

 

      foreach (DataRow row in myDataTable.Rows)

      {

        SqlCeCommand cmd

          = new SqlCeCommand(sql.ToString(), _connection);

 

        foreach (DataColumn col in myDataTable.Columns)

        {

          cmd.Parameters.AddWithValue(“@”

            + col.ColumnName.ToLower()

            , row[col.ColumnName]);

        }

        // Optional: I created a delegate called message delegate,

        // and assign it to the class level variable Cachemessage

        // It’s a simple method that takes one string and displays

        // the results in a status bar. If you want to simplify

        // things, just remove this entire section (down to

        // the try).

        rowCnt++;

        if (_CacheMessage != null)

        {

          if ((rowCnt % 100) == 0)

            _CacheMessage(“Loading “ + tableName

              + ” Row “ + rowCnt.ToString()

              + ” of “ + totalRows);

        }

 

        try

        {

          // Here’s where all the action is

          // sports racers! This is what sends

          // our insert statement to our local table.

          cmd.ExecuteNonQuery();

        }

        catch (Exception ex)

        {

          // You’ll probably want to be a bit more

          // elegant here, but for an example it’ll do.

          throw ex;

        } 

      } 

    }

 

My code comments elaborate pretty well on what’s going on, a quick read should be all you need. Only two things to really point out. First, I create a delegate to send a progress message. I’ll go into more on delegates another day, if need be, there’s a ton of info on them out on the web. Let me show you the declarations I used for my delegates so you can repeat them in your class:

 

    private CacheMessageHandler _CacheMessage;

 

    public void Messenger(CacheMessageHandler messageRoutine)

    {

      _CacheMessage = messageRoutine;

    }

 

I created a method in the calling program called ShowStatus. Very simple, takes one string as a parameter and displays it somewhere to the user. (I chose a status bar, you might use a label). All I had to do was call the Messenger method like so: 

    myMethod.Messenger(

         new MyClass.CacheMessageHandler(ShowStatus))

 

In retrospect I could also have created a CacheMessage property, I just didn’t think of it at the time. If you paste in the declarations you should be able to use the method even though you never use the delegate (note I check to see if _CacheMessage is null) but if you have issues, just delete that small section, it’s not that important to the process of loading the table.

The other major thing, and a gold star to you if you already noticed this: in order for this method to work, the column names in your DataTable must match exactly with the column names in your SSCE table!

Personally this seems like a small price to pay, and frankly if you are replicating data it will make your debugging and programming life much easier as you work through bugs. I do this as a standard, which is why this kind of routine fits well into my environment.

This wraps up (for now) my exploration of SQL Server Compact Edition. If you have decided to leverage SSCE in your own apps, please leave a comment, let us all know what your experiences have been, problems, benefits, and the like.