Peter

Creative, customer focused, results oriented Windows web developer and server administrator who enjoys providing the highest level of customer service supporting complex Windows server hosting solutions. MCITP SA, EST, DBA 2008

Mar 132013
 

Remote Management for IIS 8 on Windows Server 2012 is a great way to connect to your site and accessing IIS features without logging in to the server.  It is straight forward to configure but requires a few steps to get working properly. An alternative scenario would be if you are using a 3rd party for Windows shared hosting and you do not have administrative access to the server. You could then use IIS Manager for Remote Administration on your PC to connect to the site and maintain it.

Installing the Management Service on the Server

With Windows Server 2012 and IIS 8 there are 2 ways that you can have this service installed. The first way is using the Server Manager and launching the Add Roles and Features Wizard.

image

 

Once the Add Roles and Features Wizard opens scroll down to the Web Server (IIS) role and expand the management tools section. Click the checkbox next to Management Service and then click Next to complete the wizard.

image

 

Once installation completes you will see that it has been added to the IIS Roles and Features in Server Manager.

image

 

Alternatively you can install the Management Service using the Web Platform Installer. Open IIS Manager on the server and click Get New Web Platform Components.

image

 

The Web Platform Installer will open up. You can filter on products named IIS and then sort the name column. In the list you’ll see the IIS Management Service. Click Add then then complete the wizard. It will take just a few moments to complete. The wizard will display a confirmation page upon completion. You can also double check that it has been installed successfully in the IIS Roles and Features in Server Manager as shown above..

image

 

Configure IIS for Remote Administration

After the remote management service has been installed on the server you need to enable it and then assign user permissions before users can connect remotely. In IIS Manager at the server level scroll down to the Management groupHere you can add IIS Manager Users, check permissions for existing users, control Feature Delegation, and maintain the Management Service settings. Click on Management Service to configure remote administration and enable the service.

image

 

Click Enable remote connections and then select whether or not you want to allow users to access the server using Windows credentials only or allow users with Windows credentials and IIS Manager credentials. Assign the IP address you want the service to be on and the default port 8172. If you have your own certificate you can assign that otherwise there is a default certificate available to be used. For additional security you can implement IP address restrictions. After saving your changes be sure to click Start. If you decide to change any settings later you’ll need to stop the service first before you can make any changes.

image

 

Allow Users to Access the Site Remotely

User permissions are assigned at the site level. Go to the site you want to allow remote access to and click IIS Manager Permissions.

image

 

Click Allow User.

image

 

To add a Windows user click Select and then enter their name and then click Ok.

image

Remote administration has now been enabled and configured on the server. You have enabled a user to remotely connect to IIS. At this point the server configuration is complete. The only thing remaining is to install IIS Manager for Remote Administration on your PC.

 

Configure Client Settings

On your PC use the Web Platform Installer to install IIS Manager for Remote Administration.

http://www.iis.net/downloads/microsoft/iis-manager

image

 

Once IIS Manager is installed on your PC then you can try connecting to the site. Simply right-click on the globe icon under Connections and then select Connect to a Site.

image

 

Enter the server address where your site is hosted and the site name.

image

 

Enter the username and password for authentication.

image

 

Click Finish and then you’ll see your site in IIS Manager.

image

 

If you look at the bottom right of the window you’ll see that you’ve connected securely to the remote site.

image

 

Summary

This walkthrough has covered how to install and configure Remote Administration on IIS 8 as well as using the Web Platform Installer to install the IIS Manager for Remote Administration on your PC.  Check with your Windows shared hosting provider if you have any difficulty connecting to your site. Depending your hosting providers delegation settings certain IIS features may not be enabled for remote administration. Thanks for reading.

Feb 092013
 

In 2011 the FTP protocol had it’s 40 birthday. Despite it’s age it is still a widely used file transfer technology however it wasn’t originally designed for encryption. It has been shown to be vulnerable to brute force attacks, packet capture, and spoof attacks as well as a few other attack vectors. Now with IIS 8 on Windows Server 2012 encrypting an FTP session has never been easier. Using the IIS Manager with just a few clicks you can enable FTPS also known as FTP Over SSL on your site and take advantage of encrypted communication. In this walkthrough I am going to configure FTPS on IIS 8 using my personal SSL certificate which I obtained from a 3rd party SSL vendor. I am not going to cover how to install an SSL certificate. To get started launch IIS Manager from the Start Screen.

