Thursday, April 24, 2008

Quick Tip - Add A Visual Studio File As A Link

Have ever wanted to include a file in a Visual Studio project, but you didn't want it to be copied to the project directory? You could hack the location into the project file, but editing XML seems to be overkill for such a simple task. A colleague at work showed me a better way (thanks Cliff!). Use the Add As Link option. It is in an obscure location. When you go to add an existing item you can click the arrow next to the Add button and find Add as link.

This can really be helpful when you are sharing XML schemas, interfaces, etc... between assemblies that need to keep these resources in sync, such as client and server assemblies.

Save to del.icio.us Add to Technorati Add to dzone

Tuesday, April 22, 2008

When is a LINQ Statement Executed?

LINQ statements are the latest and greatest from Microsoft's .NET Framework. If used correctly they can make complex operations readable, maintainable and simple. Here is a simple example:


string[] characters = { "Ender", "Peter", "Valitine", "Stilson", "Graff", "Anderson" };

var eCharacters = from i in characters where i.Contains("e") select i;

foreach (string character in eCharacters)
// Do something with character

This sample shows a LINQ statement that extracts strings that contain an "e" from the character array. The characters would include Ender, Peter, Valitine and Anderson. One of the keys to understanding LINQ is understanding when this filtering actually occurs. Let's change the example a bit. In this example we will change the source (characters) so that Valitine will now be Val.

string[] characters = { "Ender", "Peter", "Valitine", "Stilson", "Graff", "Anderson" };

var eCharacters = from i in characters where i.Contains("e") select i;

characters[2] = "Val";

foreach (string character in eCharacters)
// Do something with character

The string array was changed after the LINQ statement. So will Valitine be included in eCharacters? No. LINQ statements do not execute until their values are enumerated over. This is called differed execution. If we wanted the LINQ statement to pull the values out at the time of execution we would need to enumerate through the values. Luckly with the extensions provided with LINQ we can do this very easily by changing our LINQ statement to something like this:

string[] eCharacters = (from i in characters where i.Contains("e") select i).ToArray<string>();

With a call to ToArray<string>() we enumerate over the LINQ result and create a string array. If the characters array changes, the values in the eCharacters array will not.

Save to del.icio.us Add to Technorati Add to dzone

Thursday, April 17, 2008

Speech Libraries added to .NET 3.0

Microsoft has wrapped the SAPI into .NET 3.0 with the System.Speech namespace. System.Speech has two main sections. They are Recognition and Synthesis. In order to use the System.Speech library you need to add a reference to it.

Synthesis

Synthesis can be done very easily.

SpeechSynthesizer synthesizer = new SpeechSynthesizer();
synthesizer.Speak("This text is spoken by the computer.");

In SAPI 5.3 (the version that System.Speech wraps) Microsoft Anna is the only voice available. Hopefully Microsoft will make more voices available.

Recognition

Getting started with speech recognition is a little more involved. You need to decide whether you want to recognize text (dictation) or recognize specific commands. The Grammar object will tell the recognition engine whether you want to recognize text or recognize specific commands. First we'll look at dictation (recognizing text).

static void Main(string[] args)
{
SpeechRecognizer recognizer = new SpeechRecognizer();
recognizer.LoadGrammar(new DictationGrammar());
recognizer.SpeechRecognized += new EventHandler(recognizer_SpeechRecognized);
}

static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result != null)
Console.WriteLine(e.Result.Text);
}

This will recognize speech from the line in and write text to the console. We can also accept input from a wave file.

SpeechRecognitionEngine engine = new SpeechRecognitionEngine();
engine.LoadGrammar(new DictationGrammar());
engine.SetInputToWaveFile("C:\\My Temp\\Test Audio Search.wav");
RecognitionResult result = engine.Recognize();
if (result != null)
Console.WriteLine("Recognized: " + result.Text);

Command recognition is done by creating a Grammer object that identifies the commands you would like to be recognized. You can build the Grammer object with GrammerBuilder and Choice classes. Here is a simple example:

