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
*/
Tuesday, October 27, 2009
Configuration Management
Multithreaded Applications
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
"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
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
Back to Exceptions in .NET ... I often refer to the following section of MSDN Website:
Best Practices for Handling Exceptions
- 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
Here is a sample program I wrote to demonstrate how to create a Generic class. I intentionally avoided using
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
Value Types
As I've been studying for the Microsoft .NET certification test, I am posting my study notes on my blog.
Value Types
Value Types are types that are copied when passed in as arguments (passed by value).
Value Types are stored on the stack (whereas Reference Types are stored in the Heap). Here is an excellent series of articles about Heap vs. Stack:
C# Heap(ing) Vs Stack(ing) in .NET: Part I
C# Heap(ing) Vs Stack(ing) in .NET: Part II
C# Heap(ing) Vs Stack(ing) in .NET: Part III
C# Heap(ing) Vs Stack(ing) in .NET: Part IV
There are two kinds of Value Types:
- Built-in value types. These include:
- Byte (8-bit unsigned integer, byte)
- SByte (8-bit signed integer, byte)
- Int16 (16-bit signed integer, short)
- Int32 (32-bit signed integer, int)
- Int64 (64-bit signed integer, long)
- UInt16 (16-bit unsigned integer, ushort)
- UInt32 (32-bit unsigned integer, uint)
- UInt64 (64-bit unsigned integer, ulong)
- Single (32-bit single-precision floating point, float)
- Double (64-bit double-precision floating point, double)
- Boolean (boolean value true/false, boolean)
- Char (16-bit Unicode, char)
- Decimal (128-bit, decimal)
- IntPtr (signed integer, depends on underlying platform)
- UIntPrt (unsigned integer, depends on underlying platform)
- User-defined Value Types.
The User-defined Value Types will extend System.ValueType or System.Enum. I copied the Complex Number Representation example from MSDN into VS.NET 2008 and played around with it.
Structs are also Value Types. This article from CodeProject covers Enums and Structs.