image

 

Once IIS Manger is open we first need to add FTP Publishing to our site. This is straight forward and can be completed in mere moments. To do this right click on your site and select Add FTP Publishing. The Add FTP Site Publishing wizard will launch taking us through the few remaining steps.

image

 

There are a few options which need to be configured. Select the IP address you want to use for the site. Under the SSL setting, select if you want to allow connections without SSL or force every connection to use it. For the highest level of security you’ll want to select Require SSL. Next pick the SSL certificate that you want to use for the encryption. Click Next to continue.

image

 

Now we’re going to configure the Authentication and Authorization settings. Check Basic Authentication and leave Anonymous Authentication unchecked. Under Authorization you can specify local users and groups that are allowed to access the site. On my test server I have a user called “ftpuser2” and we want Read and Write permissions enabled. Click Finish and then the window will close. FTP Publishing has been added to the site. Next we’ll need to configure the FTP client before we can connect.

image

 

Configuring your FTP client for FTP over SSL is just a matter of changing the protocol type in your client settings.  First I’ll do a test without making any client changes. In the previous step I choose to force all connections to use FTPS so we should get an error of some kind. Sure enough as seen in the FTP log below, the server forcibly closes the connection when it detects that we’re not using FTPS.

image

 

For my FTP client I’m using an old version Cute FTP Pro so depending on which FTP client you are using your menus may look different. Below I am selecting FTP with SSL Explicit.

image

 

Now when I try to reconnect to the server I’m prompted to accept the SSL certificate before I can continue. If I do not accept the certificate then the connection will be closed.

image

 

After clicking Accept we are logged into the FTP site and are files are displayed as expected. Looking at the FTP log we see the SSL session is being established and the session is encrypted.

image

In summary, FTP is a great file transfer technology but is unencrypted in native form. Configuring FTP over SSL with IIS 8 on Windows Server 2012 is an easy and straight forward way encrypt your FTP sessions and increase your security. Thanks for reading.

Jan 302013
 

Configuring and using FTP with IIS 8 on Windows Server 2012 is very easy and straight forward. If you ever used FTP 7 that was released with Windows 2008 then the GUI will be familiar to you. An FTP virtual directory is quite handy when you need to provide an FTP user access to files which are not in their FTP root folder. If you’ve ever created one, then you know the FTP user is usually not able to physically “see” the virtual directory when they login. To get to the new folder they have to manually change the path using their FTP client. I will show you a simple trick so the virtual directory will be visible to the FTP user.

image

 

Open the IIS 8 Manger. Depending on your needs one can have FTP configured in a few different ways. Your server may have FTP publishing configured on each site for example. My test server only has 1 IP address available so I’ve configured a “master” FTP site and have FTP user access configured accordingly for each site that is being hosted. In this example I have “ftpuser2” logging into a folder called c:\domains\domain2.com. As one would expect this is the folder where the user can maintain all their web site files.

image

 

Probably one of the most common requests with web hosting is having access to the web site traffic logs. These logs are typically stored outside of the FTP path somewhere else on the web server.  On my test server they’re stored in the folder C:\wwwlogs and the logs for domain2.com are located in the folder W3SVC3. Ordinarily on a locked down web server no FTP user would ever be able to access this location.

image

 

So let’s walk through how to provide “ftpuser2” FTP access to his site’s traffic logs. In the IIS Manger right-click on the FTP user in question and then right-click again on Add Virtual Directory.

image

 

This will open the Add Virtual Directory window. Enter the Alias you want to use and browse the physical path to which you want to provide FTP access.

image

 

One additional step is to add the FTP user to the folder permissions. That is straight forward so I’m not going to walk through that. So now ftpuser2 has the necessary permissions to read the log files in the W3SVC3 folder and access them using their FTP client. So what happens when we log in via FTP? Well nothing.

image

 

Why don’t we see our new virtual directory with the traffic logs? We can see them if we manually change the path in the FTP client to /wwwlogs. But having to manually change paths is a bit of a pain. And trying to explain that to someone who may not be technical is even more complicated. So what’s the solution?

image

The solution is to create an empty folder in the root of the FTP user’s FTP path that matches the alias of our FTP virtual directory. With this dummy folder in place, when the FTP user logs in and clicks it they will automatically be redirected into the path of the virtual directory and see all the files. What’s really cool about this technique is that works with legacy versions of IIS as well as IIS 7 and IIS 8.

image

So now we’ve created a far more intuitive experience for the FTP user to access files and folders outside of their FTP root anywhere on the server –provided they have permissions to access the folder of course. I hope you’ve enjoyed this walkthrough. Thanks for reading.

Dec 142012
 
Using system.net.mail to send email messages from your web site makes life so easy.  In the old days of Classic ASP you often had to rely on 3rd party components such as AspMail from serverobjects.com or AspEmail from persists.com. While they were very capable products and are still widely used today it added an additional layer of complexity to your programming. If you ever had to move a site from one server to another there was always a risk the components were not in place which would cause problems for your users.  With system.net.mail you know as long as .Net is installed on the server hosting your site, your code will always work no matter how many times you move your web site or change hosting providers. In it’s simplest form the snippet below is the bare minimum of code you need to send a plain text message from your asp.net application.
//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body";

//send the message
SmtpClient smtp = new SmtpClient("localhost");
smtp.Send(mail);
This works great when you are sending mail using the local SMTP server. However in certain situations you may need to send mail through a remote SMTP server. In most cases that remote server will have quite a bit of security enabled to prevent relaying and blocking spammers so the above code will not be enough for your application to send mail. In this case you will need to send your message by authenticating on the remote server with a username and password. So how does one go about doing that with system.net.mail? Well here’s a bit a code that shows you how to do just that.
string strTo = "test@gdomain-y.com";
string strFrom="test@domain-x.com";
string strSubject="Mail Test Using SMTP Auth";
string strBody="This is the body of the message";

string userName = "xxx"; //remote mail server username
string password = "xxx"; //remote mail server pasword

MailMessage mailObj = new MailMessage(strFrom, strTo, strSubject, strBody);
SmtpClient SMTPServer = new SmtpClient("mail.mydomain.com"); //remote smtp server
SMTPServer.Credentials = new System.Net.NetworkCredential(userName, password);
try 
{ 
SMTPServer.Send(mailObj); 
Response.Write("Sent!"); 
}
 
catch (Exception ex) 
{
Response.Write(ex.ToString()); 
}

For additional examples check out the wonderful resource at http://www.systemnetmail.com. I hope this helps. Thanks for reading.
Dec 092012
 

The other day I was helping someone who was trying to configure a wildcard certificate on their Windows Cloud Server. Their server was running Windows 2008 R2 server using IIS 7. The were technically savvy and knew how to configure site’s on their own and install a regular SSL certificate but they were stuck trying to get a wildcard certificate configured properly.

They had quite a few site’s configured using subdomains such as support.domain.com, mail.domain.com, login.domain.com, etc. To tighten security they decided to use SSL to protect all these sites so they bought a wildcard certificate for *.domain.com. They installed the new certificate on the 1st site correctly but when they tried doing it on the 2nd site they couldn’t. IIS wouldn’t let them assign the certificate on the other sites using a shared IP address. Does this sound familiar? Here’s how you can solve it and it’s easier than you think.

Here are 4 site’s configured in IIS using host header xxx.domain.com with the same IP address.

image

 

After installing our wildcard SSL certificate we assign the binding on the first site.

image

 

Testing the site we see that the wildcard SSL certificate is working great.

image

 

Now we go to site #2 and try to assign our certificate. However we’re not able to enter a host name for site #2.

image

 

If we click OK and try to proceed we get a warning about the dire consequences of our actions. As soon as we try to access site #2 using SSL, IIS will actually stop site #1 which cause all kinds of issues for our users.

image

 

Now that we’ve seen the problem let’s the get to the solution. According to my friend, former coworker, and IIS MVP Scott Forsyth, it turns out that this is not a bug and the IIS team designed it to work this way. There are 2 ways to solve this particular issue when using a wildcard SSL certificate. One way is to simply execute the following app command for each binding that you need.

appcmd set site /site.name:”” /+bindings.
[protocol='https',bindingInformation=':443:']

This certainly works however I tend to have hard time remembering the syntax which leads us to the 2nd method which is in my opinion is far easier and has to do with how the wildcard SSL certificate was originally installed.

Remember back when you had just received the completed wildcard certificate from your SSL vendor? Like most IT people you were probably in a hurry when you installed it. Do you remember what you entered when you were prompted for a Friendly name before saving it? Chances are you just entered “domain.com” however what you should have specified is “*.domain.com”. Doh!

You can check this easily by looking at the certificate store in IIS Manager. If the Name column doesn’t show the * then you need to change it before it SSL binding on multiple sites will work properly.

image

 

So how does one change the Friendly name this after the certificate has already been installed? Open the MMC Snap-In for Certificates. Right-click on the certificate and change the Friendly name to *.domain.com. Save the changes and close out the MMC.

image

 

Now that the Friendly name has been changed to *.domain.com go back to IIS and try to add the SSL binding for site number #2 and now it works. Woohoo. Smile

image

 

Now you can add your wildcard certificate to as many subdomain host header sites as needed using only 1 IP and you don’t have to remember any programming syntax. I hope this helps and thanks for reading.

Nov 302012
 

In case you haven’t heard Windows 8 is now available. As a web developer I think one of the best reasons to upgrade to Windows 8 is that you can start testing IIS 8 right from your PC. This way if you don’t have a budget for a new server you can start to familiarize yourself with some of the new features.

IIS 8 has some great new features such as Dynamic IP Restrictions an Application Initialization. However one of the best new features of IIS 8 enables you to throttle the CPU utilization for any application pool. If you’ve ever hosted a server with multiple sites you’ve probably experienced a situation where one site impacts the performance of the entire server. With this new feature now that will never become an issue.

IIS 8 is not installed by default on Windows 8. To install IIS 8 you just need to add it using the Control Panel. To get to the Control Panel just right-click on the background and you’ll see the All Apps icon come on screen at the bottom right. Click this and then click the Control Panel.

image

You can also get to the Control Panel from the Desktop. Just click Settings and then click on the Control Panel.

image

The Control Panel hasn’t changed much with Windows 8. It looks pretty much like it did in Windows 7. Once you’re at the Control Panel just click on Programs menu item.

image

 

Next you just need to click on Turn Windows features on or off. This will be under the Programs and Features menu item.

image

 

From here now you just need to check the box next to Internet Information Services and then click OK. Windows will do some background processing and the complete the installation.

image

 

After just a few short moments Windows will have completed installing IIS 8 for you. You will be notified once the installation is complete.

image

 

Now you are ready to start using IIS 8 on Windows 8. As shown above just right-click on the background and go to All Apps. From here you’ll see the familiar icon for IIS. Click it and launch IIS.

image

 

Here is the IIS Manager that we all know and love. Since we’re not running this on Windows Server 2012 we don’t have all the familiar icons but you can get the feel of things right from your PC.

image

To look at the new CPU throttling feature I mentioned above just open the Advanced properties of application pool and scroll down to CPU. You’ll see a property for CPU Limit.

image

I’ve shown you how easy it is to install IIS 8 on Windows 8. I hope this simple walk-through helps you get started on the road to discovering the many great new features of IIS 8.

Nov 102012
 

The other day I was checking the traffic stats for my WordPress blog to see which of my posts were the most popular. I was a little concerned to see that wp-login.php was in the Top 5 total requests almost every month.  Since I’m the only author on my blog my logins could not possibly account for the traffic hitting that page.

image

The only explanation could be that the additional traffic was coming from automated hacking attempts. Any server administrator concerned about security knows that “footprinting” is one of the first things a hacker will do when checking for vulnerable sites. I checked a few of my non-wordpress sites and sure enough every couple of days page requests were coming in for wp-login.php and urls for other CMS products such as Plesk’s Cpanel.

Using log parser I wanted to see how many IPs were hitting my login page during a particular month. I like to keep my complex queries in a separate query file and then output the results to a text file. In a previous post I showed how you can leverage this technique to automate log parser to run multiple queries at once. Here’s the query I used to check every log file for my site in the month of October. So this query outputs a simple text file clearly showing thousands of requests to wp-login.php from across the internet during the month of October.

logparser.exe file:wplogin.sql?destination=wpadmin.txt -o:NAT

Here is the SQL query contained in wplogin.sql. I am using a couple of advanced techniques such as searching in multiple log files and filtering the dates to get a results for one month:

SELECT c-ip, COUNT(*) AS TotalHits
FROM ./log/u_ex*.log  TO %destination%
where (EXTRACT_FILENAME(cs-uri-stem) = 'wp-login.php'
and TO_STRING(To_timestamp(date, time), 'MM')='10'
GROUP BY c-ip
ORDER BY TotalHits DESC

Having always followed best practices for hosting sites I was confident that my sites were not vulnerable to these automated probes but it was still a bit irksome to know they were occurring. And there’s always the possibility of some zero-day exploit showing up so I decided the simplest thing do was to block them. IIS now has a great new module available for Dynamic IP Restrictions however that would only block the requests once a threshold was reached. I needed something more “nuclear”. I wanted a means to block everyone hitting that page except for me and the help of the IIS Url Rewrite module a simple rewrite rule was going to do the trick.

In another previous post I showed how easy it was to use Url Rewrite for SEO and security. Now you can see how to tighten security even more by aborting requests based on almost any criteria. In my particular case I wanted to abort requests to wp-login.php from any IP address except for my own IP. So the next logical question is “what’s my ip address?” There are several sites online which can offer you this information. Probably the easiest to remember is whatsmyip.org. When you visit that site, your public IP address is displayed very clearly at the top of the page. This is the IP that you want to put in the rule below. It is important to note the use of “negate=true”. This means all IPs except for the one referenced. The next logical question is what if I need to login to WordPress from more than 1 IP address such as from home and at the office? This is a simple matter of just adding an additional condition to the rule below.

<rewrite>
      <rules>   
    <rule name="Block wp login" stopprocessing="true">
          <match url="(^wp-login.php)" ignorecase="true" />
          <conditions>
            <add negate="true" pattern="10\.10\.10\.10" input="{REMOTE_ADDR}" />
          </conditions>
          <action type="AbortRequest" />
        </rule>
      </rules>
<rewrite>

So in summary Log Parser makes it very easy to get quick extracts of data from your web site’s logs and IIS 7’s Url Rewrite module not only offers powerful rewriting and redirecting of urls but also an easy way to tighten the security of your site. Thanks for reading.

Nov 062012
 

Microsoft’s SQL Server Express is a fantastic product for anyone needing a relational database on a limited budget. By limited budget I’m talking free. Yes SQL Server Express is free but it comes with a few limitations such as only utilizing 1 GB of RAM,  databases are limited to 10 GB, and it does not include SQL Profiler. For low volume sites that do not need enterprise level capabilities, this is a compelling solution. Here is a complete SQL Server feature comparison of all the SQL Server editions.

There is one other important limitation that needs to be mentioned which is that SQL Server Express does not include SQL Agent. This means that you can not schedule administrative tasks such as backing up your databases.  As everyone knows backing up data is critical and with SQL Server Express you can still backup your databases but you have to do it manually. So what does one do if you don’t have a budget to license SQL Server  but you need scheduled backups of your databases? Thanks to the folks at lazycoding.com there is a solution and it’s called SQL Scheduler.

SQL Scheduler is a simple lightweight application that installs on your server and runs as a service. Using the application’s GUI you can create multiple jobs to run your backups on a predefined schedule and you can even configure it to send you an email notification if it completes or fails to run properly.

After you download the program, unzip the archive and run InstallService.bat file from the command prompt. The installation will complete quickly.

image

Once you launch the program you just need to connect to your local SQL Server Express instance on your server. Here is how it will appear without any jobs configured.

image

From the File menu create a new job. In this example we’ll create 1 job to take a full backup of each database that is configured on the server.

image

Click on the Details tab and you’ll be able to enter your SQL statements for whatever task you’re trying to accomplish. Here is an example backup script you can use to run a full backup of each database on your server. Be sure to edit the script and change the path of where you want the database backups stored on your server.

image

On the schedule tab you can define the time and date of your job will run.

image

To have the job send you an email upon completion or in the event of a failure open the SQLScheduler.WindowsService.exe.config file and enter the mail server address along with the and username and password for authentication.

<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from=”somone@somewhere.com”>
<network host="locahost" userName="x" password="x” />
</smtp>
</mailSettings>
</system.net>

 

Once the job runs a full backup will be created for each database and it will be stored in a subfolder of the path you specified in the script.
Now that your daily full backups are being created locally on the server the next step would be to either configure Windows Server Backup or configure 3rd party online backup solution.

As stated in the beginning this only makes sense if you have a limited budget otherwise you should license either SQL Server Standard Edition or SQL Server Web Edition. SQL Express is an ideal product for Cloud Server hosting. If you need Windows Cloud Server hosting take a look at Orcsweb.com. I know them well and I happen to work there.

Oct 042012
 

If you’re getting started with Windows web development or you just need a lightweight web development tool then check out Microsoft’s WebMatrix 2. Creating, deploying, and maintaining, web sites has never been easier and considering it’s free you can’t beat it. What I like about WebMatrix is that it allows you to install 3rd party products such as blogs or forums from the App Gallery. 

I needed to create a new WordPress blog so that I could test a few things without impacting my production site so I decided to try out WebMatrix.  I was really impressed with how easy the whole process was.  I had a test VM on my PC running Windows 7 Home Edition so my first step was to download and install WebMatrix 2.

image
After completing the install you’ll see the Quick Start menu. I clicked on the App Gallery and picked WordPress.

image

I used the default site name of “WordPress” and clicked Next.

image
This is a really nice feature. The installation detects that I do not have MySQL installed on my Windows 7 VM so it will be installed for my automatically. All I have to do is enter the “root” username and password that I want to use and click next.

image

I was prompted to accept the End User License Agreement so naturally I clicked “I Accept”. It won’t install without it so you have to agree to it.

 

image

After a few moments I was presented with a status update showing everything that was installed on my PC during the installation.

image

So now the installation is done. All that remains is to configure WordPress. This is a really simple step. I just had to enter the site title, the admin username and password, and and email address. I then clicked “Install WordPress”.

image
Now the installation has completed and I can login to WordPress. That’s it. WordPress has been installed locally on my PC. I can start installing new plugins or themes and creating posts.

image

 As I mentioned earlier I was installing this locally on a test VM so its not live yet on a production web server.  However if I wanted to publish this to a 3rd-party server then Webmatrix can handle that for me as well. From the Home Tab I just click on the “Publish” icon.

image

Click on Edit Settings and just enter the Web Deploy settings you need to use for your hosting provider. If you need discount asp.net hosting then look no further than Cytanium.com. I know them personally and have hosted site’s there. They do a great job.

image

WebMatrix is a great product and is easy to use. Using WebMatrix to install and configure a WordPress blog could not have been easier or more straight forward. The entire process from start to finish took about 7 minutes.

Sep 302012
 
Email is everywhere. You may not know immediately if your web site is down but you’ll almost always know if your email isn’t working.  The ability to send and receive email 24×7 is critical to the success of any business. This means you need a product which is reliable, scalable, and affordable. There are not many mail server products on the market which meet that criteria. However, Smartermail by SmarterTools.com is one such product. Year after year Smartertools has evolved with more features and better security. The latest version of Smartermail is their best product to date.
Smartermail 10 GUI
However, they inadvertently introduced a small design flaw in the administration GUI. Finding disabled domains is a real pain. If your Smartermail deployment only has 5-10 domains then you probably haven’t even noticed this. However if your organization relies on Smartermail to host hundreds or even thousands of mail domains then you are already well aware of this design oversight.  Of course one can simply scroll through the domain list looking for Disabled status which is clearly marked in red however this is a daunting task for large deployments. Curiously in legacy versions of Smartermail you could easily sort your entire domain list by enabled or disabled status.

Because Smartermail stores it’s domains in a logical fashion, it is easy to programmatically access the config files and determine whether or not a domain is enabled. For example C:\Smartermail\Domains would contain all the domains of your Smartermail instance.  Each mail domain will be stored as subdirectory of this directory and the individual domain settings will be stored in file called domainconfig.xml. Contained in this file is a node called “isEnabled”.  As one might expect if the domain is enabled the value will be True whereas if the domain is disabled then the value will be False. Here is a a snippet of what it looks like.


So here’s where a bit of programming saves the day. Using C# and ASP.NET I created a simple console application which will read the Smartermail domains folder,  check the domainconfig.xml of each domain on the server, and then output the results to a log file. One complication with this is that Smartermail may not have been installed in the default location so I am using a simple xml config file for my program which specifies the path to the domains folder along with the path where I want the log file to saved.

<?xml version="1.0" encoding="utf-8"?>
<MyConfig>
  <DomainsPath>H:\Smartermail\Domains</DomainsPath>
  <LogPath>H:\Temp\disabled_log.txt</LogPath>
</MyConfig>
Here’s how my program looks:
namespace checkDisabled
{
    class Program
    {
        public static string strLogPath;
        public static string strDomainsPath;
                
        static void Main(string[] args)
        {
            string path = System.IO.Path.GetFullPath(@"checkDisabled.xml");
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path);
            XmlNodeList DomainsPath = xmlDoc.GetElementsByTagName("DomainsPath");
            XmlNodeList LogPath = xmlDoc.GetElementsByTagName("LogPath");

            strDomainsPath = DomainsPath[0].InnerXml;
            strLogPath = LogPath[0].InnerXml;

            checkFolders();
        }

        static private void checkFolders()
     
        static private void checkDisabled(string sDomain, string sPath)
     
        static private void disabledLog(string strLine)
    }
}
I create a subroutine called “checkFolders” which reads the Smartermail domains folder and then iterates through any subdirectory. To help keep things clean I will use a another subroutine to actually read domainconfig.xml file.
static private void checkFolders()
{
    string[] folders = System.IO.Directory.GetDirectories(strDomainsPath);
    string strDomainName = "";
    string strConfigFile = "";

    Console.WriteLine("Checking " + strDomainsPath + " for disabled domains.");

    foreach (string sDir in folders)
    {
        strConfigFile = sDir + @"\domainConfig.xml";
        strDomainName = sDir.Substring(strDomainsPath.Length + 1);
        if (File.Exists(strConfigFile))
            checkDisabled(strDomainName, strConfigFile);
    }

    Console.WriteLine("Done.");
}
Here is the code I use to read the domainconfig.xml file. If a domain is identified as being disabled then I write a line to the screen as well as the log file.
static private void checkDisabled(string sDomain, string sPath)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(sPath);
    XmlNodeList isEnabled = xmlDoc.GetElementsByTagName("isEnabled");

    if (!Convert.ToBoolean(isEnabled[0].InnerXml))
    {
        Console.WriteLine("Disabled: " + sDomain);
        disabledLog(sDomain);
    }
}
Writing the output to the log file is straight forward. I check if the log file exists and if it doesn’t then just create an empty file.
static private void disabledLog(string strLine)
{
    if (!File.Exists(strLogPath))
        using (StreamWriter sw = File.CreateText(strLogPath))
            sw.WriteLine("");

    using (StreamWriter sw = File.AppendText(strLogPath))
        sw.WriteLine(strLine);
}
Running the program from the command line we see the results.

H:\temp>checkdisabled
Checking H:\Smartermail\domains for disabled domains.
Disabled: domain2.net
Disabled: domain4.com
Done.

H:\temp>


Taking it a step further we could use Windows Task Scheduler run it on a weekly or daily basis and with only a small tweak we could code emailing the log file so that we didn’t even have to login to the server to check the disabled domains.