Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Saturday, December 6, 2008

Regular Expression Vowel Counter

In this example we are going to touch on two objectives of the 70-536 exam.

Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application
  • Regex class
  • MatchCollection class

Implementing serialization and input/output functionality in a .NET Framework application
  • FileStream class
  • StreamReader class
To show these classes in use we are going to count the number of vowels in 25 popular search terms (popular according to Lycos) These strings are included in a link in the resources.

Regex and File Stream Example

using System;
using System.Text.RegularExpressions;
using System.IO;

namespace SimpleRegExExample
{
class Program
{
static void Main(string[] args)
{
// In this example we are going to hit two exam points,
// using a file stream and using a regular expression.
// This example only touches on the use of regular
// expressions... in fact there are whole books on the subject
// as it can be cosidered a language it self. Feel free
// to comment on specific regular expressions you want
// to see examples on.

//Match only the vowels...
Regex vowels = new Regex("[aeiou]", RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection mc;
FileStream fs = null;
StreamReader reader = null; ;
String current_line;

// A filestream can throw a number of exceptions if the file
// you use to create it can't be found or accessed ( such as
// security reasons, a disc error, etc)

try
{
// For this example we are reading in a text file with 25 lines of text.
// It's hard to make up that much data, so I just took the top 26-50
// search terms on lycos and placed them in a text file. Some of the terms
// were kind of racy, like "Kendra Wilkinson Playboy Playmate"...
// If you stumbled here hoping to find pictures of said search term, this
// is the wrong place.
fs = new FileStream("lycos_top_search_terms_26_to_50.txt",FileMode.Open);

//Life is easier when we wrap the filestream ina stream reader,
// then we don't have to code the buffering for read line operations
reader = new StreamReader(fs);
}

// This is bad, you really should catch specific exceptions...
// but we skip it for this example.
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
Console.Out.WriteLine(e.StackTrace);
if (reader != null)
{
reader.Close();
}
if (fs != null)
{
fs.Close();
}
return;
}

while (!reader.EndOfStream)
{
current_line = reader.ReadLine();
mc = vowels.Matches(current_line);

// The match collect now contains the results of running the regular
// against the line we read in from the file
Console.Out.WriteLine("The search term \"" + current_line + "\" has " + mc.Count + " vowels in it");
}

//Close the reader first
reader.Close();
//Now close the file
fs.Close();
}
}
}

Output
The search term "Flickr Picture" has 4 vowels in it
The search term "Brooke Burke Dancing star" has 8 vowels in it
The search term "Kendra Wilkinson Playboy Playmate" has 10 vowels in it
The search term "Julianne Hough Watching stars" has 9 vowels in it
The search term "Twilight Vampire movie out now" has 11 vowels in it
The search term "Lindsay Lohan Relatively quiet week" has 13 vowels in it
The search term "Holly Madison Playboy Playmate #2" has 9 vowels in it
The search term "Black Friday Look for your local ad" has 11 vowels in it
The search term "Harry Potter New movie in the works" has 10 vowels in it
The search term "Weight Watchers Getting ready for the new year" has 13 vowels in it
The search term "Carmen Electra Taking it slow" has 9 vowels in it
The search term "Jessica Alba New Mom" has 7 vowels in it
The search term "Limewire Download site" has 9 vowels in it
The search term "Fox News National new coverage" has 11 vowels in it
The search term "Lowes Do-it-yourself" has 7 vowels in it
The search term "Santa Claus Coming to town" has 8 vowels in it
The search term "Beyonce Knowles Is Sasha Fierce" has 11 vowels in it
The search term "Home Depot The Lumberyard" has 8 vowels in it
The search term "Paula Abdul Leaving American Idol?" has 14 vowels in it
The search term "US Postal Service Holiday Packages " has 12 vowels in it
The search term "Jennifer Lopez Keeping it quiet" has 12 vowels in it
The search term "Haley Joel Osment On Broadway" has 10 vowels in it
The search term "Lil Wayne New CD release" has 8 vowels in it
The search term "Angelina Jolie Mom again?" has 11 vowels in it
The search term "Plentyoffish.com Dating site" has 8 vowels in it


Additional Resources
Introductions to Regular Expressions (Microsoft)
FileStream Class (Microsoft)
StreamReader Class (Microsoft)
Regular Expression Designer (Rad Software, a must have for non trivial regular expression testing)
Test File used in this example

non code related...
Lycos top 50 search terms (Lycos)

Monday, November 24, 2008

The December 21, 2012 Date Formatting Example

One of the objectives in Exam 70-536 is to ensure knowledge formatting dates. Specifically in the

Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application section, we see

  • Format date and time values based on the culture

The .NET framework makes this task pretty straight forward with the System.Globalization namespace. Within this name space there is the CultureInfo class. The CultureInfo class contains all of the specific formatting rules for a specific culture. Cultures are divided up by language and region.

So to exercise this objective we print out a date in five different culture specific formats. We pick the date December 21, 2012, the end of the Mayan calendar as a fun date to use. Links are provided below about this date if you want to see what all of the buzz is about. But onto the code sample

Date Formatted Based on Culture Example

using System;
using System.Globalization;

