Showing posts from 2010

C# Formatting DateTime to a String

Often times you find yourself needing to convert a DateTime object into a useful string representation.  Here are some basic parameters to the DateTime.ToString() method. MM/dd/yyyy 08/25/2010 dddd, dd MMMM yyyy Tuesday, 25 August 2010 dddd, dd MMMM yyyy HH:mm Tuesday, 25 August 2010 06:30 dddd, dd MMMM yyyy hh:mm tt Tuesday, 25 August 2010 06:30 AM dddd, dd MMMM yyyy H:mm Tuesday, 25 August 2010 6:30 dddd, dd MMMM yyyy h:mm tt Tuesday, 25 August 2010 6:30 AM dddd, dd MMMM yyyy HH:mm:ss Tuesday, 25 August 2010 06:30:07 MM/dd/yyyy HH:mm 08/25/2010 06:30 MM/dd/yyyy hh:mm tt 08/25/2010 06:30 AM MM/dd/yyyy H:mm 08/25/2010 6:30 MM/dd/yyyy h:mm tt 08/25/2010 6:30 AM MM/dd/yyyy h:mm tt 08/25/2010 6:30 AM MM/dd/yyyy h:mm tt 08/25/2010 6:30 AM MM/dd/yyyy HH:mm:ss 08/25/2010 06:30:07 MMMM dd August 25 MMMM dd August 25 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2010-08-25T06:30:07.7199252-04:

C# get number of messages in message queue (MSMQ)

Working with message queues in .net is incredibly easy. However I often find myself having to get the number of message in queue for monitoring, etc. That aspect of the message queue framework is a bit lacking. There are a few options available but they all have some problems. You can call GetAllMessages() right off the message queue object. This code works, however it gets a copy of EVERY message queue item currently in the queue. Got 10 items, you get ten. Now do this with 10,000 items every second and it starts to become a problem. It's also possible to enumerate through all the messages in the queue and take a count of them manually but if your queue is busy this can cause invalid cursor exceptions to happen. This is the main reason I moved away from doing this. You can also do some performance counter work but I find that code to be too complex and very fragile and prone to breakage. I've found the best bet is to go with the COM/Win32 route. The nice thing here is

C# Serialize an object to/from XML

