November 2010 (1)
August 2010 (1)
July 2010 (1)
June 2010 (3)
July 2009 (3)
June 2009 (1)
May 2009 (1)
February 2009 (1)
January 2009 (1)
November 2008 (3)
October 2008 (4)
September 2008 (9)
August 2008 (6)
July 2008 (3)
June 2008 (3)
January 2008 (1)
November 2007 (2)
October 2007 (6)
September 2007 (5)
August 2007 (22)
July 2007 (6)
June 2007 (1)
May 2007 (3)
April 2007 (27)
March 2007 (8)
February 2007 (6)
September 2006 (2)
August 2006 (4)
July 2006 (9)
June 2006 (17)
May 2006 (20)
April 2006 (12)
March 2006 (9)
February 2006 (4)
January 2006 (3)
December 2005 (2)
November 2005 (4)
October 2005 (5)
September 2005 (37)
August 2005 (83)
July 2005 (6)

Active Directory / LDAP (0)
ASP.Net (19)
Blackberry Development (4)
c# (34)
c++ (3)
Code Camp (1)
Excel (1)
Exchange (3)
Front Page 2003 (6)
FTP User Editor (4)
HTML / CSS / DHTML (8)
IIS (146)
IIS - Log Parser (7)
IIS / FTP (12)
IIS / Tools / Administration (42)
IIS / Tools / Authentication (6)
IIS / Tools / Compression (8)
IIS / Tools / Crash & Hang (12)
IIS / Tools / ISAPI Filters (17)
IIS / Tools / Log Files (17)
IIS / Tools / Scripts (28)
IIS / Tools / Security (9)
IIS / Tools / SSL (6)
IIS 7 (3)
Internet Information Server (1)
Me (Chris Crowe) (6)
MIME Types (1)
Misc (72)
Oulook Express (2)
Silverlight (1)
SQL Server (27)
SQL Server CTE (1)
Vista (15)
Vista Gadgets (8)
Visual Studio (11)
Voice over BroadBand (1)
Windows (33)
Windows Powershell (3)
Windows Sharepoint Services (0)
Windows Sharepoint Services (15)
Windows Vista (14)
Wine Cellar (1)
WMI (8)
c# (34) blog.crowe.co.nz.Models.Category

c#

Code Camp in Christchurch, New Zealand in November 2007

I see that there is now offical talk of a Code Camp in Christchurch, New Zealand in November 2007 which is good to see. I hope for some confirmed dates soon.

This is great news as the Mainland as we call it (the South Island of New Zealand) has never had a Code Camp before.

For pre-registrations and more details see http://dot.net.nz/Default.aspx?tabid=108 

The theme of the code camp is Next generation, back to basics. 

New releases of C#, VB, .Net, ASP and SQL are iminent.  This code camp will focus on getting up to speed with all of this, plus cover migration stratigies and many non-technology specific topics such as Architecture and Development Life Cycle.  Hopefully something for everyone - noobs, gurus, youg and old.

I have been asked to speak on IIS 7 and will be providing a session on this somewhere over the two day event.

I also spoke to Daniel Wissa ( at TechEd 2007) who runs the Christchurch .NET user group with Peter Jones [MVP] about running a shared session some time this year on Windows Vista Gadget Development. The code camp may be a good time for this session as well.

 I am trying to get some sponser support as well - but I will keep it quiet until I know the result.


c# - An example of setting NTFS Directory / File ACLS

Below is a simple c# console application that shows how you can set the NTFS ACLs for a directory. 

You are probably aware of the DirectoryInfo object which you can use to get details on a folder, but there is also the ability to get and set the NTFS file ACLs (Access Control List Entries)

No special reference need to be made in order to use the code.

using System.IO; 
using System.Security.AccessControl; 

namespace DirectoryPermissions 
{ 
    internal class Program 
    { 
        private static void Main(string[] args) 
        { 
            string ADDomain = "Domain"; 
            string ADUser = "Chris"; 
            string Path = @"c:\temp\chris"; 

            if (Directory.Exists(Path) == false) 
                Directory.CreateDirectory(Path); 

            // Remove any inheritable permissions from the path 
            RemoveInheritablePermissons(Path); 

            // Add the access control entries for the path 
            AddDirectorySecurity(Path, ADDomain + "\\" + ADUser, FileSystemRights.Modify, 
                                 InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
                                 PropagationFlags.None, AccessControlType.Allow); 
            AddDirectorySecurity(Path, ADDomain + "\\Domain Users", FileSystemRights.Delete, InheritanceFlags.None, 
                                 PropagationFlags.None, AccessControlType.Deny); 
            AddDirectorySecurity(Path, ADDomain + "\\Domain Admins", FileSystemRights.FullControl, 
                                 InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
                                 PropagationFlags.None, AccessControlType.Allow); 
        } 


        // Adds an ACL entry on the specified directory for the specified account. 
        public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, 
                                                InheritanceFlags Inheritance, PropagationFlags Propogation, 
                                                AccessControlType ControlType) 
        { 
            // Create a new DirectoryInfo object. 
            DirectoryInfo dInfo = new DirectoryInfo(FileName); 
            // Get a DirectorySecurity object that represents the  
            // current security settings. 
            DirectorySecurity dSecurity = dInfo.GetAccessControl(); 
            // Add the FileSystemAccessRule to the security settings.  
            dSecurity.AddAccessRule(new FileSystemAccessRule(Account, 
                                                             Rights, 
                                                             Inheritance, 
                                                             Propogation, 
                                                             ControlType)); 
            // Set the new access settings. 
            dInfo.SetAccessControl(dSecurity); 
        } 

        // Removes an ACL entry on the specified directory for the specified account. 
        public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights, 
                                                   AccessControlType ControlType) 
        { 
            // Create a new DirectoryInfo object. 
            DirectoryInfo dInfo = new DirectoryInfo(FileName); 
            // Get a DirectorySecurity object that represents the  
            // current security settings. 
            DirectorySecurity dSecurity = dInfo.GetAccessControl(); 
            // Add the FileSystemAccessRule to the security settings.  
            dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account, 
                                                                Rights, 
                                                                ControlType)); 
            // Set the new access settings. 
            dInfo.SetAccessControl(dSecurity); 
        } 

        // Removes an ACL entry on the specified directory for the specified account. 
        public static void RemoveInheritablePermissons(string FileName) 
        { 
            // Create a new DirectoryInfo object. 
            DirectoryInfo dInfo = new DirectoryInfo(FileName); 
            // Get a DirectorySecurity object that represents the  
            // current security settings. 
            DirectorySecurity dSecurity = dInfo.GetAccessControl(); 
            // Add the FileSystemAccessRule to the security settings. 
            const bool IsProtected = true; 
            const bool PreserveInheritance = false; 
            dSecurity.SetAccessRuleProtection(IsProtected, PreserveInheritance); 
            // Set the new access settings. 
            dInfo.SetAccessControl(dSecurity); 
        } 
    } 
}

c# - How to create a comma seperated string from a list of items

I found an interesting post from a work colleague "Simeon Pilgrim" at http://simeonpilgrim.com/blog/2007/08/23/how-to-rewriter-systemconfigurationcommadelimitedstringcollection-wrong/ that shows that in the System.Configuration namespace there is a very simple class that will create a comma seperated string for you.

The class is called CommaDelimitedStringCollection and you must add a reference to System.Configuration in order to use it.

 
There is a simple example of how to use it.
using System; 
using System.Collections; 
using System.Configuration; 

namespace Commas 
{ 
    internal class Program 
    { 
        private static void Main(string[] args) 
        { 
            ArrayList Items = new ArrayList(); 
            Items.Add("http://blog.crowe.co.nz"); 
            Items.Add("http://www.simeonpilgrim.com"); 
            Items.Add("http://www.iis.net"); 

            CommaDelimitedStringCollection commaStr = 
                new CommaDelimitedStringCollection(); 

            foreach (string item in Items) 
                commaStr.Add(item); 

            Console.WriteLine(commaStr.ToString()); 
        } 
    } 
}
The output from the above would be :

http://blog.crowe.co.nz,http://www.simeonpilgrim.com,http://www.iis.net

In the sample above we loop through each item in my ArrayList and add it to the list of strings to comma seperate.
We could have replaced for foreach loop with this to make it a bit easier.

commaStr.AddRange((string[]) Items.ToArray(typeof(string)));

 

I wonder how many other usefull classes are out there but no one uses them and reinvents the wheel.


Looking for a way to get WinForms Developer License with Subscription and Source (value $999) for free!
Telerik ( www.telerik.com ) makers of some great controls for Asp.net and WinForms have a content running now that will allow you the chance to win a 50" Plasma Television.
 
Telerik WinForms Contest - Part II
In order to participate you need to download RadControls for WinForms, explore the software for a while and then answer 10 easy questions.
 
For 5 or more correct answers, you will receive a complimentary RadControls for WinForms Developer License with Subscription and Source (value $999).
 
 
THE AWARDS:
  • Grand prize: 50 inch plasma TV
  • The first 50 participants that answer all questions correctly will receive a $20 Amazon gift coupon.

Telerik Code Converter - convert C# to VB.NET and visa versa

Code Converter is a free and simple VB to C# and C# to VB code converter. While there are several other good code converters available, none are perfect. Some are buried in busy websites. Some are awkward to use. Some just don't convert accurately! Code Converter, while not yet perfect, aims to address these issues and provide the best free .NET converter available on the web.

Part of the mission of delivering the best code conversion service means that it needs to be available wherever and whenever you need it. For that reason, we will be building code conversion widgets for all of the major widget engines (such as Google Desktop, Windows Sidebar, and Yahoo! Widgets) so that you can easily convert your code snippet while minimizing the interruption to your work. The following code conversion widgets are already ready and available here:

To try on line see http://converter.telerik.com/Default.aspx

Conversions by NRefactory

For the heavy lifting, we rely on the open source NRefactory library to perform code conversions. NRefactory is a powerful C# to VB and VB to C# conversion engine maintained by the developers at SharpDevelop. By default, NRefactory requires that all code be properly wrapped in a class and (as necessary) method before converting. We try to save you time by automagically wrapping your code snippets in "dummy wrappers" so it can be processed by NRefactory. If you're having trouble converting your code, try wrapping it in a class yourself to skip our "magic" wrapping process.

http://www.google.com/search?q=NRefactory&rls=com.microsoft:*&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1

 


Refactor!™ for ASP.NET free download from www.devexpress.com

For those that do not know Developer Express make some really great tools and controls for .NET. They have made their Refactor tool for ASP.NET available for free.