namespace DateTimeFormatExample
{
class Program
{
static void Main(string[] args)
{
//This example is going to show how to format
// a date for several cultures. We could pick
// any date for this example, but just for kicks
// we'll pick December 21, 2012. This date is
// mysterious to astrologists and conspiracy
// theorists because it is the end of the Mayan
// calandar... will it be THE end? Who knows, but
// we'll use it here for our example.

// Declare the date December 21, 2012
DateTime dt = new DateTime(2012, 12, 21, 4, 0, 0);

//First let's print out for US English
CultureInfo en_us_ci = new CultureInfo("en-US");
//Print short date format
Console.WriteLine("US English " + dt.ToString("d", en_us_ci));

//Next let's print out for Chinese, PRC
CultureInfo zh_cn_ci = new CultureInfo("zh-CN");
Console.WriteLine("Chinese, PRC " + dt.ToString("d", zh_cn_ci));

//Next let's print out for German (Germany)
CultureInfo de_de_ci = new CultureInfo("de-DE");
Console.WriteLine("German (Germany) " + dt.ToString("d", de_de_ci));

//Next let's print out for Hebrew (Israel)
CultureInfo he_il_ci = new CultureInfo("he-IL");
Console.WriteLine("Hebrew (Israel) " + dt.ToString("d", he_il_ci));

//Next let's print out for Punjabi (India)
CultureInfo pa_in_ci = new CultureInfo("pa-IN");
Console.WriteLine("Punjabi (India) " + dt.ToString("d", pa_in_ci));
}
}
}

Date Format Example Output
US English 12/21/2012
Chinese, PRC 2012/12/21
German (Germany) 21.12.2012
Hebrew (Israel) 21/12/2012
Punjabi (India) 21-12-12

Additional Resources
CultureInfo Class (Microsoft)

Non code related...
2012 (Wikipedia)
Survive 2012

Tuesday, October 21, 2008

How do I retrieve information about the current process using C#?

I can think of many occasions when I have been diagnosing an issue on a customer machine and I find myself opening the task manager to gather valuable information about the application under question. If the customer will allow it, I will usually take the task manager one step further and use the Process Explorer from SysInternals.

But there has to be a better way, your application should be able to grab that information without using another application. And in fact it can by using the System.Diagnostics namespace. Conveniently this is also a requirement on the 70-536 exam in the "Manage system processes and monitor the performance of a .NET application by using the diagnostics functionality of the .NET Framework." section. Specifically the objective is to:

"Retrieve information about the current process"

This is made possible by the Process class within the System.Diagnostics class. Before we get into the code sample, it should be noted that a Process has a number of attributes. Many of these attributes are omitted to keep it short and sweet. Refer to the docs for the full list of Process attributes.

Current Process Info Example

using System;
using System.Diagnostics;

namespace CurrentProcessInfo
{
class Program
{
static void Main(string[] args)
{
//First lets get our parent process
Process my_process = Process.GetCurrentProcess();

// Now we'll spit out some pertinent info on our process
// Only a handful of the properties are referred to here,
// see the docs for the full list
Console.WriteLine("\nThe current process has the following attributes:");
Console.WriteLine("------------------------------------");
Console.WriteLine("Process Name: " + my_process.ProcessName);
Console.WriteLine("Window Title: " + my_process.MainWindowTitle);
Console.WriteLine("Running on: " + my_process.MachineName);
Console.WriteLine("Priority: " + my_process.PriorityClass.ToString());
Console.WriteLine("Responding: " + my_process.Responding);
Console.WriteLine("Virtual Memory: " + my_process.VirtualMemorySize64);
Console.WriteLine("------------------------------------");
}
}
}


Additional Resources
Process Class (Microsoft)
System.Diagnostics Namespace (Microsoft)

Monday, October 20, 2008

Set a break point through code with C#

If you have spent time debugging, you probably know you can click any code line to add a break point. If you have spent some more time you have probably even figured out how to set conditional breakpoints, as Sara Ford explains in this "tip of the day".

But did you know you can also cause a break point to trigger from within your code? It is actually pretty easy using the Debugger class within the System.Diagnostics name space. I learned about the Debugger class while looking over the specifics for the "Debug and trace a .NET Framework application by using the System.Diagnostics namespace." section of the 70-536 exam.

If this code is run outside of the debugger, the OS will ask you if you would like to debug the process.

Debugger Break form Code Example

using System;

namespace BreakFromCodeExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Thing are going fine...");
Console.WriteLine("then something goes wrong and we want to break");
Console.WriteLine("so we can investigate further...");

//This is the call that fires the break point event
System.Diagnostics.Debugger.Break();

Console.WriteLine("You are now free to place break points with or without a GUI.");
}
}
}

Additional Resources
Debugger Class (Microsoft)
System.Diagnostics Namespace (Microsoft)

Implemeting the IConfigurationSystem Interface

After a long hiatus... getting back in the writing zone....

Within the "Embedding configuration, diagnostic, management, and installation features into a .NET Framework application" section of Exam 70-536 we are instructed to "Implement IConfigurationSystem Interface".