There have been many times I've needed to serialize an object to/from XML. .NET makes this incredibly easy. With a few meta tags your class(es) can easily be serialized and deserialized. You can then take this even further any start applying custom attributes to have as much granular control over the serialization as you want. For instance lets' take a very basic class with some data and properties. public class Person { int _age; String _name; /// Gets or sets the Age of the person. public int Age { get { return _age; } set { _age = value; } } /// Gets or sets the Name of the person. public String Name { get { return _name; } set { _name = value; } } /// Creates a new instance of the Person class public Person() { } } Now let's take this class and add the [Serializable] attribute. [Serializable] public class Person { int _age; String _name; /// Gets or sets the Age

C# Equal vs CompareTo

Out of curiosity I decided to run some speed tests on strings using the Equals and CompareTo methods. I wrote some quick code and came up with some interesting results: This test was run for 10000000 iterations. The Equals methods trounced the CompareTo method. Under the hood Equals stops when the first character that doesn't match is found. CompareTo continues on to the end of the string all the time. However this was a case insensitive search with no culture information. Adding more variables may cloud the water a bit, but that is going to be reserved for future posts. The code used in the test can be seen below. using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Threading; namespace Sandbox { class Program { static void Main( string[] args ) { const int counter = 10000000; int i = 0; int count =

C# using a background worker

This post is going to focus on creating and using a BackgroundWorker object. Background workers are found in the System.ComponentModel namespace. They're pretty easy to use. You just create a new object, assign a few properties and event handlers and let it do its thing. using System; using System.ComponentModel; First let's create a background worked object and set it up. Pstatic void Main( string[] args { // create the background worker object BackgroundWorker _worker = new BackgroundWorker(); // tell the background worker it can be cancelled and report progress _worker.WorkerReportsProgress = true; _worker.WorkerSupportsCancellation = true; // a worker thread object where the actual work happens WorkerThread thread = new WorkerThread(); // add our event handlers _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( thread.RunWorkerCompleted ); _worker.ProgressChanged += new ProgressChangedEventHandler( thread.ProgressCha

C# Creating a Singleton

A lot of people talk trash about the Singleton and how it should be avoided like the plague. I think like a lot of things it has its place and can be used effectively in certain situations. I'm going to leave what those situations are alone for the time being and just focus on creating a nice thread safe lazy init singleton class. public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Use an explicit static constructor to tell the C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } }

Binding to a DataGridView with a custom collection

Often times I find the need to bind a custom collection to a datagridview in a windows form. .Net makes this easy and with some simple code we can achieve some pretty quick results. First drop a DataGridView onto your form. Click the little white arrow on the top right of the grid and select Choose Data Source. This should bring up wizard that allows you to select what you want to bind to the grid. Select Object and click Next. Now select the class you want to bind too. You can select from all the existing references in your project or add a new one by clicking Add Reference. When you've selected the class to use click the Finish button. Now that you've got the design done let's write some code to show our data in the grid. I have created a custom collection called Playlists that contains a list of Playlist items. My datagrid is bound to this collection and uses its public properties as the values for the columns. public class Playlist { privat

And now for something completely different

I use remote desktop almost every day. However it has the annoying habit of keeping idle connections open in a zombie state so when you try to logon to a server you get the dreaded max number of connections has been reached error. To bypass this you need to run the remote desktop app from the command line with some special switches. So to do this simply use this command from the command line prompt: mstsc /console /admin /v:<server>

Convert string to base64 string

A while back I came across the need to convert regular string text into a base64 string. .Net makes this fairly easy to do. I created a public static class and added two public static methods to encode/decode strings. Now they don't have to be static or public but I tend to make helper/utility classes that way. All of the classes being used are in the System and System.Text namespaces. /// <summary> /// Encodes the string to Base64. /// </summary> /// <param name="valueToEndcode">The value to endcode.</param> /// <returns>A base64 encoded string.</returns> public static string EncodeStringToBase64( string valueToEndcode ) { // encode the string into ascii byte array byte[] toEncodeAsBytes = ASCIIEncoding.ASCII.GetBytes( valueToEndcode ); // use the byte array to encode to a base64 string string returnValue = Convert.ToBase64String( toEncodeAsBytes ); // drop back the new encoded string value return returnVal

Validating a Guid in C#

Oftentimes you find a need to validate if a string is a valid Guid or not. Luckily for us .net offers some excellent regular expression tools. I've found the best way to do this is to place a small static function in a helper class that validates a string passed in using a regular expression. All regular expression stuff is location in the using System.Text.RegularExpressions namespace. So in some class simply call use the following code: /// <summary> /// Determines whether the specified string is GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <returns> /// <c>true</c> if the specified string is GUID; otherwise, <c>false</c>. /// </returns> public static bool IsGuid( String guid ) { if( guid != null ) { return Regex.IsMatch( guid, @"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$" ); } return

First post of the new year

Happy new year to everyone! I hope this year brings everyone great health, wealth, and the best possible in everything you strive towards. Normally I post a lot of code to this blog but sometimes I have interesting non code info I like to share. Today is one of those posts. I read a lot of code sites and decided to share the ones I love to read the most with you. The Old New Thing This is my favorite blog an d is run by Raymond Chan of Microsoft. He has a lot of really interesting posts about programming, technology, science, and some great insights into Microsoft and why certain things are the way they are. It's not all code all the time but it's fun to read. Joel on Software Joel on Software, another excellent blog that I think focuses more on the high level aspects of programming and less on the low level in the weeds day to day programming kind of tasks. Still tons of cool and great info to read. Coding Horror Coding Horror I think is more a general programm