static void Main(string[] args)
{
SpeechRecognizer recognizer = new SpeechRecognizer();
GrammarBuilder commandGB = new GrammarBuilder();
commandGB.Append(new Choices("open", "close"));
recognizer.LoadGrammar(new Grammar(commandGB));
recognizer.SpeechRecognized += new EventHandler(recognizer_SpeechRecognized);
}

static void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result != null)
Console.WriteLine("Recognized: " + e.Result.Text);
}

Here we are looking for open or close as commands. The System.Speech namespace makes this very easy to code, but the speech recognition and synthesis aren't the quality you would hope for in 2008. Synthesis can be improved with SSML and SRGS although it still sounds robotic and the only voice available is Anna. Recognition needs to be calibrated to get any sort of reasonably accurate results, at least for dictation. Also the documentation leaves a lot to be discovered. I like that Microsoft has included this in a managed library, but I would like to see even more effort applied to the speech technology itself.

Save to del.icio.us Add to Technorati Add to dzone

Friday, April 11, 2008

The X in AJAX Is For XML Right?

AJAX is generally accepted as asynchronous Javascript and XML. It is documented as such on Wikipedia. Although I've found that XML isn't the best choice in transmitting data with Javascript. I'll show you why. Lets look at my previous AJAX example. Here we sent just the text of the customer's name and then send back their address. We aren't even using XML. This is fine for this simple example, but what if you wanted to send and receive more complex objects? What if you wanted to send a list of first and last names and receive back all of the customer's information like birth date, color, sex, etc... You could make a delimited list. I shouldn't have to tell you why this is not a good idea, but if you need convincing read the Advantages of XML section of the Visual Basic® .NET Developer's Guide to ASP .NET, XML and ADO.NET.

XML does seem to be the logical choice and it's the X in AJAX! So if we have a list of objects that have a first name and a last name how do we get these to XML? In C# you can use the XmlSerializer and serialize your object into XML. Can you do this in Javascript? no. JavaScript doesn't have the extensive group of helper libraries like .NET has. So we have to serialize the object ourselves. Here are some examples: toXML and XmlSerializer. Ok so we can do some copy and paste and now we can send our list of first and last names to the web server.

Now when we get our response we will get more XML. We can use the XmlSerializer to deserialize the objects into Javascript objects, but that requires a schema. Instead we can use the XmlHttpRequest's responseXML property to get a document object that we can traverse to get our object.


var xml=ajaxRequest.responseXML;
var xmlArray=xml.getElementsByTagName("CustomerInfo");
var customers=[];
for (var i=0;i<xmlArray.length;i++) {
var customer={};
var ciNode=xmlArray[i];
for (var j=0;j<ciNode.childNodes.length;j++)
customer[ciNode.childNodes[j].nodeName]=ciNode.childNodes[j].text;
customer[i]=customer;
}

This requires us to use DOM to move through the nodes and extract the data we are interested in and create an array of hash tables that represent our customers. XML is requires processing power to traverse through and is quite bulky running down the wire, but what else can we do? JSON!

JSON


As stated on JSON's website JSON is a subset of the object literal notation of JavaScript. What does that mean well it means that you can use the JavaScript interpreter to create objects from JSON. Why is that important? Because this means that using JSON will make your AJAX calls fast, small and most importantly very transparent to use. Take a look at the JSONized version of the above example:

var customers=eval('('+ajaxRequest.responseText+')');

One line! It doesn't get much better then that. There has to be a downside right? Well it's really not that bad. If you want to send JSON strings to the web server you need to download the JSON library. just use the JSON.stringify on your object to send to the web server and you are all set. Now what about the web server side? If you are using .NET I like to use JSON.NET. You can also look at Scott Hanselman's Blog on a few other JSON serializers.

Summary


XML is not the right fit for JavaScript. I think we need to wipe our hands of AJAX and start web 3.0 with JavaScript with asynchronous notation transport, JANT!

Save to del.icio.us Add to Technorati Add to dzone

Thursday, April 10, 2008

AJAX in ASP.NET

AJAX is simply a callback to the web server that doesn't refresh the current web page. Most AJAX application then use that information to dynamically modify the web page. We can quickly setup an AJAX call in ASP.NET. To start we need to have a web form. For this example we'll add a input text box, a button(not a submit button), and a textarea. You will input a customer's name in the input box and click on the button to get the customer's address in the textarea.


<body>








</body>

On the button's onclick event the javascript method GetCustomer is called. GetCustomer is where we will make our AJAX call. Most of the AJAX magic is done with the XMLHttpRequest object. The XMLHttpRequest object sends a request back to the web server without refreshing the page. To make a request you need three things: a function to handle the response, a handler on the web server and the content to be sent. Since we are sending a request that is asynchronous we need to have a function to handle the response. A handle is a simple web page that will handle our request and send back a response. The content can be null so technically content is optional. The callback function that will handle the request will set the textarea to the response text we will get from the handler. We will set the location of the request to handler that will create in a second. We will also send the customer so the handler will know what customer to lookup. Here is the code we will use to send our request:

function GetCustomer() {
var ajaxRequest=new XMLHttpRequest();

ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState==4)
document.getElementById("TextArea1").value=ajaxRequest.responseText;
}

ajaxRequest.open("POST", "Handler1.ashx", true);
var customer=document.getElementById("Text1").value;
ajaxRequest.send(customer);
}

Next we need to create the Generic Handler, Handler1.ashx. In the Handler1.ashx.cs file you need to handle our AJAX request. The ProcessRequest method will be called when a request is sent so we will place our customer lookup code there. We will first pull out the customer from the request, look it up and then return the address in the response.

public void ProcessRequest(HttpContext context)
{
string customer = new StreamReader(context.Request.InputStream).ReadToEnd();

context.Response.ContentType = "text/plain";
if (String.Compare(customer, "Bob") == 0)
context.Response.Write("123 Bob Ave.\nBobville, BO 12345");
else if (String.Compare(customer, "Foo") == 0)
context.Response.Write("789 Bar St.\nFooville, FB, 01111");
else
context.Response.Write("Unknown customer!");

context.Response.Flush();
context.Response.Close();
}

Be sure to include the Flush method otherwise the response will not be sent. Here we only have two customers: Bob and Foo. Any other values will return "Unknown customer!"

Gotchas


The XMLHttpRequest object is only compatible in Opera 8.0+, Firefox, Safari, IE 7.0+. If we want to have support for other browsers we need to make a small modification. We will create a new factory function to return a AJAX request object.

function getAjaxRequest() {
// Opera 8.0+, Firefox, Safari, IE 7.0+
if (window.XMLHttpRequest) return new XMLHttpRequest();
// IE 5-6
else if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");

return false;
}

We need to make a small change to the GetCustomer class to implement this change.

function GetCustomer() {
var ajaxRequest=getAjaxRequest();

if (ajaxRequest!=false) {
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState==4)
document.getElementById("TextArea1").value=ajaxRequest.responseText;
}

ajaxRequest.open("POST", "Handler1.ashx", true);
var customer=document.getElementById("Text1").value;
ajaxRequest.send(customer);
}
}

From this example you can see that it is very easy to setup an AJAX call within ASP.NET. The possibles for AJAX are endless. Hope you find it as innovative as I have.

If you are having trouble with any of the code try downloading the full source code for the above example.

Save to del.icio.us Add to Technorati Add to dzone

Thursday, April 3, 2008

Do your .NET assemblies have Trace Statements? Maybe they should.

Have you ever had a problem with your code in a production environment? If not you must be awful lucky. For the rest of us I'm sure we have spent may hours troubleshooting code that worked fine in development, but is now not working in the production environment. If you've used the Debug class to output debug messages you mostly like have found that these don't work in release builds. Yes you can enable them in the release build, but a better way to handle this is to use the Trace class.

You can write a Trace message very easily.


Trace.WriteLine("I'm doing some work");


This will write "I'm doing some work" to the output window. If I'm in a production environment I might want to write to a text file instead. Trace handles this by implementing TraceListeners. The default is the DefaultTraceListener which writes to the output window. We can use the TextWriterTraceListener to output to a file. We can do this via a configuration file or programmatically. If you want to add this to the configuration file add the following to your app.config file.


<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="2">
<listeners>
<remove name="Default" />
<add name="TextTraceLogger" type="System.Diagnostics.TextWriterTraceListener" initializeData="Log.Txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>


In this configuration we removed the Default Listener. This isn't required. You can have many listeners if you like. If you are adding Trace messages to libraries be sure to add the Trace configuration to your executing assembly. You can add a Listener programmatically by using the Trace.Listeners property.


Trace.Listeners.Add(new TextWriterTraceListener("Log.Txt"));


Especially in production you don't want detailed output all the time. You just want it when you are troubleshooting. The TraceSwitch class performs this function. The TraceSwitch class stores a TraceLevel that is used to evaluate whether a message should be outputted or not.

public enum TraceLevel
{
Off = 0,
Error = 1,
Warning = 2,
Info = 3,
Verbose = 4,
}


When a TraceSwitch is set to a specific TraceLevel all the lower valued levels are "activated" as well. For example if a TraceLevel is set to Warning, Error messages will be outputted as well.

Like the TraceListeners the TraceSwitch can be created in the configuration file or programmatically. Configuration example:

<configuration>
<system.diagnostics>
<switches>
<add name="General" value="Warning" />
</switches>
</system.diagnostics>
</configuration>


If you are adding TraceSwitches to a library be sure to set the configuration of the executing assembly and not the libraries assembly. Programmatic example:

TraceSwitch GeneralTrace = new TraceSwitch("General", "General Trace Messages");
GeneralTrace.Level = TraceLevel.Warning;


To use a TraceSwitch in code you first need to declare it. If you have defined a TraceSwitch in the configuration file the TraceSwitch name needs to match the name in the configuration file. You then will use the TraceSwitch to evaluate weather a message is outputted or not.

TraceSwitch GeneralTrace = new TraceSwitch("General", "General Trace Messages");

Trace.WriteLineIf(GeneralTrace.TraceVerbose, "A verbose message");
Trace.WriteLineIf(GeneralTrace.TraceError, "an error message");


If you need to do some work to create the Trace message you may want to just include the TraceSwitch evaluation in an if block.

if (GeneralTrace.TraceError)
{
StringBuilder errorMessageBuilder = new StringBuilder();
errorMessageBuilder.Append("Error processing. Details: ");
foreach (ErrorDetail detail in ErrorDetails)
{
errorMessageBuilder.Append(detail.Message);
}

Trace.Write(errorMessageBuilder.ToString());
}


Here are some other TraceListeners:

You can also create your own TraceListener by inheriting from TraceListener.

Save to del.icio.us Add to Technorati Add to dzone

Wednesday, April 2, 2008

Is Enterprise Logging Application Block the best choice for Logging?

I've been using Log4Net for quite some time now, but I recently came across a new logging framework called Microsoft's Enterprise Logging Application Block. That is quite a mouthful, but it sounds promising. The Logging Application Block is part of a collection of other application blocks that is called the Enterprise Library. The Enterprise Library contains eight application blocks:

  • Caching
  • Cryptography
  • Data Access
  • Exception Handling
  • Logging
  • Policy Injection
  • Security
  • Validation

Let's see how the Logging Application Block compares to Log4Net. For this review we will use Microsoft Enterprise Library 3.1 - May 2007 and Log4Net 1.2.10. The four areas we will compare them on are easy of use, configuration, performance, flexibility.

Easy of Use

Setup of Enterprise Logging for flat files and the event log is very easy with the help of the Enterprise Library Configuration utility. Logging to the database was a little more difficult and a little awkward. For instance you need to set the Formatter for the Database Trace Listener even though it doesn't dictate what is entered into the database.

Log4Net doesn't have a UI configuration, but I've always found the setup is documented well and intuitive to implement.

Configuration

The Enterprise Logging application block can be configured using the Enterprise Library Configuration utility. Both Log4Net and Enterprise Logging modify the XML config file, so manual configuration can be done easily. Both of them also support programmatic configuration as well.

Both loggers include logging to text files, databases, event log and email. Log4Net includes logging to the console with colored ANSI for enhanced readability.

Performance

My initial tests showed Log4Net being exponentially faster. Others have found this to be true as well. For more details and stats check out Loren Halvorson's Blog.

Flexibility

The Enterprise Logging provides full source code. And has an extensible trace listeners. Log4Net's Appenders offer similar functionality.

In summary the Enterprise Logging Application Block is a very full featured and extensible logging framework. If you are using any of the other Enterprise Application Blocks this would be the first logger to try. It's only downfall is that it's performance is lacking. Unlike Log4Net the Enterprise Library including the Logging Application Block is being updated quite regularly.

If you would like to try one of these logging frameworks out check out these tutorials:
Some other Logging Frameworks:

Save to del.icio.us Add to Technorati Add to dzone

Friday, March 28, 2008

Are ForEach Loops Slower Then For Loops?

While reading some of Microsoft's patterns and practices material on optimizing .NET code I ran across an interesting comment. Microsoft recommends using for instead of foreach in performance sensitive loops.

To test I started out using the ArrayList on a bunch of strings. To get the best accuracy I P/Invoked GetTickCount . Here is what I found:

Collection SizeForeach Loop TicksFor Loop TicksPerformance Gain
5,000,0001099317.20%
10,000,00023417236.05%
20,000,00046835830.73%
50,000,000120292030.65%


Although the lower numbers were a bit sporadic the for loop did seem to function roughly 30% faster then the foreach. Lets look at what the foreach is doing. First lets look at a simple foreach loop:


foreach (string str in arr)
{
// Do Something
}


What is the foreach operator doing? It's calling GetEnumerator from arr and then calling MoveNext on each iteration.


IEnumerator enumerator = arr.GetEnumerator();
while (enumerator.MoveNext())
{
string str = (string)enumerator.Current;
// Do Something
}


MoveNext is called on each iteration of the loop. Using Lutz Roeder's .NET Reflector we can see what MoveNext is doing.


public bool MoveNext()
{
if (this.version != this.list._version)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
}
if (this.isArrayList)
{
if (this.index < (this.list._size - 1))
{
this.currentElement = this.list._items[++this.index];
return true;
}
this.currentElement = dummyObject;
this.index = this.list._size;
return false;
}
if (this.index < (this.list.Count - 1))
{
this.currentElement = this.list[++this.index];
return true;
}
this.index = this.list.Count;
this.currentElement = dummyObject;
return false;
}


We could step through this but lets look at only the lines that are run:



public bool MoveNext()
{
if (this.version != this.list._version) { }
if (this.isArrayList)
{
if (this.index < (this.list._size - 1))
{
this.currentElement = this.list._items[++this.index];
return true;
}
}
}


So it looks like our loop execution is being slowed down by some properties and conditional statements. This is insightful, but do we really care? Well if you are still reading this you might. If you are in the rare case that you need a insanely fast loop and you need precious milliseconds when looping millions of records you might want to replace your foreach loops with for loops. As for the sane rest of us I'm sure we can get a better return if we optimize the code within the loop.

Supplemental Links:
Loop Test Code

Save to del.icio.us Add to Technorati Add to dzone

Tuesday, March 25, 2008

Class Creation - To Create or Not To Create, That Is The Question.

It can be difficult to decide when to create a class. Most of the time it's clear when you need to create a class to perform a task but I've put together a list for those edge cases. Hopefully this will help you resolve your dilemma.

Reasons to create a class:


  • Model real-world objects
  • Model abstract objects
  • Reduce complexity
  • Isolate complexity
  • Hide implementation details
  • Limit effects of changes
  • Hide global data


Reasons not to create a class:

  • I want a class of my own
  • I want to name a class after myself
  • Tied of adding code to the same class
  • Because I want to


A large class or method is a telling sign that you need to refactor, but you need to elaborate on what your class or method is doing. Then try to break it out into logical or physical operations.

Also when you create your new class be sure to put it in it's own code file. I've found that maintaining a one to one relationship with your class and code files is critical to the maintainability of your code.

Save to del.icio.us Add to Technorati Add to dzone

Thursday, March 20, 2008

Multiple Boolean Variables Without all The Declarations

I need to have a bunch of boolean variables. Say I have a Car class that needs to indicate a bunch of features like air conditioning, leather seats, stereo, power windows, power seats or alarm system. I could declare the Car class like this:


public Car
{
public string Make;
public string Model;
public bool AirConditioning;
public bool LeatherSeats;
public bool Stereo;
public bool PowerWindows;
public bool PowerSeats;
public bool AlarmSystem;


Instead of declaring each variable individually you could use an enumeration flag. An enumeration flag uses bit wise operations on integer variables to represent multiple boolean variables. If you want to know more about bit wise operators take a look at the bit wise operation Wikipedia article.

Going back to our Car class we could declare the enumeration flag:


[Flags]
enum CarFeatures
{
AirConditioning=1,
LeatherSeats=2,
Stereo=4,
PowerWindows=8,
PowerSeats=16,
AlarmSystem=32
}


Remember each value needs to be a power of 2, because we are using them as bits and not as an integer. If you wanted more values then we have here you would continue with 64, 128, 256, 512, 1024, 2048, etc... Now we can declare our Car class's features as one variable:


public class Car
{
public string Make;
public string Model;
public CarFeatures Features;
}


To initialize our Car's features we can assign it as we would any other enumerator:


Car myCar = new Car();
myCar.Features = CarFeatures.Stereo;


If we want to assign it more then one value we need to use the or ("|") bit wise operator. It might help to think of the bit wise or ("|") as a merge or combine operator. Here is what it would look like in our Car example;


Car myCar = new Car();
myCar.Features = CarFeatures.Stereo | CarFeatures.AirConditioning;


Now that we have our features assigned to the Car how do we use them? Lets say we are looking for Cars that have air conditioning. Couldn't we use a standard comparison test? Example:


if (myCar.Features == CarFeatures.AirConditioning)
{
// This car has Air Conditioning
}


You would find cars with air conditioning, but the cars you would find wouldn't have any other features, including our previous car that had a stereo and air conditioning. In order to find cars that have air conditioning regardless of the other features we need to use the bit wise and ("&") operator. Lets rewrite our previous example to use the bit wise and ("&") operator:


if (myCar.Features & CarFeatures.AirConditioning == Car.Features.AirConditioning)
{
// This car has air conditioning and possibly other features as well.
}


The bit wise and ("&") operator extracts the CarFeatures.AirConditioning bit from myCar.Features. We need to the equals operator to actually test the bit we extracted. If the bit is "off" we will get 0. If the bit is "on" we will get the value of the bit in the CarFeatures.AirConditioning bit this would be 1. Here is a diagram of what is ocurring:


000101 (myCar.Features)
& 000001 (CarFeatures.AitConditioning)
--------
000001

000001 == 000001? True


Now you understand what going on. What about the length of the comparison? Well you can shorten it like this:


if (myCar.Features & Features.AirConditioning != 0)
{
// This car has air conditioning.
}


Both statements are correct. Just use them consistently.

Flag enumerations are great, but you should not go and replace all of your boolean values with enumeration flags. There are times when they can come in handy, but use them wisely.

Save to del.icio.us Add to Technorati Add to dzone

Tuesday, February 19, 2008

Singletons, Good Design or Global Disaster?

Singletons are objects that are instantiated only once throughout the life of your application. Singletons can be very useful, but like most things if they are over used they can create problems. In most cases if you can avoid using a singleton you should. With that said lets take a look at singletons and you can decide for yourself where and when to use them.

In C# a declaration of a singleton is very simple. It is simply a static object. Example:


public static MyClass MySingleton;

When you reference MySingleton you will always receive the same object from anywhere within your application. There are exceptions to this. In C# you must be in the same application domain. To ensure that other developers can't instantiate MyClass elsewhere you can make the constructor private.

Since singletons are globals and as such can be referenced anywhere in the application instantiation of the singleton is critical. I will describe 3 methods to instantiate your singleton: automatic, lazy and managed. There are strengths and weaknesses to each.

Automatic instantiation is when the singleton is created on application start. Example:

public static MyClass MySingleton = new MyClass();

This instantiation can't be used if the class constructor requires variables that are not available during application start. If you can change the MyClass constructor you can change it to not take variables, but it would not be ready to use until you set the required properties. Another option is lazy initialization.

Lazy initialization is when you instantiate your singleton on first use. Example:

public class MyClass
{
private static MyClass _mySingleton = null;

public static MyClass MySingleton
{
get
{
if (_mySingleton == null)
_mySingleton = new MyClass();

return _mySingleton;
}
}
}

In this example you would call MyClass.MySingleton to get the instance of MyClass. This is the method I prefer, but it can get messy if you have dependences. If you need more control of the initialization process you should use managed initialization.

Managed initialization gives you total control of initialization of a singleton. You get to/have to manually initialize the singleton. This means that you need to ensure that you have fully initialized your singleton before you use it. Example:

public class MyClass
{
private static MyClass _mySingleton = null;

public static MyClass MySingleton
{
get { return _mySingleton; }
set { _mySingleton = value; }
}
}

This just exposes the MySingleton object as a property. You would need to new up a MyClass object and assign it to MySingleton. Example:


MyClass.MySingleton = new MyClass();


With managed initialization you need to ensure that you initialize the MySingleton object before you try to use it. You could help ensure the MySingleton object is initialized by including an error when trying to use the MySingleton object without first initializing it. Example:

public class MyClass
{
private static MyClass _mySingleton = null;

public static MyClass MySingleton
{
get { return _mySingleton; }
set
{
if (_mySingleton == null)
throw new Exception("MySingleton has not been initialized yet.");

_mySingleton = value;
}
}
}

This will just help identify runtime errors quicker and easier.

So as you can see you can use any class as a singleton. Singletons can be initialized in a few different ways. The main advantage to Singletons can be it's weakest and strongest benefit. Singletons, because they are just a global variable, can be called anywhere in your application. This can be very helpful for classes that need to be used in many different places. This can be a problem when it comes to testing. If your testing a method that calls anything in a singleton the singleton needs to be setup for the test as well, and thus is tested as well. This also prevents the use of mock objects in testing. If you would like to learn more about mock objects check out this paper.

Singletons are a simple design pattern that can be a great tool, just consider the risks when using them.

Save to del.icio.us Add to Technorati Add to dzone

Friday, February 15, 2008

String is a reference or a value type?

I've had a number of discusions about value types and reference types in .NET. Some developers have a good dictionary meaning of a reference type and a value type. Getting down to the nitty gritty of reference types and value types seems to stump even some of the brightest developers.

A few years ago I was interviewing for a software development position at a larger company and the interviewer asked what is the difference between a reference type and a value type. Wanting to make a good impression I whipped out my detailed dictionary answer: "A reference type is a pointer to a place in memory where a class or other object is located. A value type is the binary value." The interviewer then wanted to verify my knowledge by showing me this method:

void Calc(int x)
{
   x = 3;
}

and asking what would be outputted if he ran:

int x = 2;
Calc(x);
Console.WriteLine(x.ToString());

And I answered that it would output 2. This is true because the x value is copied to the Calc method. In the Calc method the x value is in a completely different memory location, so changing x in the Calc method doesn't do anything to the original value passed in.

The interviewer then declared a class:

public class MyObject
{
   public int x;
}


He changed the method to be:

void Calc(MyObject myObject)
{
   myObject.x = 3;
}

And asked what would be outputted in this code:

MyObject myObject = new MyObject();
myObject.x = 2;
Calc(myObject);
Console.WriteLine(myObject.x.ToString());


I answered that the output would be 3. This is true because myObject.x in the WriteLine statement points to the same myObject.x in the Calc method. This is because the myObject reference, despite being copied into the Calc method, still is a reference. A pointer to the myObject class instance. A different pointer, but to the same memory location.

The interviewer then changed the Calc method:

void Calc(MyObject myObject)
{
   myObject = new MyObject();
   myObject.x = 3;
}


He asked again what does the following code output:

MyObject myObject = new MyObject();
myObject.x = 2;
Calc(myObject);
Console.WriteLine(myObject.x.ToString());


I answered 2. That is because since the myObject reference in the Calc method is set to a new MyObject instance the x value that changes isn't the instance in the myObject that was passed into the Calc method. So why doesn't the myObject value change to the new instance? Because the myObject reference is a copy of the reference that was passed in. Meaning that the myObject reference in the Calc method points to the same class instance, but if itself is changed to point to something else the copied value that was passed into the Calc function still will not change.

The interviewer then asked what if you wanted to be able to new up new objects in the Calc method and have them affect the myObject that was passed in what would need to be changed?

I said the myObject value would need to be passed in by reference and I made the following code changes:

void Calc(ref MyObject myObject)
{
   myObject = new MyObject();
   myObject.x = 3;
}

MyObject myObject = new MyObject();
myObject.x = 2;
Calc(ref myObject);
Console.WriteLine(myObject.x.ToString());


Now it would output 3. This is because the myObject is now the same inside the Calc method as it is when it is passed in. It is no longer copied.

The interviewer then changed MyObject to string. Here is the code:

void Calc(string x)
{
   x = "3";
}

string x = "2";
Calc(x);
Console.WriteLine(x);


Then the interviewer asked what was x?

So what is it? Looks similar to the int example doesn't it? String isn't a simple value. String is a reference type. And when you assign "3" to it you are essentially pointing the reference to a new memory location containing "3". And since we did not copy the string by reference the x assignment in the Calc method doesn't affect the output. The original "2" assignment is displayed.

The Interviewer then asked what would the following output:

public class MyObject
{
   public MyObject(int x) { this.x = x; }
   public int x;
}

MyObject a = new MyObject(1);
MyObject b = new MyObject(1);
Console.WriteLine(a == b);

I answered it would output false. Even though the values in the class are the same the equals operator compares the reference or the pointer (the area in memory) not the values since it is a reference type.

Then he asked then what about this:

string a = "1";
string b = "1";
Console.WriteLine(a == b);

It's a reference type, but you know that they are equal. Why? Because strings overloaded the equals operator to compare the string value and not the reference which is the default behavior for reference types.

So strings along with classes, arrays and delegates are reference types. Values types include all numerics (int, double, etc...), bool, char, date, struct (even if they include refs) and enumerations (enum).

Save to del.icio.us Add to Technorati Add to dzone

Tuesday, February 12, 2008

Family Website with Blog and Pictures

Seems like a simple request, right? Well it wasn't an easy choice for me because I had previously created a ASP web album and family web site that had some unique features. Single or groups of pictures could be tagged. Pictures could be searched based on people in the picture, tag and date range. I created a VB6 app to upload and label the pictures which was converted to C#. It worked fairly well, but I eventually stopped maintaining the web site. A few years ago I tried to revive it from the dead, but it was past it's prime. My first thought was to just do something similar in ASP.NET. Well after I had outlined what I wanted to do it would be quite a bit of work. There has to be others out there that want the same type of web site, so I scowed the internet to see what was available. I tried dotNetNuke. It was close to what I wanted so I went to find a host. Since my domain was registered with godaddy I gave their hosting a shot. Well long story short it wasn't going to be easy to get dotNetNuke up and running. I did get it limping along, but this needed to be quick and take as little time as possible. I tried a few other things: WordPress, Weebly, Familiva. I ended up using blogger with Picasa's web albums. This is easy to use. Maybe in the future I'll have some time to whip up a snazzy family site again. If you want to check out my family's blog visit www.jjesnroth.com.

Save to del.icio.us Add to Technorati Add to dzone