Wednesday, October 28, 2009

Streams and Serialization

I started working on Streams and Serialization. I've worked with both of these concepts in-depth in Java (and have worked with System.IO Namespace in .NET), so this was an enjoyable area of study.

The biggest challenge was just remembering the class names, and not getting them mixed up with Java.

Here is a small test program I wrote that uses Binary Serialization and File Streams.

It serializes a strongly-typed list of IDs to a binary file, and deserializes it back. I had concerns about casting on formatter.Deserialize(stream), but it appeared to work okay. I do think that this is a dangerous practice, though, but am not sure of a better way to do it in a typesafe manner.


using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Serialization
{
class Program
{
static void Main(string[] args)
{
String serializedFilePath = @"c:\myObject.bin";
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
IList<int> myIds = new List<int> { 10, 20, 30, 40, 50, 60, 70, 80, 90, 99 };
FileStream fs = new FileStream(serializedFilePath, FileMode.Create, FileAccess.ReadWrite);

try
{
Console.WriteLine("About to serialize");
formatter.Serialize(ms, myIds);
formatter.Serialize(fs, myIds);

}
finally
{
ms.Close();
fs.Close();
}

// Now, we will deserialize from the file
try
{
Console.WriteLine("About to deserialize");
fs = new FileStream(serializedFilePath, FileMode.Open, FileAccess.Read);
IList<int> deserializedIds = (IList<int>) formatter.Deserialize(fs);

StringBuilder sBuilder = new StringBuilder();
foreach (int id in deserializedIds)
{
sBuilder.Append(" ");
sBuilder.Append(id);
}
Console.WriteLine("Deserialized List: " + sBuilder.ToString());
}
finally
{
fs.Close();
}
Console.ReadKey();
}
}
}

Tuesday, October 27, 2009

Configuration Management

I wrote the following test class to practice using classes in System.Configuration, especially ConfigurationManager.


using System;
using System.Configuration;
using System.Linq;
using System.Text;

namespace TestConfigurationManager
{
class Program
{
static void Main(string[] args)
{
// Get the AppSetting entries
for (int i=0; i < ConfigurationManager.AppSettings.Count; i++)
{
Console.WriteLine("AppSetting key: " + ConfigurationManager.AppSettings.AllKeys[i] + ", value: " + ConfigurationManager.AppSettings[i]);
}

// Get the Machine Config located at windows_root\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config
Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration();

ProtectedConfigurationSection protectedConfigSection = (ProtectedConfigurationSection) machineConfig.GetSection("configProtectedData");

Console.WriteLine("Protected provider default: " + protectedConfigSection.DefaultProvider);
Console.WriteLine("Here are the providers: ");
foreach (ProviderSettings settingsColl in protectedConfigSection.Providers)
{
Console.WriteLine("\t{0}", settingsColl.Name);
}

Console.ReadKey();
}
}
}
/*
Output:

AppSetting key: username, value: ptenn
AppSetting key: password, value: pass
AppSetting key: domain, value: mydomain
Protected provider default: RsaProtectedConfigurationProvider
Here are the providers:
RsaProtectedConfigurationProvider
DataProtectionConfigurationProvider

*/

Multithreaded Applications

I wrote the following test program, which makes use of several classes in the System.Threading namespace:


using System;
using System.Threading;

namespace ThreadingApp
{
public class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.RunApp();
Console.ReadKey();
}

public void RunApp()
{
ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 1");
ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 2");
ThreadMethod("Thread 3");
ThreadPool.QueueUserWorkItem(ThreadMethod, "Thread 4");
Console.WriteLine("Main thread exits.");

Thread myThread = new Thread(new ThreadStart(ThreadCallback));
myThread.Name = "My Thread";
myThread.Priority = ThreadPriority.Highest;
Console.WriteLine("From runapp, {0}.ThreadState={1}", myThread.Name, myThread.ThreadState);
myThread.Start();

}

void ThreadCallback()
{
Console.WriteLine("Calling ThreadCallback");
Console.WriteLine("{0}.ThreadState={1}", Thread.CurrentThread.Name, Thread.CurrentThread.ThreadState);
}

void ThreadMethod(Object stateInfo)
{
String state = (String) stateInfo;
if (Thread.CurrentThread.IsBackground)
{
Console.WriteLine("background thread: " + state);
}
else
{
Console.WriteLine("foreground thread: " + state);
}
}
}
}

/*
Resulting output:

foreground thread: Thread 3
Main thread exits.
background thread: Thread 1
background thread: Thread 2
background thread: Thread 4
From runapp, My Thread.ThreadState=Unstarted
Calling ThreadCallback
My Thread.ThreadState=Running

*/

Service Controllers and System.ServiceProcess namespace

From the Skills being Measured:

"Implement, install, and control a service."

These are Windows Services (the same services that we all know and love under the Control Panel -> Administration Tools -> Services).

The relevant classes, structs, enums are in the following namespace:

System.ServiceProcess