Refactor! is freely available to all ASP.NET 2.0 developers and offers a comprehensive suite of tools that enable you and your team to simplify and shape complex code and HTML markup - making your web applications easier to read and less costly to maintain.

Below is a simple example where you can refactor the source file the .APSX file into a code behind file.

If you want to watch a small 12 minute video about it see this:
http://www.devexpress.com/Products/NET/IDETools/RefactorASP/Presentation/Refactor_for_ASP_NET/
 

You can download it from:
http://www.devexpress.com/Products/NET/IDETools/RefactorASP/

They also have two other free Refactor products:

  • Refactor for Visual Basic
  • Refactor for C++

Free download: "Visual Studio 2005: A Guided Tour"

This 92-page issue contains the best MSDN Magazine Visual Studio 2005 coverage from the past two years, updated for the final release. Find out what's new in C#, C++, Visual Basic, Windows Forms, ASP.NET, Team System, security, and C++generic types -- download your copy now!


Retrieving the COM class factory for component with CLSID {3FA7DEB3-6438-101B-ACC1-00AA00423326} failed due to the following error: 80010106.
While trying to upgrade a .NET application from VS.NET 2003 to VS.NET 2005 I found I was getting a problem with creating a MAPI.Session object.

I was getting the following exception:

Searching around in www.google.co.nz and everywhere else I was finding nothing on this error.

I decided that I would simply create a new application and see if it failed.

  • I opened VS.NET 2003
  • I created a new console application
  • I added a reference to "Microsoft CDO 1.21 Library"
  • I added one line of code MAPI.Session sess = new MAPI.Session(); to my Main() routine

I then run the code and it worked fine.

So I repeated the code in VS.NET 2005

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

namespace ConsoleApplication1
{
   class Program
  
{
     
static void Main(string[] args)
      {
          MAPI.
Session sess = new MAPI.Session();
      }
    }
}

I was still getting the exception. I decided to post to the New Zealand .NET User group list that I belong to - see www.dot.net.nz

I got the following response from Alex James

" I don’t know the answer, but one thing I would check is whether different thread types have an effect. I.e. is you app [MTAThread] or [STAThread]

You never know that might be the answer, the default between 2003/2005 maybe different? "

 

I had a look at the code that VS.NET 2003 produced and indeed it has the following attribute above the Main() procedure

      [STAThread]

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

namespace ConsoleApplication1
{
   class Program
  
{
      [STAThread]
      static void Main(string[] args)
      {
          MAPI.
Session sess = new MAPI.Session();
      }
    }
}

I added the attribute to my code and the problem was gone. So obviously the CDO 1.21 library is compiled for STAThreading and not the VS.NET 2005 default which must be MTAThread.

The following is from http://www.sellsbrothers.com/askthewonk/Secure/WhatdoestheSTAThreadattri.htm

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

A multi-threaded apartment (MTA) in COM is more efficient, since any of a number of RPC threads from a pool can be used to handle a request. However, an object on the MTA thread needs to protect itself from multiple threads accessing it at the same time, so that efficiency comes at a cost.

The single-thread apartment (STA) in COM is inherently single-threaded and therefore no additional thread synchronization is needed. The STA is implemented using the thread's Windows message queue, which is how requests to objects on an STA are serialized. Because of how the STA thread is implemented, calls to objects on that thread are serialized with Windows message handling on that thread, making sure that everything, both the COM objects and the underlying windowing objects, e.g. HWNDs, are all synchronized. This is necessary for UI-oriented COM objects, like controls and drag 'n' drop, which must also be synchronized together with the UI.

When COM is needed .NET will call CoInitializeEx, picking the MTA by default because it's more efficient. However, to get the synchronization needed for controls, windows and drag 'n' drop, you need to mark a thread's entry point with the STAThreadAttribute to let .NET know to initialize the UI thread on the STA. All of the VS.NET project templates put that attribute in to make sure you don't forget:

 

 


Some examples of scripting of IIS using ADSI, WMI from VB and C# including the new Microsoft.Web.Administration namespace

Below are some simple examples of how to talk to IIS via ADSI, WMI and the new IIS 7 only .NET Managed Provider.

The IIS ADSI Provider

The IIS ADSI provider exposes COM Automation objects that you can use within command-line scripts, ASP pages, or custom applications to change IIS configuration values stored in the IIS metabase. IIS ADSI objects can be accessed and manipulated by any language that supports automation, such as Microsoft® Visual Basic® Scripting Edition (VBScript), Microsoft JScript®, Perl, Microsoft Active Server Pages (ASP), Visual Basic, Java, or Microsoft C++.

The IIS WMI Provider

Windows Management Instrumentation (WMI) is a technology that allows administrators to programmatically manage and configure the Windows operating system and Windows applications. Beginning with IIS 6.0, IIS includes a WMI provider that exposes programming interfaces that can be used to query and configure the IIS metabase.

The Microsoft.Web.Administration namespace in IIS 7

 This is a new .NET managed namespace that will allow you to talk to IIS 7 and configure all aspects of the server. This API is designed to be simple to code against in an “intellisense-driven” sort of way. At the root level a class called ServerManager exposes all the functionality you will need. At this time it appears that this will not be able to be used from Windows XP but by the time Vista & Windows Server are released this may have been ported to run on a Windows XP client.
 

For more details on these technologies see the following resources:


C# -Using System.DirectoryServices and ADSI

using System;
using System.Collections.Generic;
using System.Text;
// Must be specified and a reference added to System.DirectoryServices
using System.DirectoryServices;

namespace Console_EnumSites_ADSI_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/W3SVC");
            foreach (DirectoryEntry site in entry.Children)
            {
                if (site.SchemaClassName == "IIsWebServer")
                {
                    string ServerComment = site.Properties["ServerComment"].Value.ToString();
                    Console.WriteLine(ServerComment + " (" + site.Name + ")");
                }
            }
        }
    }
}

VB -Using ADSI

on error resume next

dim websrv, site
dim webinfo

set websrv = getobject("IIS://Localhost/W3SVC")
if (err <> 0) then
else
    err.Clear
    for each site in websrv
        if (site.classname = "IIsWebServer") then
            WScript.echo Site.ServerComment & " (" & Site.Name & ")"
        end if
    next
end if

C# -Using System.Managment and WMI

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

namespace Console_EnumSites_WMI_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementScope oms = new ManagementScope(@"\\.\root\MicrosoftIISv2");
            oms.Connect();

            ObjectQuery oQuery = new ObjectQuery("select * from IISWebServerSetting");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oms, oQuery);
            foreach (ManagementObject oreturn in oSearcher.Get())
            {
                Console.WriteLine(oreturn["ServerComment"]+" ("+oreturn["Name"]+")");
            }
            Console.Read();
        }
    }
}

C# -Using Microsoft.Web.Administration ( II7 Only )

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;

namespace Console_EnumSites
{
    class Program
    {
        static void Main(string[] args)
        {
            ServerManager iisManager = new ServerManager();

            Console.WriteLine("Display IIS Sites in IIS 7");
            Console.WriteLine("".PadLeft(40,'-'));
            foreach(Site site in iisManager.Sites)
            {
                Console.WriteLine("{0} {1}", site.Id.ToString().PadRight(12), site.Name);                
            }
            Console.Read();
        }
    }
}

c# - How to display the HttpExpires property and display its meaning...

The HttpExpires property is documented at the following URL.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/3e1d9fbb-6910-4648-a2bb-11a945ca7980.mspx?mfr=true

This simple c# console application will display the settings for the HttpExpires property at the root level of the default web site.

Basically the value is encoded as follows:

  • If the value is a blank string then there is no content expiry.
  • If the value starts with a D, then it is using a dynamic expiration period. This period is appended after the D and is stored as the number of seconds in hexidecimal format.

    Example: “D, 0x15180”    - this 0x15180 is the same as 86,400 seconds or 1 day.
  • If the value starts with an S then the following value is a GMT time of when the expiration will take place.

    Example: “S, Sat, 08 Jul 2006 12:00:00 GMT”

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace IISHTTPExpires
{
    class Program
    {
        static void Main(string[] args)
        {         
            Console.WriteLine("IIS HTTP Expires - c#");
            Console.WriteLine();
            // Serve to connect to...
            string ServerName = "LocalHost";
            // Define the path to the metabase
            string MetabasePath = "IIS://" + ServerName + "/W3SVC/1/ROOT";
            try
            {
                // Talk to the IIS Metabase to read the MimeMap Metabase key
                DirectoryEntry Entry = new DirectoryEntry(MetabasePath);
                // Get the Mime Types as a collection
                PropertyValueCollection pvc = Entry.Properties["HTTPExpires"];
                string HttpExpires = pvc.Value.ToString();
                if (HttpExpires.Length == 0)
                {
                    Console.WriteLine("HttpExpires is not enabled!");
                }
                else
                {
                    char HttpExpiresType = HttpExpires[0];
                    switch (HttpExpiresType) { case 'D':
                            string Seconds = HttpExpires.Substring(3);
                            if (Seconds == "0")
                                Seconds = "Immediately";
                            else if (Seconds.StartsWith("0x")==true)
                                Seconds = "in " + int.Parse(HttpExpires.Substring(5),
                                    System.Globalization.NumberStyles.HexNumber).ToString() + " Seconds";
                            else
                                Seconds = "in " + Seconds + " Seconds";
                            Console.WriteLine("HttpExpires {0}", Seconds);
                            break;
                        case 'S':
                            Console.WriteLine("HttpExpires {0}", HttpExpires.Substring(2));
                            break;
                        default:
                            Console.WriteLine("Unknown HttpExpires Type : {0}", HttpExpiresType);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to read HttpExpires property with the following exception: \n{0}",
                    ex.Message);
            }
            finally
            {
                Console.Read();
            }
        }
    }
}


c# - How to display the IP Address, TCP/IP Port, and Host Header values from IIS
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace EnumSites
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryEntry entry = new DirectoryEntry("IIS://localhost/w3svc/1");
            PropertyValueCollection pvc = entry.Properties["ServerBindings"];
            foreach (object value in pvc)
            {
                // Format is IPAddress:Port:HostHeader
                string[] Bits = value.ToString().Split(':');
                string IPAddress = Bits[0];
                string TCPIPPort = Bits[1];
                string HostHeader = Bits[2];
                Console.WriteLine("IP = {0}, Port = {1}, Header = {2}", 
                    (IPAddress.Length == 0) ? "(All Unassigned)" : IPAddress, 
                    TCPIPPort, 
                    (HostHeader.Length == 0) ? "(No Host Header)" : HostHeader);
            }
            Console.Read();
        }
    }
}

