Category Archives: C#

Getting Ready for Code Camp

This week I’ll be working toward the Alabama Code Camp to be held in Mobile this Saturday, April 14th. (http://alabamacodecamp.com) I will be giving a presentation on SQL Server Compact Edition, and invite you all to come.

Since my previous SSCE posts were a bit back and a little scattered, I thought I’d start with a quick recap of my SSCE to date.

My first post described the background of SSCE, and where to get it from. You can find it at:

http://shrinkster.com/nsk

My second post described how to create a new SSCE database using code. You can find this post at:

http://shrinkster.com/nsl

The third post showed how to create a new table in your database, and can be located at:

http://shrinkster.com/nsm

My next post showed you how to insert rows into the newly created table:

http://shrinkster.com/nsn

And finally is my piece on loading a SSCE table from a standard DataTable object:

http://shrinkster.com/nso

That ought to get you up to speed, stay tuned this week as I build up to the weekend presentation.

Arcane Solutions: A Data Warehouse

Tomorrow I’m doing a presentation for Microsoft, in conjunction with the vendor that we outsourced the project with, CTS (http://askcts.com). Our solution for the data warehouse was pretty cool, and I thought I’d briefly mention the technologies involved.

A SQL Server Integration Services solution reads data from our Oracle transaction system, and places the data into a SQL Server 2005 warehouse. This SSIS job runs every fifteen minutes, in what we call a “right time” scenario.

Next, the users first go to a SharePoint portal site. We have a master site for the company, the sub sites for each plant, then within those for each department. Our SharePoint site holds some report viewer SharePoint web parts, which hold SQL Server Reporting Services reports that act as our KPI (Key Performance Indicator) reports.

Also on the page is a special SharePoint web part we custom wrote in C# using the .Net 1.1 framework. This part reads a list of valid reports from a SQL Server 2005 table, then launches an ASP.Net 2.0 site.

The ASP.Net page, written in C# on the 2.0 framework, primarily houses a Microsoft report viewer control. It also has a drop down combo which holds a list of saved queries. These allow users to quickly pick combinations of stored report filters to apply to the reports.

We’ve also given users the ability to create ad-hoc reports by linking in the Report Builder control that’s part of the SQL Server 2005 suite. This lets the users create their own reports, without the necessity of providing ODBC connection info as we would with say Access.

I certainly don’t think Microsoft is perfect, as I’ve written before they certainly have room in some areas for improvement. But when it comes to their business applications, they are outstanding. I don’t know of any other company that puts out a suite of tools that integrate so nicely together, and provide the users such a complete, seamless solution.

Encoding Strings to Base64 in C#

I recently had the need to convert simple strings back and forth from Base64 encoding. It turned out to be relatively simple in .Net, once you figured out which class libraries you needed to combine.

It turns out the System.Convert has two handy methods for dealing with Base64, ToBase64String and FromBase64String. On the ToBase64String, we have a bit of a challenge, since it expects a byte array and not a string to be passed in.

It does make a certain amount of sense, typically you aren’t encoding a simple string but instead a binary object such as a file, which is usually represented as an array of bytes. For us, this means we have to take our string and convert it to a byte array.

You’d think the string class would have a nice static method to handle this, but alas it does not. Instead we have to turn to System.Text. I imagine most of you are working with ASCII encoding, so here we’ll call on the ASCIIEncoding.ASCIII class, and use it’s GetBytes to convert a string to bytes.

The small method below combines the two methods I’ve described to create a Base64 encoded string from a normal string.

    static public string EncodeTo64(string toEncode)

    {

      byte[] toEncodeAsBytes

            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);

      string returnValue

            = System.Convert.ToBase64String(toEncodeAsBytes);

      return returnValue;

    }

 

Note two things, first I am using ASCII encoding, which should cover most folks. Just in case though, System.Text has encodings for the various flavors of UTF as well as Unicode. Just choose the appropriate encoding method for your need.

Second, I made the class static because I was using a console app for my test harness. While it could be static in your class, there’s no reason it has to be. Your choice.

OK, we’ve got the string encoded, at some point we’re going to want to decode it. We essentially do the reverse of encoding, we call the FromBase64String and pass in our encoded string, which returns a byte array. We then call the AsciiEncoding GetString to convert our byte array to a string. Here’s a small method to Decode your Base64 strings.

    static public string DecodeFrom64(string encodedData)

    {

      byte[] encodedDataAsBytes

          = System.Convert.FromBase64String(encodedData);

      string returnValue =

         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

      return returnValue;

    }

 

Finally, here’s a simple test harness, done in a console app, to show you calls to the two methods.

 

      string myData = “Here is a string to encode.”;

 

      string myDataEncoded = EncodeTo64(myData);

      Console.WriteLine(myDataEncoded);

 

      string myDataUnencoded = DecodeFrom64(myDataEncoded);

      Console.WriteLine(myDataUnencoded);

 

      Console.ReadLine();

 

Be aware, I’ve done no error checking here. My little methods assume that the data you are decoding will properly convert to and from a string. If that’s not the case you could wind up with a serious case of gibberish, if not cause a run time exception. If you are not positive that all you are dealing with is simple strings, then make effort to include some try / catch logic in your implementation.

Arcane Education: Alabama Code Camp IV

Yes, it’s spring time, when the flowers are in bloom, and a young man’s fancy turns to… .NET!

Alabama Code Camp IV is coming up quick, April 14th is just a few short weeks away. For those in the south-east, this one will be held in Mobile AL. See all the details at:

http://www.alabamacodecamp.com/

If this is anything like the previous ones it’ll be great, tons of great speakers and lots of good swag. If you have never been to Mobile before, there’s a lot to see and do. My family is coming along and we’re going to make a weekend of it.

Top on my list (after code camp of course) is seeing the USS Alabama (http://www.ussalabama.com/), a WW II Battleship. At the same location they have the USS Drum, a submarine, a B52, an A-12 Blackbird, and tons of other exhibits.

If battleships aren’t your thing, Mobile is loaded with opportunities, check out Yahoo’s top 16 list at http://travel.yahoo.com/p-travelguide-2833565-mobile_things_to_do-i,  or the Mobile city guide on AL.com (http://www.al.com/mobile/cityguide/index.ssf?attractions.html).

And for the beach goers, Orange Beach is right next door to Mobile (literally). Check out the fun in the Gulf of Mexico at http://www.gulfshores.com/things-to-do/attractions/.

So there you go, a whole day of geeky fun for you, and plenty of ways for the family to be out spending your money, oops I mean having fun while you are getting an education. Well, at least Code Camp is free!

So quit sitting on your duff and start making plans today!

Dictionaries in C#: OrderedDictionary

There are times in life when you’d like to have your cake and eat it too. With a hashtable, this means there are times when you want to use the keys to look things up, or iterate in a foreach using DictionaryEntry objects. There are other times though when it would be easiest to treat the collection as if it were an array, using a traditional for(int i=0; … type syntax.

The OrderedDictionary is what lets you have the best of both worlds. Using it, you can perform specific actions at a numeric index in the collection, or you can use the Dictionary Entry style of looping over the collection. Like the other specialized dictionaries I’ve mentioned in the latter part of this week, you will need a using System.Collections.Specialized reference.

Let’s take a look at an example.

      OrderedDictionary myOD = new OrderedDictionary();

 

      myOD.Add(“01”, “First”);

      myOD.Add(“02”, “Second”);

      myOD.Add(“03”, “Third”);

      myOD.Add(“04”, “Fourth”);

      myOD.Add(“05”, “Fifth”);

 

      // Reference the values array style

      for (int i = 0; i < myOD.Count; i++)

      {

        // Create a strongly typed variable to hold the

        // generic object in myOD[], then do a cast

        string valueString = (string) myOD[i];

        Console.WriteLine(valueString);

      }

 

      // Reference the values Dictionary style

      foreach(DictionaryEntry myDE in myOD)

      {

        Console.WriteLine(myDE.Value);

      }

 

Above you can see I used two different methods to iterate over my collection. In the first example, I used a for loop and a numeric index to retrieve each object (in this case a string) stored in the collection. Using a cast I convert it from the generic object type into a more strongly typed variable.

While it’s true I simply could have used Console.WriteLine(myOD[i].ToString()), you will not always be dealing with string data in your value. This example demonstrates how to do a simple conversion.

In the second loop, you can see code similar to what has been shown all week, using a DictionaryEntry object to iterate over the collection.

The other advantage to an OrderedDictionary is speed. When going over a large collection, reading the OrderedDictionary using the first example, the numeric index, is always going to be faster than using the dictionary style method.

When you need both the power of a collection, and the simple access of a numeric index, the OrderedDictionary is the collection of choice.

Dictionaries in C#: The HybridDictionary

So far we’ve looked at the HashTable collection, and determined that it’s the way to go for large collections. We’ve also taken a look at the ListDictionary, which is geared towards very small collections. But what if you don’t know how big your collection will be?

There are many situations where at design time you simply can not know what the final size of your collection will be. Sometimes it will depend on user input, what range of data the user selects for example. Other times it may be dependant on the data, how much is out there for you to use. There’s enough uncertainty in all our lives to get stressed out, so to keep us calm Microsoft has provided the HybridDictionary collection.

A HybridDictionary will self monitor itself. Initially, and while it remains small the HybridDictionary will internally keep itself as a ListDictionary. Once it exceeds a certain threshold, it will then convert it’s data into a HashTable. The nice part is you don’t have to care when, or what state it is currently in. All you have to know is the HybridDictionary is managing the memory most efficiently on your behalf.

Like it’s sibling the ListDictionary, the HybridDictionary will require a using System.Collections.Specialized reference. After that, it has the same interface as the HashTable and can be treated as such.

      HybridDictionary genders = new HybridDictionary();

 

      genders.Add(“M”, “Male”);

      genders.Add(“F”, “Female”);

 

The question many will ask “well why not just use a HybridDictionary all the time?” As with most things in life, there is a trade off. There is a some overhead associated with HybridDictionaries, as they have to constantly monitor their own size, then convert back and forth between ListDictionaries and HashTables as needed. In return, you get the best possible performance from your collection as it changes in size.

The moral of the story, when you know you have a small collection, use a ListDictionary. On the other hand, if you know with certainty your collection will be large, use a HashTable. But for all those other times when you just don’t know, the HybridDictionary is your answer.

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.

Arcane Searches

I thought it was time for another round of Arcane Searches. In case you missed the last round, these are some of the search terms users entered into their search engine and managed to run across my blog. I’ll try to pick out a few that seem to occur frequently and answer them. Let’s get started.

ssis package not reading environment variables

There is a policy setting on the server that dictates whether or not the SQL Server job engine can access environment variables.

virtual pc exit fullscreen

To exit full screen mode, use the Right ALT+ENTER combination. Note that the left ALT key won’t work, you must use the right ALT key, with the Enter key.

connectstring SQL compact, connectionstring sql compact edition

These two show up frequently, the connection string for SQL Server Compact Edition (SSCE) is:

Datasource=”C:\MyData\myFile.sdf”; Password=’mypassword’

Note a few things, first the password part is optional. Second, the password must be enclosed in single quotes. Finally, the path to your sdf data file must be in double quotes.

wrap a string in double quotes c#

I’m guessing the search here is how to embed a double quote in a string, that’s easy. Just use a backslash in front of the double quote, and C# will interpret it as a literal character and not a double quote.

string myvar = “Right before he became unconscious, he said \”Yes dear, those pants to make you look fat.\”. “

virtual pc 2007 different ip addresses

Each Virtual PC, be it 2004 or 2007, appears as it’s own PC to the network. Your network hub can’t tell the difference between a virtual machine and a real one, and assigns each machine it’s IP address.

why would I use an interface C#

Why not? OK, sorry, couldn’t resist. Short answer, an interface gives you a way to treat many kinds of objects as if they were all the same kind of object. For example, if you had manager, field worker, office worker, and executive objects, you could have all of the implement the employee interface, then you could treat them all like generic employees to do things like pay, give vacation, etc.

For a more detailed instruction, see my series of posts which begin at https://arcanecode.wordpress.com/2007/02/13/more-oop-interfaces-in-c-part-1/ or http://shrinkster.com/mjk.

There you go, a quick selection of the most common searches I found, that were not already answered in my previous blog entries.

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.

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.