Saturday, October 31, 2009

Authentication and Authorization

Well, it's Halloween, and in between going to answer the doorbell, I'm still studying for my Microsoft .NET 70-536 exam.

Can't think of anything I'd rather be doing on Halloween than studying and writing code. :-)

Authentication and Authorization classes reside in the System.Security.Principal namespace.

The following classes and interfaces exist in this namespace:

  • WindowsIdentity - Represents a Windows or AD user account.
  • WindowsPrincipal - Provides access to a user's group memberships. From my study book, "You can use the WindowsPrincipal class to determine which groups a user is a member of. To query for built-in groups, pass to the WindowsPrincipal.IsInRole method a member of the System.Security.Principal.WindowsBuiltInRole".
  • GenericIdentity - For simple, non-Microsoft directory service user account.
  • GenericPrincipal - For simple, non-Microsoft directory service groups.
  • IIdentity - For custom users.
  • IPrincipal - For custom groups.
  • WindowsBuiltInRole (enum) - local Windows groups that are common in NT, 2000, XP. Include: User, PowerUser, Administrator, Guest, AccountOperator, SystemOperator, PrintOperator, BackupOperator, and Replicator.



Here is sample code to get the current user's group memberships:


using System;
using System.Threading;
using System.Security.Principal;

namespace IdentityPrincipal
{
class Program
{
static void Main(string[] args)
{
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
Console.WriteLine("Current User: '{0}", currentIdentity.Name);

// Two ways to get the currentPrincipal.
// 1. Through the WindowsPrincipal constructor passing in currentIdentity.
//WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);

// 2. Through the Thread.CurrentPrincipal property (after setting the Principal Policy of the
// current domain. For this sample program, we will use this method.
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal currentPrincipal = (WindowsPrincipal) Thread.CurrentPrincipal;

if (currentPrincipal.IsInRole(WindowsBuiltInRole.User))
{
Console.WriteLine("Current User is a User");
}
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Guest))
{
Console.WriteLine("Current User is a Guest");
}
if (currentPrincipal.IsInRole(WindowsBuiltInRole.PowerUser))
{
Console.WriteLine("Current User is a Power User");
}
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
Console.WriteLine("Current User is an Administrator");
}
Console.ReadKey();
}
}
}

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

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:


  1. Byte (8-bit unsigned integer, byte)

  2. SByte (8-bit signed integer, byte)

  3. Int16 (16-bit signed integer, short)

  4. Int32 (32-bit signed integer, int)

  5. Int64 (64-bit signed integer, long)

  6. UInt16 (16-bit unsigned integer, ushort)

  7. UInt32 (32-bit unsigned integer, uint)

  8. UInt64 (64-bit unsigned integer, ulong)

  9. Single (32-bit single-precision floating point, float)

  10. Double (64-bit double-precision floating point, double)

  11. Boolean (boolean value true/false, boolean)

  12. Char (16-bit Unicode, char)

  13. Decimal (128-bit, decimal)

  14. IntPtr (signed integer, depends on underlying platform)

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

Tuesday, October 20, 2009

Nullable types

A new language construct as of the .NET 2.0 Framework is Nullable types. Basically, it allows one to extend a Value Type (such as int, bool), and make it nullable.

Here's a small sample class I wrote to experiment with using Nullable Types.


namespace Project
{
public class DataTest
{
// The syntax T? (in C#) is shorthand for System.Nullable<T>, where T is a value type. The two forms are interchangeable.
private int? age = null;
private System.Nullable<system.int32> weight = null;

public int? Age
{
get { return age; }
set { age = value; }
}

public int? Weight
{
get { return weight; }
set { weight = value; }
}

public DataTest()
{}

public DataTest(int? myAge, int? myWeight)
{
Age = myAge;
Weight = myWeight;
}

///
/// Return String displaying age and weight
///

///
public override string ToString()
{
if (Age.HasValue && Weight.HasValue)
{
return "Your age is: " + Age.Value + ", and your weight is: " + Weight.Value;
}
else
{
return "No age or weight entered";
}
}
}
}


The following is a good reference for Nullable Types: Introduction to .Net Framework 2.0 Nullable Types.

Microsoft Certification Studies: 70-536

Today, I'm starting studies for Microsoft .NET certification. It looks like the first step in the journey to any certification path is the 70-536: Microsoft .NET Framework Application Development Foundation.

First question that immediately came to mind: is the test given in C# or VB? Part of the beauty of the .NET Framework is the underlying CLR, BCL (base class libraries) and language-independence. However, this has also been a bit of a challenge for me during past .NET development projects.

I'm a C# guy, myself. Sometimes I'll find excellent blog entries, posts, or forum responses of what I want to do, but the examples are in VB. Now, I can stumble through VB code examples, but it feels like reading text in a foreign language, whereas reading C# feels like reading something in my native language (English).

I found the answer to my question here:
http://www.proprofs.com/forums/index.php?showtopic=20207

I'll definitely be selecting C# for my exam.