Here are some of the key classes:

  • ServiceBase - base class that should be extended by any new class that will run as a Windows Service. Implementing a service involves extending ServiceBase and providing behavior that will occur when the service is started, stopped, paused, continued. All services that extend ServiceBase should implement OnStart and OnStop, and may also implement OnPause and OnContinue.
  • ServiceController - represents an existing Windows Service, allows for the service to be stopped, started, manipulated, and information to be obtained about it. Here is an excellent example of a ServiceController on CodeProject. GetServices is a static method that will return an array of ServiceController objects.
  • ServiceControllerPermission - From MSDN: Allows control of code access security permissions for service controllers. I could not find any samples on how to use ServiceControllerPermission class, nor could I find any properties or methods in ServiceController that demonstrated how to use the ServiceControllerPermission.
  • ServiceInstaller - Installs a Service class (class that extends System.ServiceProcess.ServiceBase). Should be called by installation utility. The method ServiceInstaller.Install will be automatically called by the install utility, and if anything goes wrong, ServiceInstaller.Rollback will be called.
  • ServiceProcessInstaller - Installs a Service class. Can be used to specify that the Service will run under a different account (such as the Local System account).
  • SessionChangeDescription (struct) - Contains reason for Terminal Services session change. Has a property, Reason, which is an enum of SessionChangeReason.
  • SessionChangeReason (enum) - See SessionChangeDescription.Reason property.

Monday, October 26, 2009

Collections

The System.Collections namespace contains non-generic classes and interfaces that pertain to gathering and sorting collections of objects and value types.

Here is the MSDN reference for System.Collections.

Classes:




  • ArrayList - Array whose size is dynamically increased as required. Implements IList, IEnumerable. Method arrayList.Add will add an object to the array. Objects can be removed by calling arrayList.Remove(o : Object). ArrayLists can be sorted. Any type of object can be stored, including null.


  • BitArray - Compact Array of bits (bool values).


  • CaseInsensitiveComparer - Compares objects for equivalence, ignoring case on Strings.


  • CollectionBase - Abstract base class for strongly-typed Collection of objects.


  • Comparer - Compares objects for equivalence, case-sensitive for Strings. Default implementation of IComparer interface.


  • DictionaryBase - abstract base class for key-value pair collections. Each entry is stored as a DictionaryEntry struct (structure that represents a key-value pair). Consequently, a foreach iteration over an implementation of DictionaryBase will be a foreach (DictionaryEntry de : dictionary).

  • Hashtable - Implementation of key-value pair collection. If an add is called, but there is already a DictionaryEntry with this key, an Exception is thrown. hashtable.ContainsKey should be called to make sure that it doesn't exist.

  • Queue - FIFO collection of objects. Method Enqueue adds to the Queue, Dequeue removes from the queue using FIFO. Peek will return the same value as Dequeue, but will not actually remove the object from the Queue.

  • ReadOnlyCollectionBase - Similar to CollectionBase, only read-only.

  • SortedList - Collection of key-value pairs, where the keys are sorted.

  • Stack - LIFO collection of objects. Method Push adds to the Stack, Pop removes from the Stack using LIFO. Peek will return the same value as Pop, but will not actually remove the object from the Stack.

Structs:



  • DictionaryEntry - represents a key-value pair for a collection that implements IDictionary.

Interfaces:



  • ICollection - base interface for classes in System.Collections namespace. Extends IEnumerable.

  • IComparer - contract defines a single method, Compare(a : Object, b: Object) : int. Will return negative if a is less than b, 0 if a and b are equal, positive if a is greater than b.

  • IDictionary - collection of key-value pairs (which are DictionaryEntry structs). 3 types of IDictionary implementations: read-only, fixed-size, variable-size.

  • IEnumerable - Provides GetEnumerator method, which must be implemented in order to support the foreach keyword.

  • IList - Collection of objects that can be accessed by index.

Wednesday, October 21, 2009

Exceptions

Since I come from a Java background, there was a bit of adjustment to .NET Framework approach to Exception handling.

The biggest difference between Java and .NET Exception Handling:

Java has checked exceptions, .NET does not have checked exceptions


No checked exceptions = no "throws" keyword, and no "throws" on method signatures.


Checked exceptions in Java always made me feel "boxed in" when I was programming, and made me spend a lot of time on "scaffolding" code.


This difference took me a bit of adjustment time. However, I found that I preferred the .NET approach to exception handling. I always hated working with APIs or Frameworks where the infrastructure code threw a lot of Exceptions, so I was forced to have huge try-catch blocks, and I wasn't really sure what to do in the event of an Exception.


A classic example is working with just about any class in the java.io or java.nio packages.


Back to Exceptions in .NET ... I often refer to the following section of MSDN Website:

Best Practices for Handling Exceptions


Notes about Exception handling:


  • System.Exception is the root class for all Exceptions. System.SystemException and System.ApplicationException derive from System.Exception.

  • Initially, I thought that all custom application exceptions should derive from System.ApplicationException (hence the name). However, the best practices on MSDN suggest that this is not necessarily true.

Generics

Generics allow us to create classes that are not bound to a specific type, and must provide generic functionality for all types. It can be used to provide type-safety during compile-time.

Here is a sample program I wrote to demonstrate how to create a Generic class. I intentionally avoided using for the type, to show this is not a requirement.


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

namespace SystemTypesCollections
{
public class GenericsTest<ZX>
{
public ZX MyVal { get; set; }

public override string ToString()
{
if (MyVal is String)
{
return "My String is: '" + MyVal + "'";
}
else if (MyVal is int)
{
return "I am an Integer: " + MyVal;
}
else
{
return "I am an object";
}

}
public GenericsTest(ZX val)
{
MyVal = val;
}
}

public class Program
{
static void Main(string[] args)
{
GenericsTest<int> g1 = new GenericsTest<int>(5);
GenericsTest<String> g2 = new GenericsTest<string>("Hello, world");
GenericsTest<IList> g3 = new GenericsTest<IList>(new ArrayList());

System.Console.WriteLine(g1);
System.Console.WriteLine(g2);
System.Console.WriteLine(g3);
}
}
}



Output result:
I am an Integer: 5
My String is: 'Hello, world'
I am an object