mike-obrien.net Resume Blog Labs
Thursday, April 12, 2007

So I am trying to write log information to an XML document using the XmlTextWriter.  When it reaches a certian size I want it closed out and archived. What I mean by "closed out" is that while the log file is "open" the root element is not closed so that I can keep adding entries over a period of time. In other words:

<?xml version="1.0"?>
<log>
    <entry date="1/1/2007">Yada yada yada</entry>
    <entry date="1/1/2007">Yada yada yada</entry>
    ...


Then once its full I will write the closing root element and rename it:

<?xml version="1.0"?>
<log>
    <entry date="1/1/2007">Yada yada yada</entry>
    <entry date="1/1/2007">Yada yada yada</entry>
    ...
    <entry date="1/1/2007">Yada yada yada</entry>
</log>

Well the XmlTextWriter automatically closes out all open elements when you close it. Looking in Reflector reveals what is happening behind the scenes:

public override void Close()
{
   try
   {
      this.AutoCompleteAll();
   }
   catch {}
   finally
   {
      this.currentState = State.Closed;
      this.textWriter.Close();
   }
}

First the AutoCompleteAll() method is called, then the underlying stream is closed. The AutoCompleteAll() method is as follows:

private void AutoCompleteAll()
{
   if (this.flush)
   {
      this.FlushEncoders();
   }
   while (this.top > 0)
   {
      this.WriteEndElement();
   }
}

Doesent look like there is any official way to explicitly close only the elements you want to close, its just automatically done for you when you close the writer. The only work around I could figure out is to explicitly close the elements I want closed, then close the base stream (Not the XmlTextReader). This works but IMO its a little hackey since the code in the Close() method could potentially change in the future and you could end up circumventing some code that you might want executed when your done with the reader.

.NET | C# | VB.NET | XML/XSL
Thursday, April 12, 2007 7:01:42 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Friday, March 23, 2007

I have been working with the new custom configuration classes in .NET 2.0 and they really make creating custom xml configuration a snap. They are a little quirky to use at first but once you get past the initial learning curve they really make the job a lot easier.

One thing I really wanted to figure out is how to use these new classes to read files other than the default app/web.config. For example if you have one config file that might be shared between exes or if a config file is pulled from a URL. Its actually pretty easy to do.

First create your custom configuration file. It will look exactly the same as a web/app.config file except it will only contain your custom section(s). Create a section handler element identifying the custom section handler and the name of the section. Again, nothing different from doing this in the app/web.config.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <configSections>
  <section name="mySettings" type="CustomConfigHandler.MySettingSection, CustomConfigHandler"/>
 </configSections>
 <mySettings>
  <someSetting someAttribute="This is an attribute value from Settings1.config"/>
 </mySettings>
</configuration>

Next create a Configuration object that points to your file by passing in an ExeConfigurationFileMap with the ExeConfigFilename set.

// Create an exe file map containing the path to your config file
ExeConfigurationFileMap FileMap = new ExeConfigurationFileMap();
FileMap.ExeConfigFilename = "MySystem.config";

// Create a configuration object that is tied to your custom config file.
Configuration Config = ConfigurationManager.OpenMappedExeConfiguration(FileMap, ConfigurationUserLevel.None);

// Create the custom config section handler
MySettingSection MySettings = (MySettingSection)Config.GetSection("mySettings");

Console.WriteLine(MySettings.SomeSetting.SomeAttribute);


The entire source can be downloaded here:

ExternalConfigFile.zip (40.24 KB)
.NET | C# | Configuration | VB.NET
Friday, March 23, 2007 8:30:17 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Monday, January 29, 2007

There is a new version of the Hid Library in the labs. It has been converted to .NET 2.0 and includes a bug fix. This bug fix involved how the vendor and product id were cast in the structure consumed by the Hid API. So some devices like Logitec's gamepads would not be recognized by their product and vendor id's. Now that issue is resolved. N-joy!

USB Hid Device Library

