Category Archives: C#

Event Logging – Reading the Event Log

Yesterday we created some code that wrote messages to the event log, and showed how to use the Microsoft Management Console (MMC) to review those messages. For the average user though, running the MMC may be a bit out of their normal comfort bounds. Instead, we need to be able to access the log from within our application. Again, the .Net Framework makes this easy.

First you’ll need to create an EventLog object, as we did with the writing. Then set the log property to the log we write to. Finally you will need to loop through the Entries collection of the EventLog, looking at each EventLogEntry object. Here’s a quick method I put together.

    public static string ReadLog()

    {

      StringBuilder returnValue = new StringBuilder();

      EventLog el = new EventLog();

 

      el.Log = “ArcaneCode”;

 

      foreach(EventLogEntry myEntry in el.Entries)

      {

        returnValue.AppendLine(myEntry.Source + “: “

          + myEntry.Message + ” “ + myEntry.TimeGenerated.ToString());

      }

 

      return returnValue.ToString();

    }

The EventLogEntry class has a lot of informative properties, here I’ve grabbed the three most important, Source, Message, and TimeGenerated. Source and Message are just as you wrote to the log. TimeGenerated is important as it lets you know when the message was generated. Not only will this tell you when the user had the issue, you can also use it to limit the amount messages you export.

In a real world situation I would have passed in the code, and probably passed in a date as well to limit the number of entries I returned. But this gives us a good starting point for building our event logger helper class. Stay tuned….

Advertisements

Event Logging – Writing to the Event Log