This seemed like a fairly straight forward task so I immediately looked up the interface in the MSDN docs. However, upon reading about the interface, I think someone goofed. The documentation specifically says that the IConfigurationSystem Interface "
supports the .NET Framework infrastructure and is not intended to be used directly from your code."

So maybe we don't need to know too much about this interface after all. Just in case the error is on the side of the documentation, you need to implement two methods to support the IConfigurationSystem Interface
  • GetConfig
  • Init

GetConfig returns an object and takes configKey (String) as a parameter.
Init returns void and takes no parameters.

Additional Resources
IConfigurationSystem Interface (Microsoft)

Saturday, May 24, 2008

How Do You Retrieve Information About All Network Connections?

One of the objectives of the MCTS .NET Framework exam is to

Embed management information and events into a .NET Framework application. (Refer System.Management namespace)

and within that exam objective there is the specific objective

Retrieve information about all network connections.

I started to look through the System.Management namespace and found the ManagementObject and the ManagementObjectSearcher. Then the clarity of the examples of the descriptions and examples began to muddy. I understood that the ManagementObjectSearcher was using an ObjectQuery object to perform the search. It was completely unclear WHAT was being queried.

My investigations then lead me to the Windows Management Interface, known as WMI. What does this have to do with ObjectQuery and the ManagementObjectSearcher classes? Well, WMI and the underlying WMI classes are what is actually being queried. The queries are written in a SQL derivative named WQL. There is a dizzying variety of information exposed by WMI.

After the mechanics of writing a query are understood, the next task is to find the correct WMI class that encapsulates the information you need. In the case of our question at hand, we are looking for networking information.

At first I was happy to find the Win32_NetworkConnection class, but found that it did not return information for me. (Despite having a connection up for writing this post). The next promising class was the Win32_NetworkAdapter class. Using this class I created the example below that retrieves information about all network connections.

A "gotcha" to consider before reviewing the code below:
My first version of the code listed a number of adapters. I then determined that it listed physical AND logical network adapters. You will see an if block in the code to distinguish between physical and logical adapters.

Retrieve Information About All Network Connections Example

using System;
// A reference to the System.Management assembly needs
// to be added to your project...
using System.Management;

namespace NetworkConnectionsExample
{
class Program
{
static void Main(string[] args)
{
// In order to use ManagementObjectSearcher, we need to
// supply an query string to search on. We are searching
// against differenct classes exposed by the Windows Management
// Interface(WMI).
ManagementObjectSearcher network_connections =
new ManagementObjectSearcher(
"SELECT * FROM Win32_NetworkAdapter");

Console.WriteLine("\nFirst we will just list the names of all physical adapters");
Console.WriteLine("and their connection status");
Console.WriteLine("-----------------------------");

// The query of the underlying ObjectQuery object is not executed
// until the Get() function is executed.
foreach (ManagementObject connection in network_connections.Get())
{
// Knowledge by experiment... on my machine there were a number
// of network adapters displayed on my first version of this code.
// I know I only have three pyhisical adapters (Wireless, 10/100,
// and 1394) so I empirically determined that the Management Objects
// with the NetConnectionStatus property were physical apdapters and
// not logical adapters... mileage may vary, results not insured ;)
if (connection.Properties["NetConnectionStatus"].Value != null)
{
Console.WriteLine("Product Name: " + connection.Properties["ProductName"].Value);
Console.WriteLine("Connection Status: " + connection.Properties["NetConnectionStatus"].Value);
Console.WriteLine("-----------------------------");
}
}

Console.WriteLine("\nNext we will show all of the information availalbe for each physical adapter.");
Console.WriteLine("Probably more than you ever wanted to know about your network adapter, but your software might need to know it...");
Console.WriteLine("-----------------------------");

foreach (ManagementObject connection in network_connections.Get())
{
if (connection.Properties["NetConnectionStatus"].Value != null)
{
foreach (PropertyData d in connection.Properties)
{
Console.WriteLine("-- Name: " + d.Name + " Value: " + d.Value);
}
Console.WriteLine("-----------------------------");
}
}
}
}
}

Additional Resources
ManagementObjectSearcher class (Microsoft)
WMI Operating System Classes (Microsoft)
Win32_NetworkAdapter class (Microsoft)

Thursday, May 22, 2008

How can I read an EventLog?

Perhaps you have a need to read from a system event log. Perhaps you have even found the System.Diagnostics namespace. Upon inspecting the EventLog class you will notice a "Write" method but the absence of a complimentary "Read" operation. You are not going crazy, there really isn't a read method.

Instead you need to understand a little more about the EventLog object. The entire contents of an EventLog are read in when the EventLog is constructed (if the variant with a logname is used) or when the Log property is set for the object. The results of reading the event log are stored in the Entries property. The entries property is a collection of EventLogEntry objects. If you would like to see the contents of a particular EventLogEntry, you need "massage" the object a little more by accessing specific properties of the EventLogEntry class.

It is important to note that the Entries property is a read only property. You can't change the contents of the event log by modifying the Entries property. In order to change the event log, you need to use the "Write" methods.

The example below shows how to access the 10 most recent log entries from the System event log.