.NET | C# | USB HID | VB.NET
Monday, January 29, 2007 10:36:12 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [27]  | 
Tuesday, January 09, 2007

I was looking over a peice of my code today and noticed I had some finalization code in a try-finally block but there was a code path that had a return statement. So I thought, "thats a bug because I'm jumping out of the method before the finally block is called!". Silly me! MSDN says "Control is always passed to the finally block regardless of how the try block exits". For some reason I always thought that the finally block was bypassed when you exited a method via the return statement... :-S

.NET | C# | VB.NET
Tuesday, January 09, 2007 5:02:49 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Thursday, January 04, 2007

Removing special chars (Control chars 0-31 and extended ASCII 127-255) is pretty easy to do with a regular expression. Simply select chars that are not in the range of ASCII 32-126 (Hex 20-7E) and replace these chars with an empty string.

Regex SpecialCharExpression = new Regex(@"[^\x20-\x7E]");
string NewData = SpecialCharExpression.Replace(OldData, string.Empty);

Here is a working example:

class Program
{
   static void Main(string[] args)
   {
      string OldData = string.Empty;

      for (int Index = 0; Index < 256; Index++)
      {
         OldData += ((char)Index).ToString();
      }

      Regex SpecialCharExpression = new Regex(@"[^\x20-\x7E]");
      string NewData = SpecialCharExpression.Replace(OldData, string.Empty);

      Console.WriteLine("Length: " + NewData.Length);
      Console.WriteLine(NewData);
      Console.ReadKey();

   }
}

.NET | C# | VB.NET
Thursday, January 04, 2007 6:47:38 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Wednesday, January 03, 2007

I really have to remember to use the IsNullOrEmpty method in the string class. I keep forgetting to use it so I figure if I blog about it I'll remember.. ;)

// Why do this...
if (MyString != null && MyString.Length > 0) {...}

// When you could do this???
if (string.IsNullOrEmpty(MyString) == false) {...}

And while we are on the subject, the .NET framework defines a lot of nice constants for us to use instead of defining our own or using literals. See if one exists in a class near you... Here are a couple of examples:

// Why use the "" literal when you can use
String.Empty;

// = "\"
System.IO.Path.DirectorySeparatorChar;

// = "/"
System.IO.Path.AltDirectorySeparatorChar;

// Returns char[] {'"', ...}
System.IO.Path.GetInvalidPathChars();

// Returns char[] {'"', ...}
System.IO.Path.GetInvalidFileNameChars();

.NET | C# | VB.NET
Wednesday, January 03, 2007 9:59:05 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Wednesday, November 22, 2006

So I'm implementing an interface, defined in an assembly written in VB.NET, on a class in an assembly written in C#. The interface defines a number of events. VB.NET event declaration doesent require you to define the corresponding delegate (as C# does) so the question is where does the VB.NET compiler declare it for you after compilation? Well it seems that the delegate definition is declared right in the interface. This could be confusing for someone who doesent know VB.NET since C# does not allow the declaring of types within an interface whereas VB.NET does.

Here IDataInputDevice is an interface residing in an assembly written in VB.NET with three events defined. The corresponding delegate definitions are defined right within the interface.

.NET | C# | VB.NET
Wednesday, November 22, 2006 11:39:52 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Friday, November 10, 2006

One of the shortcuts of C# (And now in VB.NET 2005) I love is the using statement. For those not familiar with it, it allows you to create objects within the scope of the using block and then once the block completes execution, calls the Dispose method on all the specified objects if they implement IDisposable. This occurs even if an exception is thrown. From what I understand, the using block in the resulting IL is a try/finally block, where the object disposal takes place in the finally.

This is perfect for working with a DataReader and instances where we want to make sure a database connection is closed right after a call. Since the Dispose method on a DataReader and Connection object call their own Close method they will be implicitly closed when we exit the using block, regardless of errors.

string ConnectionString = "server=127.0.0.1;database=duwamish7vb;Trusted_Connection=true";