This simple code will allow you to display the IP Address, TCP/IP Port, and Host Header values for the default web site. The default web site has an Instance ID of 1.

If you want to display for a different web site then change the "IIS://localhost/w3svc/1" to another instance. You can determine the instance ID from the log file name in the log entry properties dialog in the IIS manager.

 


Mix 06 - All 52 sessions are online and free!
Back a few months ago Microsoft went to Las Vegas to put on a share called Mix06. If you do business on the Web today, it's likely that more than 90% of your customers reach you via Microsoft® Internet Explorer and/or Microsoft Windows®. Come to MIX and learn how the next versions of these products, due later this year, are going to dramatically improve your customers' experience. Explore a wide range of new Web technologies that Microsoft is delivering to help you unlock new revenue opportunities and lower development costs. Learn about the future of Internet Explorer and join us in a discussion about how we can build the ideal Web surfing platform to meet your needs and those of your customers.
  • Be the first to get the latest preview build of IE7
  • Work with the members of the Internet Explorer team in the Compatibility Lab to get your site ready for IE7
  • Test drive "Atlas," Microsoft's powerful new framework for building cross–browser, cross–platform AJAX applications
  • Explore Windows Live!, Microsoft's new consumer services strategy
  • Learn how to deliver revolutionary, media–rich Web content with the new Windows Presentation Foundation
  • Find out how to extend your content, media and services into the living room with Windows Media Center and Xbox 360™
  • More than 50 separate sessions and discussions for Web developers, designers and business professionals

All 52 sessions are now online and free

http://mix06.com/Default.aspx


C# - How to display MimeMap entries to the console from an instance of IIS

 The following c# application will return all of the MimeMaps defined in an IIS instance. The MimeMaps hold the mime types that IIS uses to return the ContentType header.

An example of such a header is application/octetstream

This example requires a reference to the Active DS IIS Namespace Provider in Visual Studio .NET. This reference enables you to use the IISOle namespace to access the IISMimeType class.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.DirectoryServices;
using System.Collections;
namespace IISMIMEType
{
    class Program
    {
        static void Main(string[] args)
        {
            // Maintain a sorted list to contain the MIME Types
            SortedList sl = new SortedList();
            Console.WriteLine("IIS Mime Map - c#");
            Console.WriteLine();
            // Serve to connect to...
            string ServerName = "LocalHost";
            // Define the path to the metabase
            string MetabasePath = "IIS://" + ServerName + "/MimeMap";
            // Note: This could also be something like
            // string MetabasePath = "IIS://" + ServerName + "/w3svc/1/root";
            try
            {
                // Talk to the IIS Metabase to read the MimeMap Metabase key
                DirectoryEntry MimeMap = new DirectoryEntry(MetabasePath);
                // Get the Mime Types as a collection
                PropertyValueCollection pvc = MimeMap.Properties["MimeMap"];
                // Add each Mime Type so we can display it sorted later
                foreach (object Value in pvc)
                {
                    // Convert to an IISOle.MimeMap - Requires a connection to IISOle
                    // IISOle can be added to the references section in VS.NET by selecting
                    // Add Reference, selecting the COM Tab, and then finding the 
                    // Active DS Namespace provider
                    IISOle.MimeMap mimetypeObj = (IISOle.MimeMap)Value;
                    // Add the mime extension and type to our sorted list.
                    sl.Add(mimetypeObj.Extension, mimetypeObj.MimeType);
                }
                // Render the sorted MIME entries
                if (sl.Count == 0)
                    Console.WriteLine("No MimeMap entries are defined at {0}!", MetabasePath);
                else
                    foreach (string Key in sl.Keys)
                        Console.WriteLine("{0} : {1}", Key.PadRight(20), sl[Key]);
            }
            catch (Exception ex)
            {
                if ("HRESULT 0x80005006" == ex.Message)
                    Console.WriteLine(" Property MimeMap does not exist at {0}", MetabasePath);
                else
                    Console.WriteLine("An exception has occurred: \n{0}", ex.Message);
            }
        }
    }
}
    


Example Output

.*  application/octet-stream
.323  text/h323
.acx  application/internet-property-stream
.ai  application/postscript
.aif  audio/x-aiff
.aifc  audio/aiff
.aiff  audio/aiff
.application  application/x-ms-application
.asf  video/x-ms-asf
.asr  video/x-ms-asf
.asx  video/x-ms-asf
.au  audio/basic
.avi  video/x-msvideo
.axs  application/olescript
.bas  text/plain
.bcpio  application/x-bcpio
.bin  application/octet-stream
.bmp  image/bmp
.c  text/plain
.cat  application/vndms-pkiseccat
.cdf  application/x-cdf
.cer  application/x-x509-ca-cert
.clp  application/x-msclip
.cmx  image/x-cmx
.cod  image/cis-cod
.cpio  application/x-cpio
.crd  application/x-mscardfile
.crl  application/pkix-crl
.crt  application/x-x509-ca-cert
.csh  application/x-csh
.css  text/css
.dcr  application/x-director
.deploy  application/octet-stream
.der  application/x-x509-ca-cert
.dib  image/bmp
.dir  application/x-director
.disco  text/xml
.dll  application/x-msdownload
.doc  application/msword
.dot  application/msword
.dvi  application/x-dvi
.dxr  application/x-director
.eml  message/rfc822
.eps  application/postscript
.etx  text/x-setext
.evy  application/envoy
.exe  application/octet-stream
.fif  application/fractals
.flr  x-world/x-vrml
.gif  image/gif
.gtar  application/x-gtar
.gz  application/x-gzip
.h  text/plain
.hdf  application/x-hdf
.hlp  application/winhlp
.hqx  application/mac-binhex40
.hta  application/hta
.htc  text/x-component
.htm  text/html
.html  text/html
.htt  text/webviewhtml
.ico  image/x-icon
.ief  image/ief
.iii  application/x-iphone
.ins  application/x-internet-signup
.isp  application/x-internet-signup
.IVF  video/x-ivf
.jfif  image/pjpeg
.jpe  image/jpeg
.jpeg  image/jpeg
.jpg  image/jpeg
.js  application/x-javascript
.latex  application/x-latex
.lsf  video/x-la-asf
.lsx  video/x-la-asf
.m13  application/x-msmediaview
.m14  application/x-msmediaview
.m1v  video/mpeg
.m3u  audio/x-mpegurl
.man  application/x-troff-man
.manifest  application/x-ms-manifest
.mdb  application/x-msaccess
.me  application/x-troff-me
.mht  message/rfc822
.mhtml  message/rfc822
.mid  audio/mid
.mmf  application/x-smaf
.mny  application/x-msmoney
.mov  video/quicktime
.movie  video/x-sgi-movie
.mp2  video/mpeg
.mp3  audio/mpeg
.mpa  video/mpeg
.mpe  video/mpeg
.mpeg  video/mpeg
.mpg  video/mpeg
.mpp  application/vnd.ms-project
.mpv2  video/mpeg
.ms  application/x-troff-ms
.mvb  application/x-msmediaview
.nc  application/x-netcdf
.nws  message/rfc822
.oda  application/oda
.ods  application/oleobject
.p10  application/pkcs10
.p12  application/x-pkcs12
.p7b  application/x-pkcs7-certificates
.p7c  application/pkcs7-mime
.p7m  application/pkcs7-mime
.p7r  application/x-pkcs7-certreqresp
.p7s  application/pkcs7-signature
.pbm  image/x-portable-bitmap
.pdf  application/pdf
.pfx  application/x-pkcs12
.pgm  image/x-portable-graymap
.pko  application/vndms-pkipko
.pma  application/x-perfmon
.pmc  application/x-perfmon
.pml  application/x-perfmon
.pmr  application/x-perfmon
.pmw  application/x-perfmon
.png  image/png
.pnm  image/x-portable-anymap
.pnz  image/png
.pot  application/vnd.ms-powerpoint
.ppm  image/x-portable-pixmap
.pps  application/vnd.ms-powerpoint
.ppt  application/vnd.ms-powerpoint
.prf  application/pics-rules
.ps  application/postscript
.pub  application/x-mspublisher
.qt  video/quicktime
.ra  audio/x-pn-realaudio
.ram  audio/x-pn-realaudio
.ras  image/x-cmu-raster
.rgb  image/x-rgb
.rmi  audio/mid
.roff  application/x-troff
.rtf  application/rtf
.rtx  text/richtext
.scd  application/x-msschedule
.sct  text/scriptlet
.setpay  application/set-payment-initiation
.setreg  application/set-registration-initiation
.sh  application/x-sh
.shar  application/x-shar
.sit  application/x-stuffit
.smd  audio/x-smd
.smx  audio/x-smd
.smz  audio/x-smd
.snd  audio/basic
.spc  application/x-pkcs7-certificates
.spl  application/futuresplash
.src  application/x-wais-source
.sst  application/vndms-pkicertstore
.stl  application/vndms-pkistl
.stm  text/html
.sv4cpio  application/x-sv4cpio
.sv4crc  application/x-sv4crc
.t  application/x-troff
.tar  application/x-tar
.tcl  application/x-tcl
.tex  application/x-tex
.texi  application/x-texinfo
.texinfo  application/x-texinfo
.tgz  application/x-compressed
.tif  image/tiff
.tiff  image/tiff
.tr  application/x-troff
.trm  application/x-msterminal
.tsv  text/tab-separated-values
.txt  text/plain
.uls  text/iuls
.ustar  application/x-ustar
.vcf  text/x-vcard
.wav  audio/wav
.wbmp  image/vnd.wap.wbmp
.wcm  application/vnd.ms-works
.wdb  application/vnd.ms-works
.wks  application/vnd.ms-works
.wmf  application/x-msmetafile
.wps  application/vnd.ms-works
.wri  application/x-mswrite
.wrl  x-world/x-vrml
.wrz  x-world/x-vrml
.wsdl  text/xml
.xaf  x-world/x-vrml
.xbm  image/x-xbitmap
.xla  application/vnd.ms-excel
.xlc  application/vnd.ms-excel
.xlm  application/vnd.ms-excel
.xls  application/vnd.ms-excel
.xlt  application/vnd.ms-excel
.xlw  application/vnd.ms-excel
.xml  text/xml
.xof  x-world/x-vrml
.xpm  image/x-xpixmap
.xsd  text/xml
.xsl  text/xml
.xwd  image/x-xwindowdump
.z  application/x-compress
.zip  application/x-zip-compressed
 

For more details on MimeMaps see:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iissdk/html/b9b7a30c-5d24-4310-bb70-398c3129f6b3.asp

For more details on using System.DirectoryServices to configure IIS see:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iissdk/html/d39fae66-abe7-4902-a3fc-f36151561f01.asp?frame=true


C# - How to display almost all properties for all IIS Virtual Web Servers

Source Code

Note: You will need to add a reference to System.DirectoryServices if you are using VisualStudio.net

using System;
using System.DirectoryServices;
namespace IISSample
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            const string WebServerSchema = "IIsWebServer"; // Case Sensitive
            string ServerName = "LocalHost";
            DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc");
            foreach (DirectoryEntry Site in W3SVC.Children)
            {
                if (Site.SchemaClassName == WebServerSchema)
                {
                    Console.WriteLine("WebSite Instance ID : " +Site.Name);
                    foreach (string PropertyName in Site.Properties.PropertyNames)
                    {
                        Console.WriteLine(PropertyName);
                        PropertyValueCollection pvc = Site.Properties[PropertyName];
                        foreach(object Value in pvc)
                            Console.WriteLine("  " + Value.ToString());
                    }
                }
                Console.WriteLine("".PadRight(80, '-'));
            }
        }
    }
}

Example Output:

ServerSize
  1
NotDeletable
  True
FrontPageWeb
  True
ServerAutoStart
  True
ServerState
  2
ServerComment
  Default Web Site
KeyType
  IIsWebServer
DefaultDoc
  Default.htm,Default.asp,index.htm,iisstart.asp
SecureBindings
  :443:
ServerBindings
  :80:
  :9090:chris
CPUResetInterval
  1440
CPULoggingInterval
  60
CPULoggingOptions
  1
CPULoggingMask
  255
CPUCGIEnabled
  True
CPUAppEnabled
  True
AnonymousPasswordSync
  True
LogType
  1
LogFilePeriod
  1
LogFileTruncateSize
  20971520
LogExtFileFlags
  1414
DirBrowseFlags
  1073741886
CacheISAPI
  True
AllowKeepAlive
  True
CGITimeout
  300
ConnectionTimeout
  900
MaxConnections
  10
ContentIndexed
  True
PasswordChangeFlags
  6
AspLogErrorRequests
  True
AspScriptFileCacheSize
  250
AspScriptEngineCacheMax
  125
AspExceptionCatchEnable
  True
AspTrackThreadingModel
  False
AspAllowOutOfProcComponents
  True
AspEnableAspHtmlFallback
  False
AspEnableChunkedEncoding
  True
AspEnableTypelibCache
  True
AspErrorsToNTLog
  False
AspProcessorThreadMax
  25
AspRequestQueueMax
  3000
AspThreadGateEnabled
  False
AspThreadGateTimeSlice
  1000
AspThreadGateSleepDelay
  100
AspThreadGateSleepMax
  50
AspThreadGateLoadLow
  50
AspThreadGateLoadHigh
  80
AspMaxDiskTemplateCacheFiles
  1000
AspAllowSessionState
  True
AspBufferingOn
  True
AspEnableParentPaths
  True
AspSessionTimeout
  20
AspQueueTimeout
  -1
AspCodepage
  0
AspScriptTimeout
  90
AspScriptErrorSentToBrowser
  True
AppAllowDebugging
  False
AppAllowClientDebug
  False
AspKeepSessionIDSecure
  False
AspBufferingLimit
  134217728
AspEnableApplicationRestart
  True
AspQueueConnectionTestTime
  3
AspSessionMax
  -1
AspLCID
  2048
AspMaxRequestEntityAllowed
  1073741824
AuthFlags
  5
AnonymousUserName
  IUSR_CCROWE
AnonymousUserPass
  O0vqT^=Vz:2\9&
NTAuthenticationProviders
  Negotiate,NTLM
LogPluginClsid
  {FF160663-DE82-11CF-BC0A-00AA006111E0}
Realm
  ap.trimblecorp.net
AspScriptLanguage
  VBScript
AspScriptErrorMessage
  An error occurred on the server when processing the URL.  Please contact the system administrator.
AdminACL
  System.__ComObject
LogFileDirectory
  C:\WINDOWS\system32\LogFiles
AspDiskTemplateCacheDirectory
  %windir%\system32\inetsrv\ASP Compiled Templates
HttpErrors
  400,*,FILE,C:\WINDOWS\help\iisHelp\common\400.htm
  401,1,FILE,C:\WINDOWS\help\iisHelp\common\401-1.htm
  401,2,FILE,C:\WINDOWS\help\iisHelp\common\401-2.htm
  401,3,FILE,C:\WINDOWS\help\iisHelp\common\401-3.htm
  401,4,FILE,C:\WINDOWS\help\iisHelp\common\401-4.htm
  401,5,FILE,C:\WINDOWS\help\iisHelp\common\401-5.htm
  403,1,FILE,C:\WINDOWS\help\iisHelp\common\403-1.htm
  403,2,FILE,C:\WINDOWS\help\iisHelp\common\403-2.htm
  403,3,FILE,C:\WINDOWS\help\iisHelp\common\403-3.htm
  403,4,FILE,C:\WINDOWS\help\iisHelp\common\403-4.htm
  403,5,FILE,C:\WINDOWS\help\iisHelp\common\403-5.htm
  403,6,FILE,C:\WINDOWS\help\iisHelp\common\403-6.htm
  403,7,FILE,C:\WINDOWS\help\iisHelp\common\403-7.htm
  403,8,FILE,C:\WINDOWS\help\iisHelp\common\403-8.htm
  403,9,FILE,C:\WINDOWS\help\iisHelp\common\403-9.htm
  403,10,FILE,C:\WINDOWS\help\iisHelp\common\403-10.htm
  403,11,FILE,C:\WINDOWS\help\iisHelp\common\403-11.htm
  403,12,FILE,C:\WINDOWS\help\iisHelp\common\403-12.htm
  403,13,FILE,C:\WINDOWS\help\iisHelp\common\403-13.htm
  403,15,FILE,C:\WINDOWS\help\iisHelp\common\403-15.htm
  403,16,FILE,C:\WINDOWS\help\iisHelp\common\403-16.htm
  403,17,FILE,C:\WINDOWS\help\iisHelp\common\403-17.htm
  404,*,FILE,C:\WINDOWS\help\iisHelp\common\404b.htm
  405,*,FILE,C:\WINDOWS\help\iisHelp\common\405.htm
  406,*,FILE,C:\WINDOWS\help\iisHelp\common\406.htm
  407,*,FILE,C:\WINDOWS\help\iisHelp\common\407.htm
  412,*,FILE,C:\WINDOWS\help\iisHelp\common\412.htm
  414,*,FILE,C:\WINDOWS\help\iisHelp\common\414.htm
  500,12,FILE,C:\WINDOWS\help\iisHelp\common\500-12.htm
  500,13,FILE,C:\WINDOWS\help\iisHelp\common\500-13.htm
  500,15,FILE,C:\WINDOWS\help\iisHelp\common\500-15.htm
ScriptMaps
  .asp,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .cer,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .cdx,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .asa,C:\WINDOWS\system32\inetsrv\asp.dll,5,GET,HEAD,POST,TRACE
  .idc,C:\WINDOWS\system32\inetsrv\httpodbc.dll,5,OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE
  .shtm,C:\WINDOWS\system32\inetsrv\ssinc.dll,5,GET,POST
  .shtml,C:\WINDOWS\system32\inetsrv\ssinc.dll,5,GET,POST
  .stm,C:\WINDOWS\system32\inetsrv\ssinc.dll,5,GET,POST
  .asax,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ascx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ashx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .asmx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .aspx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .axd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .vsdisco,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .rem,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .soap,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .config,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .cs,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .csproj,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .vb,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .vbproj,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .webinfo,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .licx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .resx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .resources,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .master,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .skin,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .compiled,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .browser,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .mdb,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .jsl,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .vjsproj,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sitemap,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .msgx,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .ad,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .dd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ldd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .cd,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .adprototype,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .lddprototype,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sdm,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .sdmDocument,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ldb,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .svc,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG
  .mdf,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .ldf,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .java,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .exclude,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
  .refresh,C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,5,GET,HEAD,POST,DEBUG
HttpCustomHeaders
  X-Powered-By: ASP.NET
MaxBandwidth
  -1

You can also do this for all of the IIS Classes such as:

IIsCertMapper Maps certificates to Windows accounts.
IIsCompressionSchemes Global settings for HTTP 1.1 compression schemes.
IIsCompressionScheme Settings for individual compression schemes.
IIsComputer Establishes global settings for IIS configuration.
IIsCustomLogModule Sets properties for custom logging information field nodes.
IIsFilter Provides information about a specific filter.
IIsFilters Manages filters.
IIsFtpInfo Establishes configuration properties for FTP servers in addition to those set at IIsFtpService.
IIsFtpServer Establishes configuration properties for a single FTP server.
IIsFtpService Establishes configuration properties common to all FTP servers.
IIsFtpVirtualDir Sets properties for an individual FTP virtual directory.
IIsIPSecurity A custom ADSI object you can use to set access permissions by IP address and domain address.
IIsLogModule Contains information about a specific logging module.
IIsLogModules Maintains information about installed logging modules.
IIsMimeMap Manages Multipurpose Internet Mail Extension (MIME) mappings.
IIsMimeType Used to manipulate the list of valid MIME types.
IIsWebDirectory Sets properties for an individual Web directory.
IIsWebFile Sets properties for an individual Web file.
IIsWebInfo Establishes configuration properties for Web servers in addition to those set at IIsWebService.
IIsWebServer Establishes configuration properties for a single Web server.
IIsWebService Establishes configuration properties common to all Web servers.
IIsWebVirtualDir Sets properties for an individual Web virtual directory.

Note: Note all classes are available at all levels in the IIS Metabase Hierarchy - so you can not for example get an IIsVirtualDirectory at the same level as the IIsWebServer because it is a child element of an IIsWebServer

For more details see the following references


Creating a virtual directory using System.EnterpriseServices and C#
I came across this post in the IIS Newsgroups today


I want to create virtual directory in IIS. I have a method in doing C# for doing this . The following code is supposed do my job. But It throws the following errors. I strongly feel there is something going wrong with the metabase path "IIS://localhost/W3SVC/1/Root".

Can somebody help me in finding out correct metabase path.

//Create a virtual directory

System.EnterpriseServices.Internal.IISVirtualRoot vr = new System.EnterpriseServices.Internal.IISVirtualRoot();

string sError;

vr.Create("IIS://localhost/W3SVC/1/Root",@"C:\Demos\WebServices\","WebServices",out sError);

The error it has thrown is :

System.Runtime.InteropServices.COMException (0x80070003): The system cannot find the path specified
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_IsContainer()
at System.DirectoryServices.DirectoryEntries.CheckIsContainer()
at System.DirectoryServices.DirectoryEntries.Add(String name, String schemaClassName)
at System.EnterpriseServices.Internal.IISVirtualRoot.Create(String RootWeb, String inPhysicalDirectory, String VirtualDirectory, String Error)
 

In my search to try to help this person I came across the original location of the code he used at
http://blogs.officezealot.com/charles/archive/2004/10/26/3191.aspx

I never know that there was a System.EnterpriseServices.Internal.IISVirtualRoot object in .NET so I learned something along the way as well.

Note: If testing this you will need to add a reference to System.EnterpriseServices

I did some simple tests to try to reproduce the error that the user has seen. I managed to get the same error by specifying an invalid metabase path which explains the The system cannot find the path specified message.

In the code above the IIS Metabase path is specified as /W3SVC/1/Root. The digit 1 (one) in the code refers to the Web Site with an Instance ID of 1. This is always the default web site.

The way to determine what your web site instance id is; is to look at the log file name.

The Log filename contains a path such as W3SVCx where x is the web site Instance ID.

Open IIS Manager and select the web site.

Right click it and select properties and the following will be displayed.

Click on the properties button to bring up the Extended logging properties dialog.

In the highlighted area in the image above you will see the web site Instance ID.

Replace the number in the code with this number and it should work fine for you.


More free books.....

While searching for some free books I came across these two good sites.

Microsoft and .NET books for free download
http://www.techbooksforfree.com/microsoft.shtml

and

Free computer science books and lecture notes
http://www.freetechbooks.com/

 


Dissecting a C# Application: Inside SharpDevelop

Learn advanced .NET programming techniques by getting an insider's look at a complete application!

The developers who created SharpDevelop give you the inside track on application development with a guided tour of the source code for SharpDevelop. They show you the most important code features and explain how you can use these techniques in your own projects. You will gain valuable experience of building an application on this scale, learning from the decisions, mistakes, problems, and solutions that led to the current version of SharpDevelop.

You will need to register to download the PDF but it is well worth it. Total Pages 538..

http://www.apress.com/free/index.html

Microsoft Atlas Control Extender - Focus

What it does

The Focus extender will allow you to set the input focus to a particular control on your web form. I know that with ASP.NET v2 you can use the DefaultFocus attribute of the

tag to set the focus but that does not work well with Master Pages.

How to use it.

In your ASP.NET source page you need to register a tag prefix to the DLL as shown below.

<%@ Register Assembly="Focus" Namespace="Focus" TagPrefix="trmb" %>

You then need to add the tags to the page to control the focus.

<trmb:FocusExtender ID="Focusextender1" runat="server">
    <trmb:FocusProperties TargetControlID="txtPN" />
</trmb:FocusExtender>

There is really only one property which you need to set which is the TargetControlID. You simply set this to the ID of the server control to set the focus to.

The source code

The source is made up of 4 primary files - the easiest way to generate source code for an Atlas Control Extender is to use the Add - New Project dialog and select the "Atlas" control project

Creating a project using the "Atlas" control project template will create 4 files for you:

  • [ProjectName]Behavior.js
  • [ProjectName]Designer.cs
  • [ProjectName]Extender.cs
  • [ProjectName]Properties.cs

Note: If you do not see the "Atlas" control project listed then you need to install the "Atlas Control Extender" templates.

Note that the "Atlas Control Extender" is for building extenders and controls, not web sites, and therefore does not work with
Visual Web Developer - it is for use with Visual C#, Visual Basic, or Visual Studio

  • In the folder where you installed the "Atlas" Control Toolkit package, you will find a folder called "AtlasControlExtender" with a file called "AtlasControlExtender.vsi" inside it - double-click AtlasControlExtender.vsi to install it
  • Choose which templates you would like to install (it is recommended to install all templates), then click "Next", then "Finish"
  • You have now installed the templates are ready to create your "Atlas" Extenders!

FocusBehavior.js

The changes made to this file have been to remove some features that we did not need to keep the file size smaller.

The code in bold is all that we have to implement to get the control to focus.

Type.registerNamespace('Focus');
Focus.FocusBehavior = function() {
    Focus.FocusBehavior.initializeBase(this);   
    
    this.initialize = function() {
        Focus.FocusBehavior.callBaseMethod(this, 'initialize');
var e = this.control.element;
if (e != null)
    e.focus();
   }
}
Focus.FocusBehavior.registerSealedClass('Focus.FocusBehavior', Microsoft.AtlasControlExtender.BehaviorBase);
Sys.TypeDescriptor.addType('focus', 'FocusBehavior', Focus.FocusBehavior);

FocusDesigner.cs

No changes were made to this file

using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.AtlasControlExtender;
using Microsoft.AtlasControlExtender.Design;
namespace Focus
{
    class FocusDesigner : ExtenderControlBaseDesigner
    {
    }
}

FocusExtender.cs

No changes were made to this file

using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;
using Microsoft.AtlasControlExtender;
#region Assembly Resource Attribute
[assembly: System.Web.UI.WebResource("Focus.FocusBehavior.js", "text/javascript")]
#endregion

namespace Focus
{
    [Designer(typeof(FocusDesigner))]
    [ClientScriptResource("Focus", "FocusBehavior", "Focus.FocusBehavior.js")]
    public class FocusExtender : ExtenderControlBase
    {
    }
}

FocusProperties.cs

The changes made to this file was to basically remove everything and leave it as below since we did not need any custom properties defined.

using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using Microsoft.AtlasControlExtender;
namespace Focus
{
    [DefaultProperty("TargetControlID")]
    public class FocusProperties : TargetControlPropertiesBase
    {
            
    }
}

COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.

If you add a reference to Microsoft Excel and then try to use it within your ASP.NET application you may receive the following error.

Server Error in '/excel' Application.


Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005.

Example Application

The problem is that by default Microsoft Excel as a COM object can only activated by the following accounts:

  • Administrator
  • System
  • Interactive

When you are running your ASP.Net account on Windows XP your web application is running as the ASPNET account.

The way to resolve this issue is to edit the DCOM configuration settings for the Microsoft Excel Application object.

Configure DCOM

  • Go to the Start-Run menu item.
  • Type in "DCOMCNFG" and hit enter.
  • This should load the "Component Services" MMC (you can also load from Administrative Tools - Component Services"
  • Expand "Component Services"
  • Expand "Computers"
  • Expand "My Computer"
  • Select the "DCOM Config" item
  • Select the "Microsoft Excel Application" item.
  • Right click and select Properties
  • Select the Security Tab and you should see the following:



     
  • Under "Launch and Activation Permissions" select the "Customize" option.
  • Click the "Edit" button

    Windows XP

             

    Windows 2003 Server

     

      
     
  • Click the "Add" button to add a new account to the list.
  • On the dialog that is displayed click the Locations button

    (this is because by default your domain will be selected and we need a local account)

    In this dialog scroll the list to the top (sometimes the first item is not visible) but scroll to the top and select the first item which is your computer name. In the list below "CCROWE" is the name of my computer.



     
  • Click the OK button
  • On the dialog that is displayed enter "ASPNET" as the account name (make sure location is set to the name of the computer that IIS is on) on Windows XP or if you are running on Windows 2003 Server you must enter the account that the Application Pool is running as, by default "Network Service"

    Windows XP

                  

    Windows 2003 Server

    Note: A quicker way on Windows XP is to just enter the computer name and the account
    so in my case that would be:

              ccrowe\ASPNET 

     


  • Click the OK button
  • Now make sure you select the following options for the "ASP.NET Machine Account" or the account that is the application pool identity ( by default Network Service)
     
    • Local Launch         : Allow
    • Remote Launch        : [blank]
    • Local Activation     : Allow
    • Remote Activation    : [blank]

    These settings can be seen below:

  •  

    Windows XP

             

    Windows 2003 Server

     
  • Click the OK button and test your web application again and it should work fine.

Note: Remember if you are running on Windows 2003 Server you must use the application pool identity as the account and not the ASPNET account.

 


C# application to show the WWW and FTP Sites and their log file directories....

I often look at the log files on my web server and with IIS 6 the folders are created with random numbers.

Correction from Tom regarding the “random numbers“:

In fact the log file names are generated from the site name so that in cases where a site is run on multiple servers the site id will be the same on each server. This helps with scripting and stuff. You can configure it in the registry to use the IIS5 type naming format if you want.

More details can be found below:

This simple application will display the WWW and FTP sites along with the log file directory. Just compile
it up or download the executable and drop the executable into your c:\windows\system32\logfiles folder and
just dblclick on it when you need to view the sites to folders relationships.



using System;
using System.DirectoryServices;
using System.IO;
using System.Collections;
using System.Windows.Forms;
namespace IISHelpDir
{
    /// 
    /// Summary description for Class1.
    /// 
    class Class1
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main(string[] args)
        {
            SortedList www = new SortedList();
            SortedList ftp = new SortedList();
            try
            {
                const string FtpServerSchema = "IIsFtpServer"; // Case Sensitive
                const string WebServerSchema = "IIsWebServer"; // Case Sensitive
                string ServerName = "LocalHost";
                DirectoryEntry W3SVC = new DirectoryEntry("IIS://" + ServerName + "/w3svc");
                foreach (DirectoryEntry Site in W3SVC.Children) 
                {
                    if (Site.SchemaClassName == WebServerSchema) 
                    {
                        string LogFilePath = System.IO.Path.Combine(
                            Site.Properties["LogFileDirectory"].Value.ToString(),
                            "W3CSVC"+Site.Name);
                        www.Add(Site.Properties["ServerComment"].Value.ToString(), LogFilePath);
                    }
                }
    
                DirectoryEntry MSFTPSVC = new DirectoryEntry("IIS://" + ServerName + "/msftpsvc");
                foreach (DirectoryEntry Site in MSFTPSVC.Children) 
                {
                    if (Site.SchemaClassName == FtpServerSchema) 
                    {
                        string LogFilePath = System.IO.Path.Combine(
                            Site.Properties["LogFileDirectory"].Value.ToString(), 
                            "MSFTPSVC"+Site.Name);
                        ftp.Add(Site.Properties["ServerComment"].Value.ToString(), LogFilePath);
                    }
                }
                int MaxWidth = 0;
                foreach(string Site in www.Keys)
                {
                    if (Site.Length > MaxWidth)
                        MaxWidth = Site.Length;
                }
                foreach(string Site in ftp.Keys)
                {
                    if (Site.Length > MaxWidth)
                        MaxWidth = Site.Length;
                }
                Console.WriteLine("Site Description".PadRight(MaxWidth)+"  Log File Directory");
                Console.WriteLine("".PadRight(79,'='));
                Console.WriteLine();
                Console.WriteLine("WWW Sites");
                Console.WriteLine("=========");
                foreach(string Site in www.Keys)
                {
                    Console.WriteLine(Site.PadRight(MaxWidth) + "  " + www[Site]);
                }                
                if (ftp.Keys.Count > 0)
                {
                    Console.WriteLine();
                    Console.WriteLine("FTP Sites");
                    Console.WriteLine("=========");
                    foreach(string Site in ftp.Keys)
                    {
                        Console.WriteLine(Site.PadRight(MaxWidth) + "  " + ftp[Site]);
                    }                
                }
            }
                // Catch any errors
            catch (Exception e) 
            {
                Console.WriteLine("Error: " + e.ToString());
            }
            finally
            {
                Console.WriteLine();
                Console.WriteLine("Press enter to close/exit....");
                Console.Read();
            }
        }
    }
}

To download a ZIP file containing the c# source and executable (.Net 1.1) please click here.


Microsoft Scripting Resources

I came across a number of cool scripting utilities today that may help others; these are:

  • Do-It-Yourself Script Center Kit
  • Scriptomatic 2.0
  • TechNet Script Center Sample Scripts
  • WMI Code Creator v1.0
  • HTA Helpomatic
  • TechNet Script Center Sample Scripts
  • Technet Script Center
  • ADSI Scriptomatic
  • Tweakomatic

Do-It-Yourself Script Center Kit

The Do-It-Yourself Script Center Kit includes all the materials you need to create your own version of the TechNet Script Center, either as stand-alone Web pages, stand-alone .vbs files, or as a .chm Help file. Included in the Kit are a database ( Microsoft Access ) of all the scripts found in the TechNet Script Center Script Repository as of January 2005, as well helper scripts for creating Web pages, .vbs files, and .chm files.

The Kit also includes instructions for using these helper scripts.

For more details see:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=D187C9D7-FFA8-49CD-BB33-363DB8FA481E&sGuid=8c9e492e-9f9b-4f33-8bad-26c69ee9a42b&hash=P8DMHJ

Scriptomatic 2.0

A completely new version of the famous Scriptomatic, the utility that writes WMI scripts for you. (And, in the process, teaches you the fundamental concepts behind writing WMI scripts for yourself.) U

nlike its predecessor, Scriptomatic 2.0 isn’t limited to writing just VBScript scripts; instead, Scriptomatic 2.0 can write scripts in Perl, Python, or JScript as well.

In addition, Scriptomatic 2.0 gives you a host of new output formats to use when running scripts, including saving data as plain-text, as a stand-alone Web page, or even as XML.

Scriptomatic 2.0 handles arrays, it converts dates to a more readable format, and it works with all the WMI classes on your computer; on top of all that, it also writes scripts that can be run against multiple machines.

For more details see:
http://www.microsoft.com/downloads/details.aspx?familyid=09DFC342-648B-4119-B7EB-783B0F7D1178&displaylang=en

Incase you want the old 2002 version :
http://www.microsoft.com/downloads/details.aspx?familyid=9EF05CBD-C1C5-41E7-9DA8-212C414A7AB0&displaylang=en

TechNet Script Center Sample Scripts

Sample scripts found in the TechNet Script Center. The sample scripts are not supported under any Microsoft standard support program or service. You can, however, report issues and bugs by sending e-mail to scripter@microsoft.com.
 

HTA Helpomatic

The HTA Helpomatic is a utility that helps script writers create HTML Applications (HTAs). HTAs enable you to provide a graphical user interface for your scripts, an interface that can include anything from list boxes to radio buttons to checkboxes. The HTA Helpomatic includes sample VBScript code and sample HTML code showing you how to do things like add a button to an HTA. Equally important, the Helpomatic also shows you how you can run a script any time that button is clicked. As an added bonus, the Helpomatic enables you to modify the scripts and HTML code and test those modifications in the utility itself.

For more details see:
http://www.microsoft.com/downloads/details.aspx?familyid=231D8143-F21B-4707-B583-AE7B9152E6D9&displaylang=en

WMI Code Creator v1.0
The WMI Code Creator tool generates code that uses WMI to obtain management information or perform management tasks. You can use the tool to learn how to manage computers using WMI scripting and WMI .NET. The tool generates code that runs on the local computer, a remote computer, or a group of remote computers based on your selection from the Target Computer menu on the tool. You can also execute the generated code directly from the tool.

The tool is meant to help IT Professionals quickly create management scripts and to help developers learn WMI scripting and WMI .NET. The tool helps take the complexity out of writing code that uses WMI and helps developers and IT Professionals understand how powerful and useful WMI can be for managing computers.

Using the tool, you can query for management information such as the name and version of an operating system, how much free disk space is on a hard drive, or the state of a service. You can also use the tool to execute a method from a WMI class to perform a management task. For example, you can create code that executes the Create method of the Win32_Process class to create a new process such as Notepad or another executable. The tool also allows you to generate code to receive event notifications using WMI. For example, you can select to receive an event every time a process is started or stopped, or when a computer shuts down.

The tool also allows you to browse through the available WMI namespaces and classes on the local computer to find their descriptions, properties, methods, and qualifiers.

The code that creates the tool is also included in the download. The tool was created using WMI .NET, and the code for the tool can help developers understand how WMI .NET is used to create applications and manage information. Be sure to read the end-user license agreement that is included in the download.
 
For more details see:
 
Technet Script Center
The TechNet script center is a repositaty specially tailed for scripting, there are columns and verything you need to learn how to write scripts for Windows is right there!
 
Find articles, documentation, webcasts, and even hands-on labs for all levels, right at your fingertips.
 
 
ADSI Scripomatic
The ADSI Scriptomatic is designed to help you write ADSI scripts; that is, scripts that can be used to manage Active Directory or IIS.
 
The ADSI Scriptomatic also teaches you an important point about ADSI scripting: like WMI, there are consistent patterns to ADSI scripts.
 
For example, the ADSI Scriptomatic will help you write a script to delete a user account. It will also help you write scripts for deleting groups and organizational units.
 
And if you take a close look at the scripts for deleting different objects, you’ll see something very interesting: theyre practical identical!
 
 
Tweakomatic

Tweakomatic is a nifty new utility that writes scripts that enable you to retrieve and/or configure Windows and Internet Explorer settings. So what, you might say. Well, think about it. Because these are Windows Management Instrumentation (WMI) scripts, they can be used to configure settings on remote computers. Need to change something on a remote computer? Then haul out Tweakomatic. And think about this: because Tweakomatic writes scripts, you could do something like run these scripts as logon or logoff scripts. In other words, you could quickly, easily, and automatically configure settings on any or all the computers in your organization. Tweakomatic is undoubtedly the single best thing Microsoft has released since Windows itself

For more details see:
http://www.microsoft.com/technet/scriptcenter/tools/twkmatic.mspx


C# - An extremely good resource for code generators for c# and other languages
http://www.codegeneration.net/generators-by-language.php?language=3

Exchange - Using WMI to list all mailboxes and their sizes from c#

First off this is my 100th post to my blog!

This is a sample of how to talk to MS Exchange to enumerate all of the mailboxes and display them with the total message count and total message size.

It also shows examples of:

  • Creating your own table
  • Using a DataView to sort the table
  • Writing to XML from a dataset
  • Padding Strings
  • Using the System.Management namespace
using System;

namespace Sample1
{
    /// 
    /// Summary description for Class1.
    /// 

    class Class1
    {
        /// 
        /// The main entry point for the application.
        /// 

        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/e2k3/e2k3/_wmiref_cl_exchange_mailbox.asp

                System.Console.WriteLine("Enumerate mailbox sizes in MS Exchange Server - Chris Crowe");
                System.Console.WriteLine();

                // Create a DataSet (only needed if you want to save to XML )
                System.Data.DataSet ds = new System.Data.DataSet();
                // Create a DataTable to hold our results
                System.Data.DataTable dt = new System.Data.DataTable("Mailboxes");            
                // Add the table to the dataset
                ds.Tables.Add(dt);

                // Create columns for our data
                dt.Columns.Add(new System.Data.DataColumn("Mailbox"typeof(String)));
                dt.Columns.Add(new System.Data.DataColumn("Messages"typeof(Int32)));            
                dt.Columns.Add(new System.Data.DataColumn("Size"typeof(Int32)));            

                // 
                System.Management.ConnectionOptions objconn = new System.Management.ConnectionOptions();
                objconn.Impersonation = System.Management.ImpersonationLevel.Impersonate;
                // Gets or sets a value indicating whether user privileges need to be enabled for the 
                // connection operation. This property should only be used when the operation performed 
                // requires a certain user privilege to be enabled (for example, a machine reboot).
                objconn.EnablePrivileges = true;

                // Exchange Server Name
                string cServername = "*"// YOUR EXCHANGE SERVER NAME

                // Create a management scrope into the Exchange WMI namespace
                System.Management.ManagementScope exmangescope = 
                    new System.Management.ManagementScope(@"\\" + cServername + @"\root\MicrosoftExchangeV2",objconn);
            
                // Create a query to get the data from the Exchange WMI
                System.Management.ObjectQuery objquery = 
                    new System.Management.ObjectQuery("SELECT * FROM Exchange_Mailbox");

                // Retrieves a collection of management objects based on the query.
                System.Management.ManagementObjectSearcher objsearch = 
                    new System.Management.ManagementObjectSearcher(exmangescope,objquery);

                // Invokes the WMI query and returns the resulting collection.
                System.Management.ManagementObjectCollection queryCollection1 = objsearch.Get(); 

                // Loop through each item in the collection
                foreach( System.Management.ManagementObject instmailbox in queryCollection1 ) 
                {
                    // Add a row of data to our table
                    dt.Rows.Add(new object[] { 
                                                 instmailbox["MailboxDisplayName"],    
                                                 instmailbox["TotalItems"], 
                                                 instmailbox["size"] } );
                } 

                // Used to calculate the size of all of the mailboxes and the message count
                int TotalMessages=0;
                Int64 TotalSize=0;

                // Create a DataView to sort the data by Mailbox Size
                System.Data.DataView dv = new System.Data.DataView(dt);
                dv.Sort = "Size desc, Mailbox";

                // Write a heading
                System.Console.WriteLine(string.Format("{0} {1} {2} "
                    "Mailbox".PadRight(55), 
                    "Messages".PadLeft(8), 
                    "Size".PadLeft(13)));
            
                // Write a line of dashes
                System.Console.WriteLine("".PadRight(78'-'));

                // Get an enumerator to enumate the DataView to get the rows from the table (sorted)
                System.Collections.IEnumerator enumerator = dv.GetEnumerator();            
            
                // Loop through each item in the table
                while(enumerator.MoveNext())
                {
                    // Get a row 
                    System.Data.DataRowView row = enumerator.Current as System.Data.DataRowView;

                    // Display the row
                    System.Console.WriteLine(string.Format("{0} {1} {2} Kb"
                        row["Mailbox"].ToString().PadRight(55), 
                        row["Messages"].ToString().PadLeft(8), 
                        row["Size"].ToString().PadLeft(10)));

                    // Add the size and message count to our totals
                    TotalMessages += Convert.ToInt32(row["Messages"]);
                    TotalSize += Convert.ToInt64(row["Size"]);
                }

                // Write a row of dashes
                System.Console.WriteLine("".PadRight(78'-'));

                // Write the totals
                System.Console.WriteLine(string.Format("{0} {1} {2} Kb"
                    "Total".PadRight(55), 
                    TotalMessages.ToString().PadLeft(8), 
                    TotalSize.ToString().PadLeft(10)));

                // Write the XML to a file if we want to
                ds.WriteXml("Mailboxes.xml");        
            }

            // Catch any problems and show a message!
            catch(Exception e)
            {
                System.Console.WriteLine("Error : " + e.Message.ToString());
            }
        }
    }
}
 

This is how it displays its output to the console.

If you write the data to a XML file as the above example does this is how it may appear.

xml version="1.0" standalone="yes"?>
<NewDataSet>
  <Mailboxes>
    <Mailbox>WeeThings</Mailbox>
    <Messages>742</Messages>
    <Size>41596</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>SMTP (SBS2003-{7390D6EA-A466-417D-A461-ADEA24553CB8})</Mailbox>
    <Messages>0</Messages>
    <Size>0</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>worldnet</Mailbox>
    <Messages>11</Messages>
    <Size>51</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Paradise</Mailbox>
    <Messages>25</Messages>
    <Size>80</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>SystemMailbox{7390D6EA-A466-417D-A461-ADEA24553CB8}</Mailbox>
    <Messages>401</Messages>
    <Size>361</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Art</Mailbox>
    <Messages>53</Messages>
    <Size>333</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Chris Crowe [MVP]</Mailbox>
    <Messages>20</Messages>
    <Size>170</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Pam Elston</Mailbox>
    <Messages>1052</Messages>
    <Size>20852</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Stocks</Mailbox>
    <Messages>33</Messages>
    <Size>607</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>stuff</Mailbox>
    <Messages>106</Messages>
    <Size>1716</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>TradeMe</Mailbox>
    <Messages>287</Messages>
    <Size>1846</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>chris crowe</Mailbox>
    <Messages>4201</Messages>
    <Size>239183</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>IISFAQMailBoxes</Mailbox>
    <Messages>338</Messages>
    <Size>878</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>WeeThings_Trademe</Mailbox>
    <Messages>16</Messages>
    <Size>278</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>PamStocks</Mailbox>
    <Messages>94</Messages>
    <Size>160</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Pets</Mailbox>
    <Messages>20</Messages>
    <Size>148</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Chris Crowe</Mailbox>
    <Messages>14416</Messages>
    <Size>221939</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>IISMVP</Mailbox>
    <Messages>15</Messages>
    <Size>638</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>CarryingABitTooMuch</Mailbox>
    <Messages>19</Messages>
    <Size>1056</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>chris_iisfaq</Mailbox>
    <Messages>4944</Messages>
    <Size>48027</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Forums</Mailbox>
    <Messages>2</Messages>
    <Size>4</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Test</Mailbox>
    <Messages>4</Messages>
    <Size>5</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>System Attendant</Mailbox>
    <Messages>0</Messages>
    <Size>0</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>psoriasis</Mailbox>
    <Messages>3</Messages>
    <Size>5</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Holiday</Mailbox>
    <Messages>959</Messages>
    <Size>24704</Size>
  </Mailboxes>
  <Mailboxes>
    <Mailbox>Braindump</Mailbox>
    <Messages>14</Messages>
    <Size>121</Size>
  </Mailboxes>
</NewDataSet>

c# - Open Source Projects written in c#

Here is a site that lists open source c# projects such as:

  • Aspect-Oriented
  • Bloggers
  • Build Systems
  • Charting & Reporting
  • Chat Servers
  • CMS
  • Code Coverage
  • Forum Soft
  • IDEs
  • Installers
  • Inversion of Control
  • Issue Tracking
  • Logging Tools
  • Network Clients
  • Network Servers
  • PDF Libraries
  •  
  • Persistence
  • Portals
  • Profilers
  • Project Management
  • RSS & RDF Tools
  • Rule Engines
  • Search Engines
  • Source Control
  • SQL Clients
  • Template Engines
  • Testing Tools
  • Web Frameworks
  • Web Mail
  • Web Testing
  • Wiki Engines
  • XML Parsers
  • For more details see http://csharp-source.net/

    ASP.NET - How to render a Server Control to a string

    The following method renders control into HTML string.


       public static string RenderControl(Control ctrl) 
       {
          System.Text.StringBuilder sb = new System.Text.StringBuilder();
          System.IO.StringWriter tw = new System.IO.StringWriter(sb);
          System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
          ctrl.RenderControl(hw);
          return sb.ToString()
       }
    

    ASP.Net Server Control - Dynamic Lookup Edit Control with Popup Window

    Welcome to my ASP.NET Server Control : LookupEditControl. This control uses a number of different technologies to do its magic.

    • Dynamic requests, DHTML, and JavaScript

    There is a lot of talk these days about AJAX but not a lot of source in the edit control stage from what I have found. There is always the Google Suggest discussions but no real code.

    I have written an ASP.Net server control (currently still in development) that does what I need and works quite well, but not 100% well, still more work to do.

    Here are some of the features that I have implemented and currently basically work

    • ASP.Net Server Control
    • Multi Browser Compatible (IE 6, and Firefox 1.04, maybe others?)
    • Supports Multiple Columns in the popup window
    • Supports saving a value that is visible in the Columns just like a DropDownList
    • Supports updating values when you have tabbed off the control, this was for those times when you type too quick and the control is still doing its lookup.
    • Supports defining the width of the Popup Window
    • Supports CSS styles for the columns and the Popup Window
    • Supports Keyboard Up/Down
    • Supports Mouse Selection
    • Popup Window Displays over Select Tags with no bleeding 

    I really am looking for people to help me with this project as I need testers and people with ideas who may be better than me to help clean up the code.

    If you want to see it in action browse to http://code.crowe.co.nz/LookupEditControl/

    Please let me know what you think of this control as I have spent a lot of time and I am quite happy with it but there are issues yet to be fixed.


    IIS - Creating Web Sites and AppPools using WMI ( C# sample code )

    I came across a very good example of creating Web Sites with custom App Pools in c# using WMI by a guy called Ramesh Raman's who has a blog at MSDN blogs. It it appears he no longer updates it since the last entry is dated July, 2004

    He had an example of using the WMI Provider and XML to create a new web site with a complete description of the process of each step taken:

    Using the WMI Provider to Configure IIS 6.0 - A Data Driven Approach
    http://blogs.msdn.com/ramesh_r/archive/2004/03/24/95109.aspx

    For just the code (which was updated to include the creation of App Pools and Virtual Directories) see:

    http://blogs.msdn.com/ramesh_r/articles/170665.aspx

    For a copy of the code click here (just incase it disappears) - please note you should right click and save-as as you can not view it as IE will try to render it as XML and fail (although you can then do a view-source to see the code)


    ILMERGE - Merge multiple .NET assemblies (.exe, .dll) into a single .NET assembly

    ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly. ILMerge takes a set of input assemblies and merges them into one target assembly. The first assembly in the list of input assemblies is the primary assembly. When the primary assembly is an executable, then the target assembly is created as an executable with the same entry point as the primary assembly. Also, if the primary assembly has a strong name, and a .snk file is provided, then the target assembly is re-signed with the specified key so that it also has a strong name.

    ILMerge is packaged as a console application. But all of its functionality is also available programmatically. While Visual Studio does not allow one to add an executable as a reference, the C# compiler does, so you can write a C# client that uses ILMerge as a library

    For more details see - http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en


    Looking for the source to the .Net Framework Libraries

    We all know that Microsoft has not released the source code to the .NET Framework.

    If you do not know about a tool called .Net Reflector, then you are missing something very important. With this tool you can view the code to .NET DLL's that have not been obfuscated

    I was looking to try and find a problem with a Server Control I was writing for ASP.Net - this server control was inherited from TextBox and I had a problem with trying to add a collection property to the control. I could get it rendered correctly to the WebForm but when I reopened the web form the .TEXT property was filled with my collection details and the collection property was empty.

    Using this tool you can see code for objects such as TextBox and therefore maybe make a better choice in the way you develop code.

    See example below for the AddAttributesToRenderMethod of the TextBox class for ASP.Net

    For more details where you can download this tool see - http://www.aisto.com/roeder/dotnet/

    Also see Lutz Roeder's Weblog for more details regarding .Net Reflector

    For addons such as rendering the source in different languages see http://csharp21.tripod.com/ReflectorAddIns

    I wish I had used this tool before - thanks Lutz for writing it and releasing it to the community.


    How to set the return code (ExitCode) from a c# Console Application

    The following is the way to specify an exit code in a c# application. A value of 0 is normally a sign of success and a value of 1 or more a sign of failure.

    int MyErrorCode = 0

    System.Environment.ExitCode = MyErrorCode


    Regular Expressions - [ Freeware ] Expresso 2.1

    Expresso is useful for learning how to use regular expressions and for developing and debugging regular expressions prior to incorporating them into C# or Visual Basic code.

    • Build complex regular expressions by selecting components from a palette
    • Test expressions against real or sample input data
    • Display all matches in a tree structure, showing captured groups, and all captures within a group
    • Build replacement strings and test the match and replace functionality
    • Highlight matched text in the input data
    • Test automatically for syntax errors
    • Generate Visual Basic or C# code
    • Save and restore data in a project file
    • Maintain and expand a library of frequently used regular expressions

    For more details see - http://www.ultrapico.com/Expresso.htm

    For more details on Regular Expressions try:


    Step/Step - An example of updating a Windows Sharepoint Server List from c#

    1) Open Visual Studio.NET 2003

    2) New Project (We will create a console application in this demo)

    3) Name your project "GetListItems"

    4) Right Click on "References" under the Project and select "Add Web Reference"

    5) In the URL field type the path to your Windows SharePoint Services Site that contains the list you want to use.

    Each site is different and only contains the lists for the particular child site.

    For example the root site could be called "http://sharepoint.mysite.com" and you could have a sub site called "Test" which is accessible via "http://sharepoint.mysite.com/Test"

    So type in your URL and append the following "_vti_bin/lists.asmx"

    So if you were going to the "Test" child site your URL would be like this:

    http://sharepoint.mysite.com/Test/_vti_bin/lists.asmx

    You may be prompted to log onto your SharePoint site when do perform this action.

    6) Click on "Go" and the Add Web Reference Dialog should display that it found one service and display you some available operations.

    7) Click on "Add Reference"

    8) Now you should end up with a new Web Reference Node in the Solution Explorer and your actual Web Reference which may have a funny name like "com.mysite.sharepoint"

    9) Right click on the Web Reference and rename it to something simple like "SharePoint", this is what we will use to reference the web service in code.

    10) Right click on the Web Reference and select "Properties" and change the "URL Behavior" to "dynamic"

    This will add a "app.config" to the project and populate an appSettings item in the config file so that the URL is dynamically loaded from the "app.config" file and not hard coded into the source of the proxy stub that was created.

    <?xml version="1.0encoding="utf-8"?>
    <configuration>
         <appSettings>
               <add key="GetListItems.Sharepoint.Listsvalue="http://sharepoint.mysite.com/Test/_vti_bin/lists.asmx"/>
         </appSettings>
    </configuration>

    11) Open the Class1.cs file in the editor and enter the following:

    using System;
    using System.Net;
    using System.Xml;

    namespace GetListItems
    {
        /// 
        /// Summary description for Class1.
        /// 

        class Class1
        {
            /// 
            /// The main entry point for the application.
            /// 

            [STAThread]
            static void Main(string[] args)
            {
                string Username="UserName";
                string Password="Password";
                string Domain="Domain";
                string ListName = "ListName";

                Sharepoint.Lists ListsService = new Sharepoint.Lists();
                ListsService.Credentials = new NetworkCredential(Username, Password, Domain);

                // Create a new XML document to hold the updates we are going to perform
                XmlDocument doc = new XmlDocument();
                XmlElement updates = doc.CreateElement("Batch");
                updates.SetAttribute("OnError""Continue");

                // We need to Create a Method Tag for each row we are going to update.
                XmlElement UpdatesMethod = doc.CreateElement("Method");
                UpdatesMethod.SetAttribute("ID""1");
                UpdatesMethod.SetAttribute("Cmd""Update");
                updates.AppendChild(UpdatesMethod);

                // We need to update a particular row based on its internal ID.

                XmlElement UpdatesField1 = doc.CreateElement("Field");
                UpdatesField1.SetAttribute("Name""ID");        // Which record to update
                UpdatesField1.InnerText = "1";                    // is defined here
                UpdatesMethod.AppendChild(UpdatesField1);

                // We are going to update the field called "Status"

                XmlElement UpdatesField2 = doc.CreateElement("Field");
                UpdatesField2.SetAttribute("Name""Status");    // Which field to update
                UpdatesField2.InnerText = "Status is OK";        // The actual new value
                UpdatesMethod.AppendChild(UpdatesField2);
            
                // Call the web service to update the list items
                XmlNode Result = ListsService.UpdateListItems(ListName, updates);

                ListsService.Dispose();

                Console.WriteLine("The record has been updated!");

                // Sleep for a moment so we can see the results
                System.Threading.Thread.Sleep(5000);
            }
        }
    }

    Make sure you populate the Username, Password, Domain, and ListName variables above. You also need to make sure that the field “Status” exists in the particular list that you are updating. If it does not you will need to change it to a field that does exist.

    For some sample code that will allow you to display the attribute names in a list see - /archive/2005/08/10/197.aspx

    The XmlNode called Result should be parsed to locate errors that may have occurred during the update.


    Step/Step How to retrieve the contents of a Windows SharePoint Services List from c#

    1) Open Visual Studio.NET 2003

    2) New Project (We will create a console application in this demo)

    3) Name your project "GetListItems"

    4) Right Click on "References" under the Project and select "Add Web Reference"

    5) In the URL field type the path to your Windows SharePoint Services Site that contains the list you want to use.

    Each site is different and only contains the lists for the particular child site.

    For example the root site could be called "http://sharepoint.mysite.com" and you could have a sub site called "Test" which is accessible via "http://sharepoint.mysite.com/Test"

    So type in your URL and append the following "_vti_bin/lists.asmx"

    So if you were going to the "Test" child site your URL would be like this:

    http://sharepoint.mysite.com/Test/_vti_bin/lists.asmx

    You may be prompted to log onto your SharePoint site when do perform this action.

    6) Click on "Go" and the Add Web Reference Dialog should display that it found one service and display you some available operations.

    7) Click on "Add Reference"

    8) Now you should end up with a new Web Reference Node in the Solution Explorer and your actual Web Reference which may have a funny name like "com.mysite.sharepoint"

    9) Right click on the Web Reference and rename it to something simple like "SharePoint", this is what we will use to reference the web service in code.

    10) Right click on the Web Reference and select "Properties" and change the "URL Behavior" to "dynamic"

    This will add a "app.config" to the project and populate an appSettings item in the config file so that the URL is dynamically loaded from the "app.config" file and not hard coded into the source of the proxy stub that was created.

    <?xml version="1.0encoding="utf-8"?>
    <configuration>
         <appSettings>
               <add key="GetListItems.Sharepoint.Lists
                  value="http://sharepoint.mysite.com/Test/_vti_bin/lists.asmx"/>
         </appSettings>
    </configuration>

    11) Open the Class1.cs file in the editor and enter the following:

    • Add using System.Net; to the using clause at the top of the page.
    • Add using System.Xml; to the using clause at the top of the page.

    In the Main() function add the following code:

    string Username="MyUsername";
    string Password="MyPassword";
    string Domain="MyDomain";
    string ListName = "MyListName";
    string MaxItemsToReturn = "999";

    Sharepoint.Lists ListsService = new Sharepoint.Lists();
    ListsService.Credentials = new NetworkCredential(Username, Password, Domain);
    XmlNode RootNode = ListsService.GetListItems(ListName, ""nullnull, MaxItemsToReturn, null);

    XmlNamespaceManager Manager = new XmlNamespaceManager(RootNode.OwnerDocument.NameTable);
    Manager.AddNamespace("sp""http://schemas.microsoft.com/sharepoint/soap/");
    Manager.AddNamespace("z""#RowsetSchema");
    Manager.AddNamespace("y""http://schemas.microsoft.com/sharepoint/soap/ois/");
    Manager.AddNamespace("w""http://schemas.microsoft.com/WebPart/v2");
    Manager.AddNamespace("d""http://schemas.microsoft.com/sharepoint/soap/directory/");

    XmlNodeList Nodes = RootNode.SelectNodes("//z:row", Manager);
    foreach(XmlNode Node in Nodes)
    {
     foreach(XmlAttribute attrib in Node.Attributes)
     {
      Console.WriteLine("{0} - {1}", attrib.Name, attrib.InnerText);
     }
     Console.WriteLine();
    }
    ListsService.Dispose();
    // Sleep for a moment so we can see the results
    System.Threading.Thread.Sleep(5000);

    Make sure you populate the Username, Password, Domain, and ListName variables above and then run your code and you should see the attributes that are available and the values for each item in the list.


    C# Sample code to talk to a printer using SNMP to get its status.

    The following code will allow you to talk to a printer (running on a specific IP Address) to query its current status.

    OLEPRNLib is a COM object that appears to be installed on XP and greater machines.

    On my machine I made a reference on the COM tab of the Add Reference dialog to “oleprn 1.0 Type Library“ which lived in “c:\Windows\System32\oleprn.dll

    using System;
    using OLEPRNLib;
    
    namespace PrinterStatus
    {
     /// 
     /// Summary description for Class1.
     /// 
     class Class1
     {
      /// 
      /// The main entry point for the application.
      /// 
      [STAThread]
      static void Main(string[] args)
      {
       string[] ErrorMessageText = new string[8];
    
       ErrorMessageText[0] = "service requested";
       ErrorMessageText[1] = "offline";
       ErrorMessageText[2] = "paper jammed";
       ErrorMessageText[3] = "door open";
       ErrorMessageText[4] = "no toner";
       ErrorMessageText[5] = "toner low";
       ErrorMessageText[6] = "out of paper";
       ErrorMessageText[7] = "low paper";
    
       int DeviceID = 1;
       int Retries = 1;
       int TimeoutInMS = 2000;
       string CommunityString = "public";
       string IPAddressOfPrinter = "10.3.0.93";
    
       // Create instance of COM object
       OLEPRNLib.SNMP snmp = new OLEPRNLib.SNMP();
    
       // Open the SNMP connect to the printer
       snmp.Open(IPAddressOfPrinter, CommunityString, Retries, TimeoutInMS);
    
       // The actual Warning/Error bits
       uint WarningErrorBits = snmp.GetAsByte(String.Format("25.3.5.1.2.{0}", DeviceID));
    
       // The actual Status
       uint StatusResult = snmp.GetAsByte(String.Format("25.3.2.1.5.{0}", DeviceID));
    
       // uint Result2 = snmp.GetAsByte(String.Format("25.3.5.1.1.{0}", DeviceID));
    
       string Result1Str = "";
       switch (StatusResult)
       {
        case 2 : Result1Str = "OK";
          break;
        case 3 : Result1Str = "Warning: ";
         break;
        case 4 : Result1Str = "Being Tested: ";
         break;
        case 5 : Result1Str = "Unavailable for any use: ";
         break;
        default : Result1Str = "Unknown Status Code : "+StatusResult;
         break;
       }
    
       string Str = "";
       if ((StatusResult == 3 || StatusResult == 5))
       {
        int Mask = 1;
        int NumMsg = 0;
        for (int i=0; i< 8; i++)
        {
         if ((WarningErrorBits & Mask) == Mask)
         {
          if (Str.Length > 0)
           Str += ", ";
          Str += ErrorMessageText[i];
          NumMsg = NumMsg + 1;
         }
         Mask = Mask * 2;
        }
       }
       Console.WriteLine(Result1Str + Str);
      }
     }
    }