System Event Log Read Example

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace ReadEventLogExample
{
class Program
{
static void Main(string[] args)
{
// There are three default event logs, Application, System and Security
EventLog systemLog = new EventLog("System");
// The entries member contains all the entries in the event log
// There is no need to perform a specific read operation on the event log
// The Entries member is read only, so you will need to use the write
// methods if you want to write to the EventLog
int entryCount = systemLog.Entries.Count;
entryCount = entryCount - 1; //We are using the count for a zero based index...

Console.WriteLine("The last 10 entries in the System event log");

for (int i = 0; i < 10; i++)
{
if (entryCount - i >= 0) //We only want positive indexes...
{
Console.WriteLine("------------------------------------\n");
Console.WriteLine("Time Generated: " + systemLog.Entries[entryCount - i].TimeGenerated);
Console.WriteLine("Time Written: " + systemLog.Entries[entryCount - i].TimeWritten);
Console.WriteLine("Source: " + systemLog.Entries[entryCount - i].Source);
Console.WriteLine("Entry Type: " + systemLog.Entries[entryCount - i].EntryType);
Console.WriteLine("Message: " + systemLog.Entries[entryCount - i].Message + "\n");
}
}
}
}
}

Additional Resources
EventLog Class (Microsoft)
EventLogEntry Class (Microsoft)

What is the difference between byte and Byte in the .NET Framework?

Have you ever started to type 'by' while writing code in Visual Studio and seen both an upper case and lower case "byte" in the intellisense menu and wondered what the difference was?

Lower case "byte" is a built in type in C#. System.Byte is a class built into the .NET framework that represents a byte. The secret is that this built in type is an alias to the System.Byte class. Different .NET languages have different aliases based on the semantics of the particular language, but they all map to specific object types in the .NET framework. This allows code to be written more "cleanly" and still easily compile to the correct type in the .NET framework.

Let's confirm the statement that the C# built in type 'byte' is really an alias of the System.Byte class.

byte and System.Byte Example

using System;
using System.Collections.Generic;
using System.Text;

namespace ByteDifferenceExample
{
class Program
{
static void Main(string[] args)
{
byte small_b_byte = 1;
Byte large_b_byte = 2;

Console.WriteLine("The value of the little b byte is: " + small_b_byte);
Console.WriteLine("The type of the little b byte is: " + small_b_byte.GetType());

Console.WriteLine("----------------------------");

Console.WriteLine("The value of the big b byte is: " + large_b_byte);
Console.WriteLine("The type of the big b byte is: " + large_b_byte.GetType());

Console.WriteLine("----------------------------");

if (small_b_byte.GetType() == large_b_byte.GetType())
{
Console.WriteLine("Summary: byte and Byte have the same type!");
}
else
{
Console.WriteLine("Summary: byte and Byte have different types");
}
}
}
}

Output of byte and System.Byte Example

The value of the little b byte is: 1
The type of the little b byte is: System.Byte
----------------------------
The value of the big b byte is: 2
The type of the big b byte is: System.Byte
----------------------------
Summary: byte and Byte have the same type!

Additional Resources
Built-In Types Table, C# (Microsoft)

Monday, May 19, 2008

What is a stack good for?

A stack is a specialized list data structure that enforces LIFO (last in, first out) ordering of data. Thinking of a stack as a physical stack of plates (and data items as the plates), you can only take the last plate that you added to the stack.

The stack data structure is among the most useful structures in Computer Science. Stack usage appears at all levels of programming, from operating system kernels to high level languages like those in the .NET framework. Saying that a stack is useful is easy to say, but let's look at some tasks that a stack can be used for:

Stack Usage Examples

In a future posting a detailed example that uses a stack will be provided.

Additional Resources
System.Collections.Stack Class (Microsoft)
Stacks (Wikipedia)

Monday, April 14, 2008

How can you sort a list of strings in the .NET Framework?

The .NET Framework provides a simple efficient mechanism to sort a list of strings. The ArrayList class contains a Sort() method that allows the items in the ArrayList to be sorted in ascending order.

ArrayList Sort Example
using System;
using System.Collections;

// This is an example of using the .NET Framework and the
// Sort() method of the ArrayList class
namespace CollectionSortExample
{
class Program
{
static void Main(string[] args)
{
//Let's fill the ArrayList with some strings
ArrayList exampleList = new ArrayList();
exampleList.Add("C# Video Game Programming");
exampleList.Add("Really Thick Programming Book");
exampleList.Add("1984");
exampleList.Add("Alice in Wonderland");

//Print the list before it is sorted
Console.WriteLine("The unsorted list looks like:");
foreach (string item in exampleList)
{
Console.WriteLine("- {0}", item);
}

//Now we can do some "magic" and sort the
// ArrayList by caling the Sort() method.
exampleList.Sort();

//Print the list after it is sorted
Console.WriteLine("\n\nThe sorted list looks like:");
foreach (string item in exampleList)
{
Console.WriteLine("- {0}", item);
}
}
}
}

Output of ArrayList Sort Example

The unsorted list looks like:
- C# Video Game Programming
- Really Thick Programming Book
- 1984
- Alice in Wonderland