using (SqlConnection Conn = new SqlConnection(ConnectionString))
{

    Conn.Open();

    SqlCommand Command = new SqlCommand("SELECT Name FROM Authors",Conn);

    using (SqlDataReader Reader = Command.ExecuteReader())
    {

        Authors.DataTextField = "Name";
        Authors.DataSource = Reader;
        Authors.DataBind();

    }

    Command = new SqlCommand("SELECT Subject FROM Books", Conn);

    using (SqlDataReader Reader = Command.ExecuteReader())
    {

        Books.DataTextField = "Subject";
        Books.DataSource = Reader;
        Books.DataBind();

    }

}

.NET | C# | VB.NET
Friday, November 10, 2006 9:17:27 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 

I have seen a lot of debate about VB.NET and C# and which one is "better". Before I started coding in C# I had some prejudice about it, but it’s interesting to see how my viewpoint has in some cases changed, and in others not changed after making the switch.

My viewpoint before switching over:

  • .NET languages are as MS put it a "lifestyle choice".
  • Many C# programmers think a little too much of themselves, projecting an elitist status as if a VB.NET developer knows nothing about OOD/OOP, design patterns and are just script kiddies.
  • Case sensitivity within a language is moronic, inelegant and causes ambiguity.
  • VB.NET is a very expressive language, like reading a book whereas C# looks like a bunch of ugly symbols.
  • And what’s with that stupid semi-colon anyway??

My viewpoint after switching over:

  • I still think it’s a lifestyle choice. I’m sure some C# purists will probably say I "don’t know enough about C#" or "that sounds like something a VB programmer would say". :-) The power of the .NET framework is, in my opinion, expressed well in both languages except for a few things here and there. Especially now with the release of v2.0 it’s not about whether or not you use a particular language syntax, it’s really about knowing how to develop .NET applications and about programming and design principles.
  • I still think some C# programmers think too much of themselves. I do realize however that the majority of VB.NET programmers come from the VB6/VBScript world, a world I am from. Many of those individuals carry a lot of baggage with them and do not have a good grasp of OO, design patterns, etc and are just not skilled developers. Many of them are the script kiddie type because it was so easy to pound out code in those languages, didnt require a whole lot of skill. But don’t judge a book by its cover. I think there are a lot of developers who came from that world who have embraced the principles, now present in the .NET framework (Not just a particular language syntax), that Java and C++ programmers have practiced and enjoyed for years.
  • I've not noticed the case sensitivity in C#… In fact in cases where I have not had VS prettying up my VB code I manually format my code anyway. Not even an issue. Ambiguity is definitely a possibility but I think a good developer would avoid that for clarity.
  • I actually now like all those "ugly symbols" over the expressive and verbose VB syntax… Very strange because that was one of my biggest prejudices aside from case sensitivity. It’s just a lot simpler and once you get used to it it’s not hard to read. If you are only familiar with the expressive syntax of VB it is hard to follow. I feel like I have much more flexibility over how I structure my code. Even going back to do maintenance on VB.NET code is less than enjoyable now that I have been working with C#.
  • Ok, the semi-colon is a little annoying at first but you get to the point where you don’t even think about it. It’s actually very nice in instances where you have a large string literal or a long line of code.

Bottom line is, "...just listen to your heart. That's what I always do". Dont be caught up in the hype that coding in VB.NET makes you a script kiddie. But I would seriously recomend, if you are a VB.NET developer who has not learned C#, to at least give it a try. You might be very surprised at how much you like the syntax over VB.

.NET | C# | VB.NET
Friday, November 10, 2006 8:25:01 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  | 
Thursday, September 07, 2006

Never realized this but in order to implement one or more interfaces on an interface in VB.NET you use the Inherits keyword, not the Implements keyword...

Namespace LineChart

   Public Interface IRange

      Inherits IEnumerable
      Inherits IDisposable

      ReadOnly Property Count() As Integer
      ReadOnly Property Items() As RangeItem()

   End Interface

End Namespace

Thursday, September 07, 2006 4:32:57 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |