Showing posts with label Useful .Net classes. Show all posts
Showing posts with label Useful .Net classes. Show all posts

Saturday, March 29, 2008

Webbrowser.Documentcompleted and the ReadyState property

I had previously tried using the WebBrowser class to retrieve a web page for analysis (using the DocumentText property).
The problem was determining the state of the page load (since a page requires several hits before completion on average).

Turns out I need to check on track backs to my post, as Anthony Stevens (you should read his "about" page) found a solution to my problem:
Once the page load is complete WebBrowser.ReadyState property will be set to Complete, and then you can take the loaded page and wreak havoc on it.

Saturday, March 22, 2008

Windows, Unix and Hebrew, Oh my!

As a .Net developer you are not bothered by trivialities such as character encoding, since the framework uses Unicode by default.

But what happens when you need to encode your text so someone else (non .Net) will decrypt it, and that someone uses a single byte per character?

Let's start with few definitions:

  • ASCII - a standard that uses a single byte for each character, but only defines 128 possible symbols. There is no such thing as "Hebrew ASCII".
  • ANSI - Same idea, but here you can use the remaining bits (out of a byte) to encode non-English specific characters. The problem is every language uses a specific version. The ANSI character table may look different on different computers, depending on the configuration.
  • Unicode, UTF-8, etc - Using 2 or more bytes for each character, allowing room for all languages (as long as both sides agree to use the same encoding)

(If you wish to learn more, you should read Joel Spolsky's "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)")

Here are your options:

  • Encoding.ASCII - Your basic ASCII (7 bits) encoding.
  • Encoding.Unicode - Unicode encoding.
  • Encoding.UTF8 - Will encode ASCII text with a single-byte representation, but will switch to a longer representation for non-ASCII strings.
  • Encoding.Default - ANSI encoding based on the computer's configuration, meaning both sender and receiver should share the same locale.
  • Encoding.GetEncoding - Uses a specific code-page to determine the desired encoding. You should try using this method if you need ANSI encoding. However, you still need to determine the code page you require.
    • Encoding.GetEncoding(862) - Uses MS-DOS Hebrew encoding, with Hebrew characters starting at bit 128.
    • Encoding.GetEncoding(1255) - Uses Windows-1255 Hebrew encoding, with Hebrew characters starting at bit 224. This encoding matches the ISO 8859-8 standard, which is also used by Unix.

Monday, March 10, 2008

Generic Singleton Factory

This is a great way to create a Singleton instance of an exiting class without needing to specifically design it as a singleton:

// Singleton factory implementation
public static class Singleton where T : class
{
static Singleton()
{
// create the single instance of the type T using reflection
Instance = (T)Activator.CreateInstance(typeof(T), true);
}
public static T Instance { private set; get; }
}

class Program
{
public static void Main()
{
// test
Console.WriteLine(Object.ReferenceEquals(Singleton.Instance, Singleton.Instance));
}
}

Tuesday, March 4, 2008

Random.NextBytes Performance Issues

I have became aware recently to a performance problem with the Random class, specifically the Random.NextBytes method.

As it turns out this is an expansive operation:


The graph displays the number of milliseconds used to perform 10,000,000 operations.
The NextBytes method handle a byte array containing only 4 bytes.
This is linear - using an array of 4000 bytes will take 1000 times longer to complete the operation!

However, there may be a work-around using the BitConverter class.
Use BitConverter.GetBytes(Random.NextDouble()) to get a randomized array of 8 bytes.

Here are the results:


As you can see, generating an array of 8 bytes this way takes half the time of generating it using the NextBytes method.

Monday, March 3, 2008

Using XmlSerializer for Serialization/Deserialization

This is something I wrote a while ago to allow easy way to serialize/deserialize various objects to and from XML by creating an adapter around the XmlSerializer class.
Since I don't know how this XML is going to be used this class stores it inside a string.

Serialize usage:
string s = SimpleSerializer.Instance.ToString(myObject);
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(s);

Deserialize:
MyClass obj = SimpleSerializer.Instance.FromString(xDoc.OuterXML);


/// <summary>
/// Objects serializer/deserializer
/// </summary>
public class SimpleSerializer
{
private static readonly SimpleSerializer instance = new SimpleSerializer(); //Singleton

/// <summary>
/// Gets the class's instance.
/// </summary>
/// <value>The instance.</value>
public static SimpleSerializer Instance
{
get { return instance; }
}

/// <summary>
/// Private constructor - prevents tempering with the singleton pattern
/// </summary>
private SimpleSerializer()
{
}

static SimpleSerializer()
{
}

/// <summary>
/// Converts an object to it's XML represntation
/// </summary>
/// <param name="message">The source object</param>
/// <returns>XML represntation</returns>
public string ToString(object message)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(message.GetType());
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
serializer.Serialize(sw, message);
return sw.ToString();
}
}

/// <summary>
/// Converts an XML to an object
/// </summary>
/// <param name="message">The XML</param>
/// <param name="type">The expected result class</param>
/// <returns>A new object deserialized from the XML</returns>
public object FromString(string message, Type type)
{
using (System.IO.StringReader sr = new System.IO.StringReader(message))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
return serializer.Deserialize(sr);
}
}

/// <summary>
/// Converts an XML to an object
/// </summary>
/// <param name="message">The XML</param>
/// <typeparam name="T">The expected result class</typeparam>
/// <returns>A new object deserialized from the XML</returns>
public T FromString<T>(string message) where T: new()
{
using (System.IO.StringReader sr = new System.IO.StringReader(message))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)serializer.Deserialize(sr);
}
}

}

Saturday, September 15, 2007

Supporting "foreach" without implementing IEnumerable

Krzysztof Cwalina wrote a post detailing how have your class support the "foreach" loop without implementing the IEnumerable interface:

  1. Public GetEnumerator() method that returns a type with 2 members:
  2. The type will have a bool MoveMext() method.
  3. The type will have an Current property of type object.
Example:
class Foo {
public Bar GetEnumerator() { return new Bar(); }

public struct Bar {
public bool MoveNext() {
return false;
}
public object Current {
get { return null; }
}
}
}

Thursday, August 23, 2007

Adding a performance counter

Some times you need to measure the value of something while running the application.
Using a logger is not comfortable, since you don't want to monitor gazillion rows of values.
The solution: create a performance counter and use Perfmon.exe to view it while the application is running.

Here is a code for creating a counter:

private PerformanceCounter CreatePerformanceCounter()
{
string categoryName = "My Category";

if ( !PerformanceCounterCategory.Exists(categoryName) )
{
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();

// Add the counter.
CounterCreationData myCounter = new CounterCreationData();
myCounter.CounterType = PerformanceCounterType.NumberOfItems64;
myCounter.CounterName = "My Counter";
CCDC.Add(myCounter);

// Create the category.
PerformanceCounterCategory.Create("categoryName", "This is my cateogory", CCDC);
}

PerformanceCounter result = new PerformanceCounter(categoryName, "My Counter", false);
}

Note: You'll need an administrator account to create a new category, but once it's there any account it OK.

Monday, August 6, 2007

Don't propagate exceptions to the user

Catch every exception in your application.
If you must, show the user some kind of an error dialog, but don't force him/her to watch the awful .Net exception dialog.
I have seen to many application with various try...catch blocks, but with nothing done to capture handled exceptions, resulting in those exceptions crashing the application, being displayed to the user, and some times without being written to any log file (making them useless).
It's strange, but some people are still not aware of the Application.ThreadException and AppDomain.UnhandledException events, used to capture unhandled exceptions. You can also use the UnhandledExceptionMode enumeration to specify which event (of the two above) should receive exceptions.
You can also surround the Application.Run call with a try..catch block.

Tuesday, June 26, 2007

Non-Generic to Generic types conversion table

Inbar Gazit published a post on "Converting the Non-Generic Collections" in the BCL Team blog.
He had this handy little table:

Non-genericGeneric replacement
ArrayListList<T>
BitArrayList<Boolean> [note that this isn’t stored as compactly as BitArray but represents the same information]
CaseInsensitiveComparerComparer<T>
CaseInsensitiveHashCodeProviderComparer<T>
CollectionBaseCollection<T>
ComparerComparer<T>
CompatibleComparerComparer<T>
DictionaryBaseKeyedCollection<K,V>
DictionaryEntryKeyValuePair<K,V>
HashtableDictionary<K,V>
KeyValuePairsKeyValuePair<K,V>
QueueQueue<T>
ReadOnlyCollectionBaseReadOnlyCollection<T>
SortedListList<T>
StackStack<T>

Sunday, June 17, 2007

Useful .Net classes people forget to use

Phil Haack wrote a post on .Net services people frequently tend to forget about the re-invent, so I made a list of his pointers as well as some of the comments:

  1. System.IO.Path.Combine(folder, filename)
  2. string.IsNullOrEmpty(string)
  3. Path.DirectorySeparatorChar
  4. Path.GetFileName(fullPath)
  5. Environment.NewLine
  6. Path.GetTempFileName()
  7. System.Diagnostics.Stopwatch
  8. System.Net.NetworkInformation.NetworkChange
  9. System.Web.VirtualPathUtility
  10. System.Web.HttpUtility

Wednesday, May 9, 2007

Multimedia Timer for the .NET Framework

Omer van Kloeten wrote a post pointing to Leslie Sanford's implementation of a very accurate timer for .Net:
The Win32 multimedia timer services provide the greatest degree of timing accuracy. They allow you to schedule timing events at a higher resolution than other timer services.
This can be useful in a multimedia application where timing accuracy is of utmost importance. For example, a MIDI application needs timing events that are as finely grained as possible.
Unfortunately, the Win32 multimedia timer is not part of the .NET Framework. However, by using the .NET interoperability services, the multimedia timer can be brought into the .NET fold.


You can find the code here.

Thursday, February 8, 2007