The sorted list looks like:
- 1984
- Alice in Wonderland
- C# Video Game Programming
- Really Thick Programming Book
Additional Resources
ArrayList Class (Microsoft)

Tuesday, April 8, 2008

What attribute should you add to a class to allow it to be serialized?

A class can be serialized when it has the "Serializable" attribute. Serialization is the process of storing the contents of an object to long term storage. If you will only be using .NET Framework based applications to process your serialized objects, then the BinaryFormatter class will be the most efficient. If you will be transmitting your serialized object across a network or sharing it with a non .NET Application, then the SoapFormatter class should be used to export the object to the XML based SOAP format.

Serialization Example
Note that you need to add a reference to System.Runtime.Serialization.Formatters.Soap.dll to your project before compiling the code below. Unlike the BinaryFormatter class, the SoapFormatter class is not included by default.


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

namespace SerializationExample
{
[Serializable]
class ObjectToSerialize
{
string sName;
int iCount;
double dPrice;

public ObjectToSerialize(string newName, int newCount, double newPrice)
{
sName = newName;
iCount = newCount;
dPrice = newPrice;
}
}

class Program
{
static void Main(string[] args)
{
ObjectToSerialize o = new ObjectToSerialize("Video Game", 1, 50.00);

// Create the files to save the data to
FileStream binary_fs = new FileStream("Serialization_Example.bin", FileMode.Create);
FileStream xml_fs = new FileStream("Serialization_Example.xml", FileMode.Create);

// Create a BinaryFormatter object to perform the serialization
BinaryFormatter bf = new BinaryFormatter();
// Create a SoapFormatter object to perform serialization
SoapFormatter sf = new SoapFormatter();

// Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(binary_fs, o);
// Use the SoapFormatter object to serialize the data to the file
sf.Serialize(xml_fs, o);

// Close the files
binary_fs.Close();
xml_fs.Close();
}
}
}


Binary Results
SOAP Results
The XML results of the SOAP Serialization can be found here: SOAP Serialization Results

Additional Resources
BinaryFormatter Class (Microsoft)
SoapFormatter Class (Microsoft)

Tuesday, March 25, 2008

What type of return types can Main have?

In C#, Main can return a void type and an int type. Returning a void type is perhaps the most commonly used return type for main, but returning an integer value from main is also useful when other applications will be running your application, such as being run by a batch file. The integer value returned from an int main method will be stored in the environment variable %ERRORLEVEL%

Additional Resources
Main() Return Values in C# (Microsoft)

Which access modifiers can be applied to a class in the .NET Framework?

The following access modifiers can be applied to classes. These modifiers determine which classes in the object hierarchy can use the class.
  • public The class can be accessed from any assembly
  • private The class can only be referenced from within the same class
  • protected The class can be accessed from the same class or any descendant of the class
  • internal The class can be accessed from any class within the same assembly
Additional Resources
C# Class Access Modifiers (Microsoft)
VB.NET Access Modifiers (Microsoft)

Monday, March 24, 2008

How can you prevent your class from being inherited by another class in the .NET framework?

You can protect your class from being inherited by another class by using the "sealed" modifier on your class. If any class tries to inherit from your sealed class, they will get an error. Why would anyone want to seal a class? Classes are sealed when you would like to prevent static members from being changed. So if you have a class that define a value for BLACK, you can use sealed to prevent other classes from changing (intentionally or unintentionally) changing BLACK to some other value other than the color of black.

The code below will not compile and will have have the following error:
'SealedExample.SealedErrorClass': cannot derive from sealed type 'SealedExample.ExampleClass'

Sealed Class Example

namespace SealedExample
{
sealed class ExampleClass
{
public void MethodToInherit()
{
Console.WriteLine("This class is sealed so you can't inherit this method");
Console.WriteLine("Even though the method is public");
}
}

class SealedErrorClass : ExampleClass
{
//This does not work because ExampleClass is sealed
}

}

