Monday, March 29, 2010

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)

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 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)

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)

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.

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)

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 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 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 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 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

' VBDim i As Nullable(Of Integer) = Nothing

// C#
Nullable i = null;

Short Form (C# only)

//C# shorthand
int? i = null;

Additional Resources
Nullable Structure in VisualBasic (Microsoft)
Nullable Type in C# (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)

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)

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)

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)

Thursday, March 11, 2010

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)

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

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)

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)

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)