First off, let me say thanks to our BSDA (http://www.bsda.info/) President, last week he gave a quick intro to event logging that inspired this piece. If you are a new developer, you may be wondering what Event Logging is.

Let’s face it, users are the worst in the world about telling you what happened.

User: “I had an error with your app.”

You: “OK, what was the error message?”

User: “I dunno, just something about an error.”

You: “Uh, did you write down the message?”

User: “No, but it looked real bad. I think you need to fix it right away. Gotta go!”

Fortunately, Windows has a built in way to track messages that your application generates, called the Event Log. In .Net 2.0 it turns out logging is very simple, just a few lines of code.

First, set a reference to the System.Diagnostics in your class, that’s where the event objects live. Now paste in a few simple lines of code:

      EventLog evt = new EventLog(“ArcaneCode”);

      string message = “This is where the error message goes. “
        + “For support info see https://arcanecode.wordpress.com”
;

      evt.Source = “ArcaneCodeApplication”;

      evt.WriteEntry(message, EventLogEntryType.Information);

The first line creates a new event log entry under the name ArcaneCode. You’d probably want to put the name of your application in this area. The next line creates the message to log, in a real app this would probably be passed in as a string from an error handler or tracer.

The Source property is for designating the area that had the problem. In a “real world” app I would probably put the class and method that generated the event log request here, perhaps passed into a routine as a string. For this example though it’s just hard coded.

The final line actually writes the entry, after all the setup has been done. The first parameter is obvious; it’s the message to log. The second parameter indicates the type of event this is. The EventLogEntryType enumerator has five choices; Information, Warning, and Error being the most common.

To see if this got to the log, we need to look in the Microsoft Management Console. Click Start, Run from your Start menu, then type in mmc and press enter. Once the Console opens, pick File, Add/Remove Snap-in from the menu. Down at the bottom of the screen you’ll see a button that says “Add”. Click it, then in the list that appears find one called “Event Viewer”. Pick it, click Add, then Close. Then click OK. You should see something like this:

[Picture of MMC Console]

You can see the entry for “ArcaneCode”. Click it and you’ll see all of the events generated by your program. Double click on one of the events (or right click and pick properties) will show you all of the detailed info including the date / time, and that spiffy error message you passed in.

[Picture of Event Properties]

You can see that having a place to log messages to could make application debugging much easier once your app winds up in production. It will also be handy for debugging things like web or windows services, things that lack a user interface.

Care should be taken with what you log. It’s easy to go overboard and log every little thing. In my book, you should always log any error message that the application cannot handle. Then you should move into the critical areas of your app that are “problem spots”. Finally, if the user does something that will have a major impact on your database, such as electing to delete every customer record, you’ve found a good candidate for an event to log.

Of course, putting data into the event log is one thing. You can hardly expect your user to have the ability to go into the management console every time they have an error. That’s why the .Net Framework also has a way to get the events back out of the system, and it’s just as easy as putting them in. We’ll cover that in the next post, then go on to build a nifty event logging class you can use in your own applications.

Static Methods

Another often overlooked topic is the usefulness of static methods. Simply put, a static method is a method you can call without having to first create an object from a class.

In a traditional class, to use a method you first have to create an instance of it. Let’s say our class looks like this:

  public class StaticTest

  {

    public string CombineName(string first, string last)

    {

      return first + ” “ + last;

    }

  }

To use our simple class, we do something like this:

      StaticTest st;

      st = new StaticTest();

      string fullName = st.CombineName(“Arcane”, “Code”);

Looking at the ComineName method, you see it’s pretty simple. It doesn’t use any of the classes internal variables, call other methods, or anything else special. Seems like a lot of overhead to use a simple method. Fortunately, .Net provides a way we can call this method without having to create an object from it’s class. As you may have guessed, it’s the static keyword. A quick change to our method declaration is all that’s required.

    public static string CombineName(string first, string last)

    {

      return first + ” “ + last;

    }

Now it’s much easier to call our method. We can get rid of the variable declaration all together. Then, instead of referencing an instance of our class, we reference the class name itself. Three lines of code is reduced to:

      string fullName = StaticTest.CombineName(“Arcane”, “Code”);

 

Notice that the st.CombineName became StaticTest.CombineName. I find that when working with new developers this becomes the most confusing thing about static methods, namely you use the class name instead of a variable when addressing static methods of the class.

Static methods do have a few restrictions. First, they are not allowed to reference any of the class’s variables or properties. This makes sense, as they are running outside of a specific instance of the class. They also cannot use the “this” keyword. Again, this makes sense as this refers to a specific instance (i.e. an object) of a class, and inside a static method there is no instance to access.

The .Net Framework is loaded with static methods, take the string for example. Type in string and hit the period, an you’ll be amazed at how many methods appear. All of these are static methods that are part of the string class.

When writing your methods, take a look and see if they could be implemented statically. If you don’t have to reference other variables or properties of the class, you may have a good candidate for a static method.

Boxing and Unboxing

I want to begin the series by covering some “advanced basics”. You can find a million “Hello World” tutorials, so I want to avoid those and cover topics frequently overlooked in beginners books. Boxing is just such a topic.

As you may be aware, there are two kinds of variables in .Net, value types and reference types. A value type is stored in an area of memory called the stack, which is a very fast place to get to. Value types are simple data types like integers, doubles, and so on. Things the compiler can always guarantee the size of.

Reference types, on the other hand have a variable size, and thus don’t fit nicely on the stack. So .Net puts them in a memory location called the heap, and stores a reference to the stack.

It’s a lot like having a post office box. For small items, like letters, you just go to the post office box and remove them, quick and easy. Let’s say you get a huge package, maybe that spiffy new laptop has finally arrived. Obviously that laptop won’t fit in your post office box, so the mail service puts a little yellow slip that says “you’ve got a package, it’s stored in this location, come get it”.

The post office box in this case would be the stack. Letters are like value types, small, fast to get to, and usually one of a few predictable sizes. The little yellow slip saying you’ve got a package would be a reference type, it’s pointing to a specific spot in the heap of packages stored in the back room.

Now, boxing occurs whenever you try to put a value type, such as an integer, into a reference type, such as an object.

      int myLetter = 42;

      object myBox = (object)myLetter;

Because .Net doesn’t know in advance how big the myBox object will be, it has to make it a reference type. Placing an int into it makes no difference. .Net will happily take the value 42, place it on the heap, and store a reference to the memory location in the myBox variable.

As you might guess, extending our PO Box analogy would have the post office take the letter out of your PO Box, shove it in a big box, put it in the back and stick one of those yellow slips in your slot.

This entire process is called Boxing. The reverse, putting a refernce type back into an value type is called Unboxing.

      object myBox = 42;

      int myLetter = (int)myBox;

Boxing and unboxing are very slow processes. Additionally, they are fraught with danger. What if we’d tried this instead?

      object myBox = 3.1415719;

      int myLetter = (int)myBox;

Gold star to anyone who blurted out “run time error” or “invalid cast exception”. There is no implicit type checking when moving from a value type back to a reference. You will have to add additional code to be sure that no errors happen.

In general you should try to avoid boxing and unboxing, and instead use generics (more on them later). Occasionally you can’t avoid it, for example:

      int recordCount;

      // Some code here that loads records and increments recordCount

      MessageBox.Show(“You loaded “ + recordCount.ToString()

         + ” records.”);

You may not realize it, but when you call ToString, you are creating a boxing operation, converting our nice value type int into a reference type string. As I mentioned, sometimes you can’t avoid these types of operations. Which brings us to the obvious question, when is it “safe” to box?

Typically when you perform a widening operation, moving a smaller variable into a larger one, you’re OK. For instance, moving an int into a double or string is safe because you are taking a smaller data type and moving it to a larger one. Much like taking an envelope out of your post office box, and placing into one of those large overnight mailers, or a shipping carton.

A narrowing conversion on the other hand is when you take a big variable and try to shove it into a smaller one, such as a double into an int. These are dangerous and you should be sure what you are doing before attempting.

By the way, not all widening operations are necessarily a boxing operation. Going from int to double is widening, but not boxing because there are two value types involved. Moving from int to string is both widening and boxing, as you are going from a value to a reference type. Whichever the case, just know that both are “safe” things to do. You can rest easy knowing this particular type of operation is safe.

Boxing is one of those arcane pieces of knowledge, understanding it will help you to be a better programmer so you will know when using it appropriately, and when to avoid it.