Additional Resources
Using Sealed Classes in .NET (C# Corner)
Sealed Keyword (Microsoft)

Saturday, March 22, 2008

Which classes can be used to compress streams in the .NET Framework?

Stream compression is used to save space and save bandwidth. There are two primary classes used for compression/decompression, the GZipStream and the DeflateStream classes.

The first thing one might like to know is, which compression class to use? That depends on how you would like to use the data. If you will be writing the stream to a file, the GZipStream class includes additional headers that make it suitable for opening with the gzip tool. The DeflateStream class does not include headers and thus has a slightly smaller size at the expense of being less portable (which may not be a concern if the data never leaves the computer that is running the application)

Both compresson methods are based on industry standard algorithms that are free of patent protecton. This allows you to incorporate them into your application with out worrying about intellectual property concerns.

In later posts we will explore source code for compressing and decompressing streams, but it is important to note the compression size limits. (Which will be repeated each time compression is discussed)

GZipStream and DeflateStream classes can't compress files larger than 4GB


Additional Resources
System.IO.Compression.GZipStream
System.IO.Compression.DeflateStream
Using GZIP for compression in .NET

Thursday, March 20, 2008

Name some classes in the .NET Framework that derive from the Stream Class

The following classes all have the Stream class as a base class.
  • FileStream
  • MemoryStream
  • CryptoStream
  • NetworkStream
  • GZipStream
By having a common base class, one is guaranteed that a certain set of properties and methods are available. So in this case, if your code only uses the methods of the stream class, then you can work with data from ANY stream data source.

Additional Resources
System.IO.FileStream
System.IO.MemoryStream
System.Security.Cryptography.CryptoStream
System.Net.Sockets.NetworkStream
System.IO.Compression.GZipStream

Tuesday, March 18, 2008

DriveInfo Properties

The DriveInfo class class models a drive and allows one to query info about the drives in the system. While writing the code to exercise this class I was tripped up by a "gotcha". Trying to query the volume label of a a CD drive when there is not a CD raises an exception. To keep the source code simple below, it was decided o check to see if the drive is ready (A CD drive will report not ready if there is there is not a CD)

// GetDrives returns an array of all the drives on the system
DriveInfo[] drives = DriveInfo.GetDrives();

Console.WriteLine("\n-------------------------------------\n");

//Please keep these two lines if you would like to use this code on your site
Console.WriteLine("DriveInfo Example");
Console.WriteLine("Created by Charles Cozad, http://www.mctscertification.blogspot.com");

Console.WriteLine("\n-------------------------------------\n");

foreach (DriveInfo drive in drives)
{
Console.WriteLine("Drive Name: {0}", drive.Name);
// We check if the drive is ready because calling some of
// the calls can throw exceptions (such as for a CD drive
// without a CD in it)
if (drive.IsReady)
{
Console.WriteLine("Drive Label: {0}", drive.VolumeLabel);
Console.WriteLine("Drive Type: {0}", drive.DriveType);
Console.WriteLine("Drive Formt: {0}", drive.DriveFormat);
Console.WriteLine("Available Free Space: {0}", drive.AvailableFreeSpace);
Console.WriteLine("Total Free Space: {0}", drive.TotalFreeSpace);
Console.WriteLine("Total Space: {0}", drive.TotalSize);
Console.WriteLine("\n+++++++++++++++++++++++++++++\n");
}
else
{
Console.WriteLine("Drive info skipped, because the drive is not ready");
}
}


Additional Resources
DriveInfo Class (Microsoft)

FileSystemInfo Properties

The FileSystemInfo Class is the base class for the FileInfo and DirectoryInfo classes. The best way to understand a particular class in the .NET Framework (and any language for that matter) is to write some code to use it.

Here is a snippet that uses many of the properties available in the FileSystemInfo class.

FileSystemInfo exampleFile = new FileInfo(@"C:\WINDOWS\System32\command.com");

Console.WriteLine("\n-------------------------------------\n");

//Please keep these two lines if you would like to use this code on your site
Console.WriteLine("FileInfo Example");
Console.WriteLine("Created by Charles Cozad, http://www.mctscertification.blogspot.com");

Console.WriteLine("\n-------------------------------------\n");

if (exampleFile.Exists)
{
Console.WriteLine("File Name: {0}", exampleFile.Name);
Console.WriteLine("File Extension: {0}", exampleFile.Extension);
Console.WriteLine("Full File Name: {0}", exampleFile.FullName);
Console.WriteLine("Creation Time: {0}", exampleFile.CreationTime);
Console.WriteLine("Last Access Time: {0}", exampleFile.LastAccessTime);
Console.WriteLine("Last Write Time: {0}", exampleFile.LastWriteTime);
Console.WriteLine("File Attributes: {0}", exampleFile.Attributes);
}
else
{
Console.WriteLine("File does not exist");
}

Additional Resources
FileSystemInfo Class (Microsoft)

Saturday, March 8, 2008

Using constraints with generics

Generics are less useful if you must write code that works with ALL objects because you would be limited to to the capabilities of the base Object class. Constraints allow you to limit the types of objects the caller can use. This additional information allows you (and the compiler) to make greater assumptions about which capabilities are available.

Generics can be constrained in the following ways
  • Interface - Allow only types that implement the specified interface
  • Base Class - Allow only types that are descendents of (or are) the specified base class
  • Constructor - Allow only types that have a parameterless constructor
  • Reference or value type - Allows value or reference types

Additional Resources
Constraints on Type Parameters, C# (Microsoft)
Defining and Using Generics, Visual Basic (Microsoft)

Range of built-in value types

The code snippet below will display the minimum and maximum values of the built in value types in the .NET Framework.


Console.WriteLine("Built-in value type ranges");

Console.WriteLine("SByte Min: " + System.SByte.MinValue + " Max: " + System.SByte.MaxValue);
Console.WriteLine("Byte Min: " + System.Byte.MinValue + " Max: " + System.Byte.MaxValue);
Console.WriteLine("Int16 Min: " + System.Int16.MinValue + " Max: " + System.Int16.MaxValue);
Console.WriteLine("Int32 Min: " + System.Int32.MinValue + " Max: " + System.Int32.MaxValue);
Console.WriteLine("Int64 Min: " + System.Int64.MinValue + " Max: " + System.Int64.MaxValue);
Console.WriteLine("Single Min: " + System.Single.MinValue + " Max: " + System.Single.MaxValue);
Console.WriteLine("Double Min: " + System.Double.MinValue + " Max: " + System.Double.MaxValue);
Console.WriteLine("Decimal Min: " + System.Decimal.MinValue + " Max: " + System.Decimal.MaxValue);


After you run the application you get the following output:
Built-in value type ranges
SByte Min: -128 Max: 127
Byte Min: 0 Max: 255
Int16 Min: -32768 Max: 32767
Int32 Min: -2147483648 Max: 2147483647
Int64 Min: -9223372036854775808 Max: 9223372036854775807
Single Min: -3.402823E+38 Max: 3.402823E+38
Double Min: -1.79769313486232E+308 Max: 1.79769313486232E+308
Decimal Min: -79228162514264337593543950335 Max: 79228162514264337593543950335
Additional Resources
TypeRanges Source

Name some commonly used interfaces in .NET

Interfaces act as a "contract" in the .NET Framework. The contract is that all classes implementing the interface will have a common set of members.

Of the many interfaces built into the .NET Framework, the interfaces listed below are commonly used and worth committing to memory.

  • IComparable (Implemented by types with values that can be ordered, this interface is required for sorting)
  • IDisposable (Allows for an object to be manually disposed, important for objects that consume limited or valuable resources)
  • IConvertible (Allows a class to be converted to a base type, such as int or string)
  • IClonable (Allows the implementing object to be copied)
  • IEquatable (Allows for two instances of a class to be compared using the == operator)
  • IFormattable (Allows for more control over formatting than the ToString method)

Additional Resources
Interfaces in C# (Microsoft)
Interfaces in VB (Microsoft)

Thursday, March 6, 2008

Tips for avoiding unnecessary boxing and unboxing

Boxing and unboxing can add overhead to runtime operations. You should especially try to avoid boxing and unboxing when you are performing compute intensive, repetitive tasks. Observing the following three tips will help eliminate unnecessary boxing and unboxing.

  • Implement type specific, overloaded versions of functions. So if a function is often called with a particular type of argument, then create specific version of the function that accepts that type of parameter. (Instead of just creating one version that selects an Object argument)
  • Use generics when ever possible instead of accepting Object arguments.
  • Override the ToString, Equals, and GetHash virtual members when defining structures.

Additional Resources
Boxing and Unboxing (David Cumps)

What is boxing and unboxing?

Boxing converts a value to a reference type, and unboxing converts a reference type to a value type.

The .NET code samples below show boxing and unboxing.

Boxing Example

' VB
Dim i As Integer = 123
Dim o As Object = CType(i, Object)


// C#
int i = 123;
object o = (object) i;


Unboxing Example

' VB
Dim o As Object = 123
Dim i As Integer = CType(o, Integer)


// C#
object o = 123;
int i = (int) o;


Additional Resources
Boxing and Unboxing (ASP Alliance)

What order should exceptions be caught in, least specific to most specific or vice versa?

Exceptions within the .NET frame work should be caught from most specific to least specific. This is because only the first catch block with a matching exception type is the only block that is executed. So in other words if you catch a more general exception before a less general exception, the code will never make it beyond the general exception that is caught. The more specific catch block becomes unreachable code.

Additional Resources
.NET Exception Handling (Microsoft)

How many strings are allocated in each of the code snippets below?

VisualBasic Code Snippet
Dim s As String

s = "how"
s += " many"
s += " strings"
s += " are"
s += "allocated?"
Console.WriteLine(s)

C# Code Snippet
string s;

s = "how";
s += " many";
s += " strings";
s += " are";
s += "allocated?";
Console.WriteLine(s);


If you said one string was allocated, then... you are wrong. Five strings are actually allocated. Strings in the .NET framework are immutable. This means that each change the string s causes the runtime to create a new string and abandon the old one. The immutable nature of .NET strings should be considered when performance is a concern. The creation of temporary strings can be avoided using two methods:

  • Use the String classes Concat, Join or Format methods to join multiple in a single statement
  • Use the StingBuilder class to create dynamic (mutable) strings

Additional Resources
String class (Microsoft)
StringBuilder class (Microsoft)

Wednesday, March 5, 2008

What is the correct declaration for a nullable integer?

Nullable was added in .NET 2.0. Nullable allows value data types to have an additional pattern, null. This can be useful to indicate within your code that a variable has not been initialized. For example, since we are talking about integers, before nullable was available an integer might be given a value of zero or some negative number when it was initialized. But what if zero or negative numbers are valid patterns? You can't really say that if a number is zero it is because it wasn't initialized or because that is the actual value.

Now that we have seen a reason for having nullable, it is time to answer the actual question. There are two ways to declare a nullable integer, the long form and the short form. (Examples will be provided for both C# and Visual Basic)

Long Form

' VB
Dim i As Nullable(Of Integer) = Nothing

// C#
Nullable<int> i = null;

Short Form (C# only)

//C# shorthand
int? i = null;

Additional Resources
Nullable Structure in VisualBasic (Microsoft)
Nullable Type in C# (Microsoft)

Tuesday, March 4, 2008

What namespace do the ASP.NET Page and LiteralControl classes belong to?

Both the Page and LiteralControl classes belong to the System.Web.UI namespace.

Additional Resources
System.Web.UI namespace
Page class
LiteralControl class

What does "type-safe" mean?

After you write your code, it is translated into Microsoft Intermediate Language (MSIL). MSIL is a CPU independent form that is later change into code specific to the machine it is running on by something called the Just In Time Compiler (All that is important is that the MSIL isn't transfered into machine code until you need it)

As the JIT compiler is translating the MSIL into machine code, it is also checking to see if variables are type safe. It does this by checking to make sure that variables do not access memory locations that they are not supposed to. This ensures that each application "plays well with others" by preventing memory corruption and crashes.

Additional Resources
Type safety (Wikipedia)

What are the seven name space automatically imported into every ASP.NET page?

Every ASP.NET page has the following seven name spaces imported by default:

What is the difference between code declaration blocks and render blocks?

The main difference between code declaration blocks and render blocks is compilation. Code render blocks are not compiled. Because they are not compiled they are not as efficient as code declaration blocks.

This really comes into play when you consider the situation where 1000 people are going to view your ASP.NET page. For code declaration blocks, the code only needs to be compiled once the first time the page is requested. From then on the compiled code can be quickly used in subsequent requests. With code render blocks, they must be processed for EVERY request that is made. That response time adds up over many requests and also places additional load on the server. More load equals decreased response time, which is bad news when you are delivering web content. When was the last time you waited more than a few seconds for a web page to load?

Additional Resources
Code declaration blocks (Microsoft)
Code render blocks (Microsoft)

What is a virtual directory?

A virtual directory is a folder that can be accessed as though it were in the www root of a web server.

Advantages of a virtual directory include:
  • Simplified URLs
  • Increased security
  • Ability to change file locations without changing the web address

Additional Resources
How to create a virtual directory (Microsoft)

Why can't you simply double click on an ASP.NET page to run it?

An ASP.NET file must be processed by the server and have all code blocks executed before it can be used. The server knows how to process a request based on rules that are set regarding a list of file types. In the case of a server with the .NET SDK installed, the server knows that the .NET Framework will be used to process files with a .aspx extension.

It is also important to understand that what you see as a developer (such as script blocks that are intended to be run on the server) are not seen in the HTML that is delivered to the user. So in other words users do not get to see the inner workings that went into creating a page, they only get to see the end result. This would not be possible if the server did not first process all the server code and produce HTML from that server code.

How does ASP.NET work with the client and server machines?

ASP.NET allows on to deliver dynamic content such as information collected from a database. ASP.NET does this by working with both the server (the source of the content) and the client (the consumer of the content).

ASP.NET on the Server
When a page is requested, the contents of the page are first examined and any code that is found is executed before honoring the request. This includes operations like processing forms and collecting data to display from databases.

ASP.NET on the Client
Code that is executed on the server inserts special client side code in the page that it returns. This allows the server to monitor what events are occurring on the client.

Additional Resources
ASP.NET 2.0's Client Call Back Feature (DotNetJunkies)

What are the programmatic improvements of ASP.NET over ASP?

When Microsoft moved from ASP to ASP.NET they had a chance to closely integrate ASP.NET with advancements they had made in the .NET Framework. (As opposed to "bolting" on a server side language after the fact)

With that tighter integration came significant programmatic improvements from ASP.NET over ASP.

Ease of Deployment
The introduction of metadata means that one no longer has to register web applications or COM objects. With this metadata the .NET Framework is able handle the details of running an application on your behalf.

Easier More Powerful Session Management
The web is based on an inherently stateless protocol (HTTP). Measures need to be taken to provide "statefulness" to web transactions. (If you added an item to a shopping cart you wouldn't want the web server to forget who you are when you request the next page) Classic ASP had session management, but that session management did not scale to web farm server environments. ASP.NET addressed this issue, opening more possibilities for robust technology offerings.

Code Declaration Blocks
Code declaration blocks are compiled instead of being interpreted at run time. This compilation allows for much better performance. Code declaration blocks also provide a mechanism to separate HTML and scripting content. This important because it helps code be more readable and maintainable. (The job is never done when the code is finished, someone will ALWAYS have to maintain it later)

There are several other advantages that you can read about in the Additional Resources section.

Additional Resources
ASP.NET vs ASP (W3Schools)

What is metadata?

In the context of the .NET Framework, metadata is descriptive information about an application. Metadata tells what the application can do, where it belongs and so forth.

Additional Resources
.NET metadata (Wikipedia)

What does CLR stand for?

CLR stands for Common Language Runtime. The CLR manages the execution of code in the .NET Framework. Traditionally source code would be compiled directly into machine specific code. This meant that different executables needed to be created for different architectures. In the .NET Framework, source code is compiled into an intermediate form. This layer of abstraction allows for a compile once, run on many architectures methodology.

Besides offering a layer of abstraction from the specific hardware architecture, the CLR also provides additional services that are common in computing environments.
  • Garbage Collection
  • Exception Handling
  • Security

Additional Resources
Common Language Runtime (Wikipedia)
Common Language Runtime Overview (Microsoft)

Support This Site

LinkShare  Referral  Prg