Today's blog post needs to have a disclaimer right up front - I freely admit I'm not a Mac OS X expert, so I may not have everything 100% correct in this post. But I've seen a lot of questions on forums.iis.net that discuss using IIS WebDAV with Mac OS X, so I thought that I'd share a few of the things that I've noticed. Just the same, if I were writing a formal walkthrough I would have said something like, "Microsoft is not responsible for the behavior of Apple's Mac family of products. The information that is provided in this topic is provided to assist Mac OS X users connect to IIS using WebDAV." 
All that being said, here are the prerequisites for getting your environment together:
- Your server needs to be running Windows Vista, Windows Server 2008, or Windows 7.
- Your server needs to have Internet Information Services 7 and the WebDAV module installed. (Note: See the Installing and Configuring WebDAV on IIS 7.0 topic for more information.)
- For best results, your Mac client needs to be running OS X version 10.4 or later.
Connecting to a WebDAV server using Mac OS X
- In Mac OS X, open Finder.
- Choose Go, then Connect To Server.
- Enter the URL of the WebDAV server in Server Address. For example:
http://www.example.com/path/
- Click Connect.
For more information, please see the following help topics that are available on Apple's Web site:
Troubleshooting WebDAV connections using Mac OS X
These are some of the issues that I've seen:
- WebDavFS connections are read-only if WebDAV LOCKs are disabled on the server. Because of this:
- If you are using WebDAV 7.0 on IIS 7 you will not be able write files to the server; this is because WebDAV locks were not available in this release.
- If you are using WebDAV 7.5 on IIS 7 you will need to enable locks before you can write files to the server; this is because WebDAV locks are disabled by default. (Note: See the How to Use WebDAV Locks topic for more information.)
- WebDavFS connections attempt to create files that may be blocked by IIS:
Allowing unknown MIME types for WebDAV requests should allow these file types, and that setting is located under Web Settings action for the WebDAV Authoring Rules feature of IIS Manager.

For more information, see the following topics that are available on Apple's Web site:
In Closing...
I have to reiterate that I'm not a Mac OS X expert, so this list is probably not all-inclusive, but it's helped to resolve some of the issues that I've seen.
One of the great features that we added to our W3C logging enhancements in FTP 7.0 and FTP 7.5 is the ability to track unique sessions, which are represented by GUIDs in a field that is named x-session. Because of this addition, you can do some interesting things with LogParser when analyzing your FTP logs.
The purpose of today's blog is to show a couple of the scripts that I use to analyze some of the session-based information that I'm interested in from time to time.
Using LogParser to Count FTP Sessions
Since the new FTP service tracks unique sessions, it is now possible to generate reports that show the number of unique FTP sessions you served by day. The following batch file accomplishes this in two parts: first it creates a temporary tab-separated-value file that contains the unique sessions by day, then it calculates the number of sessions by day and writes the totals to a tab-separated-value file that is named Sessions.tsv, which you can open using an application like Microsoft Excel.
@echo off
set LOGPATTERN=u_ex*.log
logparser.exe "SELECT DISTINCT date,x-session INTO '%~n0.tmp' from %LOGPATTERN%" -i:w3c -o:tsv -headers:ON
if exist "%~n0.tmp" (
logparser.exe "SELECT date,COUNT(x-session) AS sessions INTO sessions.tsv FROM '%~n0.tmp' GROUP BY date" -i:tsv -o:tsv -headers:ON
del "%~n0.tmp"
)
set LOGPATTERN=
Using LogParser to Split FTP Log Files into Unique Session Activity Logs
I use the following script when I am testing various FTP scenarios that will split my FTP log files into individual log files that are named after the GUID for each session. (Note: Please bear in mind, this may generate a lot of log files, so use it sparingly!) You can then analyze the resulting log files to see the list of client activity that was unique to each session.
This script accomplishes its objective in two parts: first it creates a temporary tab-separated-value file with the list of unique session IDs, then it loops through each session ID and creates a W3C log file for each session's activity.
@echo off
set LOGPATTERN=u_ex*.log
logparser.exe "select distinct x-session into '%~n0.tmp' from '%LOGPATTERN%'" -i:w3c -o:tsv -headers:off
if exist "%~n0.tmp" (
for /f "delims=|" %%a in (%~n0.tmp) do (
logparser.exe "select date,time,c-ip,cs-username,s-ip,s-port,cs-method,cs-uri-stem,sc-status,sc-win32-status,sc-substatus,x-session,x-fullpath into '%%a.log' from '%LOGPATTERN%' where x-session='%%a' order by date,time" -i:w3c -o:w3c
)
del "%~n0.tmp"
)
set LOGPATTERN=
That about does it for today - I hope this helps!
For this installment in my series about FTP Clients, I'd like to take a look at the Core FTP client. For this blog post I used Core FTP Lite Edition (LE) version 1.3c (build 1447) and version 2.1 (build 1603), although all of my screen shots are from version 2.1. Core FTP is available from the following URL:
http://www.coreftp.com/
At the time of this blog post, Core FTP provides the LE for free and charges a small fee for a professional version.
Like most graphical FTP clients, the Core FTP LE user interface is pretty easy to use and rather straight-forward - you have separate windows for your local and remote files/folders, as well as a logging window that lists the FTP commands that are sent and the FTP server's responses:

Core FTP LE has a great Site Manager feature, which allows you to store commonly-used connections to FTP sites:

Clicking on the Advanced button gives you a great deal of additional configuration settings, and I'll say more about that later:

Command-Line Support
This is one of my favorite Core FTP LE features: command-line support. Yes - I'm a geek - and I like being able to script things and run batch jobs to automate whatever I can, so command-line support is always a plus for me. That said, the interface for the Core FTP LE command-line client is not an interactive experience like you get with the built-in Windows FTP.EXE or MOVEit Freely command-line clients. The Core FTP LE command-line client is provided as via the Corecmd.exe file that is installed in the main the Core FTP LE application directory, and is used for a single FTP operation like GET or PUT - although you can pass the name of a script file to execute several commands before/after logging in or before/after a file transfer.
So my final judgment is that the Core FTP LE client doesn't have great command-line support, but it's still really nice to have.
Using FTP over SSL (FTPS)
The Core FTP LE client supports both Implicit and Explicit FTPS, so the choice is up to you which method to use. When creating a connection to a server, Core FTP LE has three FTP options that you can use with FTP7:
- AUTH SSL
- AUTH TLS
- FTPS (SSL DIRECT)
It's important to choose this option correctly, otherwise you will run into problems when trying access a site using FTPS. If you'll recall from my "FTP Clients - Part 2: Explicit FTPS versus Implicit FTPS" and my other FTP client blog posts, Explicit FTPS allows the client to initiate SSL/TLS whenever it wants, but for most FTP clients that will be when logging in to your FTP site, and in that regard it may almost seem like Implicit FTPS, but behind the scenes the FTP client and server are communicating differently.
In the case of FTP7, the following rules apply:
- If you enable FTPS in FTP7 and you assign the FTP site to port 990, you are using Implicit FTPS - Core FTP LE refers to this as FTPS (SSL DIRECT). (Note: make sure that you configure your FTP client to connect on port 990.)
- If you enable FTPS in FTP7 and you assign the FTP site to any port other than port 990, you are using Explicit FTPS - Core FTP LE allows you to configure your connection to use AUTH SSL or AUTH TLS for the explicit connection.
The type of FTPS is specified on the Connection drop-down menu:

Once you have chosen an FTPS connection, the Core FTP LE client offers you additional options where you can customize which parts of the session will be encrypted:

You can combine the Core FTP SSL options with the advanced SSL policies for your FTP7 sites to customize your security level:

Using FTP Virtual Hosts
Because Core FTP LE's site manager allows you to specify the virtual host name as part of the user credentials, Core FTP LE works great with FTP7's virtual host names. All that you need to do is use the "ftp.example.com|username" syntax when specifying your username, and when you connect to the FTP7 server it will route your requests to the correct FTP virtual host site.

Using True FTP Hosts
A really great feature of Core FTP LE is the ability to send pre-login commands, and since this feature allows you to enter custom commands you can specify the actual FTP HOST command as part of your login:

This is a tremendous feature if you're hosting multiple FTP sites on the same IP address, and gives Core FTP LE some of the best support for true FTP HOSTs.
Scorecard for Core FTP LE
That wraps it up for our quick round-trip for some of Core FTP LE's features, and here's the scorecard results:
| Client Name |
Directory Browsing |
Explicit FTPS |
Implicit FTPS |
Virtual Hosts |
True HOSTs |
| Core FTP LE 1.3 |
Rich |
Y |
Y |
Y |
Y 1 |
| Core FTP LE 2.1 |
Rich |
Y |
Y |
Y |
Y 1 |
| 1 As noted earlier, true FTP HOSTs are available in Site Manager using pre-login commands. |
Note: Keeping with my standard disclaimer, there are a great number of additional features that Core FTP LE provides - and I just focused on the topic areas that apply to FTP7.
As I pointed out in my recent blog post that was titled "FTP 7.5 and WebDAV 7.5 have been released", one of the great new features of the FTP 7.5 service is extensibility. In that blog post I mentioned that I wrote the following walkthroughs to help developers get started writing providers for the FTP 7.5 service, and these walkthroughs are all available on Microsoft's learn.iis.net Web site:
- For Managed Code Developers:
- For Native Code Developers:
We have also recently published the FTP Service Extensibility Reference on Microsoft's MSDN Web site, and here is a list of all the reference topics that we have written for FTP 7.5 service extensibility:
I hope this helps!
I recently posted a blog that was titled Creating a Read-Only Snitz Membership Provider, where I re-used the code from my How to use the Sample Read-Only XML Membership and Role Providers with IIS 7.0 walkthrough on the learn.iis.net web site to write a membership provider for web sites that use the Snitz Forums application. After I finished writing that blog post, I started thinking about the web sites where I use the phpBB 2.0 application, which leads us to today's blog post. 
Following in the footsteps of my Snitz blog and XML walkthrough, today's blog post will show how to set up a simple, read-only provider for phpBB 2.0, although for this blog I tested a web site that was specifically using the phpBB 2.0.22 version. (Before anyone sends me email about it - I know that phpBB 3.0 is has been released and it's way cooler, but I still have web sites that are running the 2.0 phpBB forums.)
As I did with the Snitz provider, I chose to create a single namespace ("ReadOnlyPhpBBProvider") that contained two classes: one for the membership provider ("PhpBBMembershipProvider") and the other for the role provider ("PhpBBRoleProvider"); and once again I added an additional class ("PhpBBUtils") with a couple of helper methods.
Here are some of the additional implementation details:
- Unlike the Snitz forums, the phpBB forums have groups, so I used those for my roles implementation.
- My SQL queries are hard-coded to use the default "phpbb_" prefix; this could easily be modified.
- I use the "user_regdate" and "user_session_time" fields in the "phpp_users" table to populate the membership CreationDate, LastLoginDate, and LastActivityDate values. It would be possible to retrieve the last post for a user from the phpbb_posts table and compute the LastActivityDate, but I'm not really using that value so I chose to avoid the hassle.
Step 1: Creating the Project
In this section you will create a project in Visual Studio for the membership/role provider.
- Open Microsoft Visual Studio 2008.
- Click the File menu, then New, then Project.
- In the New Project dialog:
- Choose Visual C# as the project type.
- Choose Class Library as the template.
- Type ReadOnlyPhpBBProvider as the name of the project.
- Uncheck the Create directory for solution box.
- Click OK.
- Add a reference path to the System.Configuration library:
- In the solution explorer, right-click the ReadOnlyPhpBBProvider project, then Add Reference...
- Click the .NET tab.
- Select "System.Configuration" in the list of assemblies.
- Click OK.
- Add a reference path to the System.Web library:
- In the solution explorer, right-click the ReadOnlyPhpBBProvider project, then Add Reference...
- Click the .NET tab.
- Select "System.Web" in the list of assemblies.
- Click OK.
- Add a strong name key to the project:
- In the solution explorer, right-click the ReadOnlyPhpBBProvider project, then Properties.
- Click the Signing tab.
- Check the Sign the assembly check box.
- Choose <New...> from the strong key name drop-down box.
- Enter ReadOnlyPhpBBProviderKey for the key file name.
- If desired, enter a password for the key file; otherwise, uncheck the Protect my key file with a password box.
- Click OK.
- (Optional) Add a custom build event to automatically register the DLL in the GAC:
- In the solution explorer, right-click the ReadOnlyPhpBBProvider project, then Properties.
- Click the Build Events tab.
- Enter the following in the Post-build event command line box:
call "%VS90COMNTOOLS%\vsvars32.bat">null
gacutil.exe /if "$(TargetPath)"
- Save the solution.
Step 2: Add the provider classes for the project
In this second step you will create the classes for the membership and role providers. Once again, the code for these classes is largely based on the Membership Providers and Role Providers topics on MSDN.
- Open the Class1.cs file if it is not already open.
- Remove all of the existing code from the class.
- Paste the following sample code into the editor:
/* ======================================== */
//
// ReadOnlyPhpBBProvider
//
// A read-only membership and role provider for phpBB forums.
//
/* ======================================== */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Data.Odbc;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
namespace ReadOnlyPhpBBProvider
{
/* ======================================== */
//
// PhpBBMembershipProvider
//
/* ======================================== */
public class PhpBBMembershipProvider : MembershipProvider
{
private Dictionary<string, MembershipUser> _Users;
private string _connectionStringName;
private string _connectionString;
private PhpBBUtils _phpbbUtils;
/* ---------------------------------------- */
// MembershipProvider Properties
/* ---------------------------------------- */
public override string ApplicationName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override bool EnablePasswordRetrieval
{
get { return false; }
}
/* ---------------------------------------- */
public override bool EnablePasswordReset
{
get { return false; }
}
/* ---------------------------------------- */
public override int MaxInvalidPasswordAttempts
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override int MinRequiredPasswordLength
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override int PasswordAttemptWindow
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override string PasswordStrengthRegularExpression
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override bool RequiresQuestionAndAnswer
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override bool RequiresUniqueEmail
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
// MembershipProvider Methods
/* ---------------------------------------- */
public override void Initialize(
string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (String.IsNullOrEmpty(name))
name = "ReadOnlyPhpBBMembershipProvider";
if (string.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Read-only phpBB membership provider");
}
base.Initialize(name, config);
_connectionStringName = config["connectionStringName"];
if (String.IsNullOrEmpty(_connectionStringName))
{
throw new ProviderException("No connection string was specified.\n");
}
_connectionString = ConfigurationManager.ConnectionStrings[
_connectionStringName].ConnectionString;
_phpbbUtils = new PhpBBUtils();
}
/* ---------------------------------------- */
public override bool ValidateUser(
string username, string password)
{
if (String.IsNullOrEmpty(username) ||
String.IsNullOrEmpty(password))
return false;
try
{
ReadMembershipDataStore();
MembershipUser user;
if (_Users.TryGetValue(username, out user))
{
if ((user.Comment == _phpbbUtils.PasswordHash(password))
&& (user.IsLockedOut == false)
&& (user.IsApproved == true))
{
return true;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
/* ---------------------------------------- */
public override MembershipUser GetUser(
string username, bool userIsOnline)
{
if (String.IsNullOrEmpty(username)) return null;
ReadMembershipDataStore();
try
{
MembershipUser user;
if (_Users.TryGetValue(username, out user)) return user;
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
return null;
}
/* ---------------------------------------- */
public override MembershipUserCollection GetAllUsers(
int pageIndex, int pageSize, out int totalRecords)
{
ReadMembershipDataStore();
MembershipUserCollection users = new MembershipUserCollection();
if ((pageIndex >= 0) && (pageSize >= 1))
{
try
{
foreach (KeyValuePair<string, MembershipUser> pair
in _Users.Skip(pageIndex * pageSize).Take(pageSize))
{
users.Add(pair.Value);
}
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
totalRecords = _Users.Count;
return users;
}
/* ---------------------------------------- */
public override int GetNumberOfUsersOnline()
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool ChangePassword(
string username, string oldPassword, string newPassword)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool ChangePasswordQuestionAndAnswer(
string username, string password,
string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUser CreateUser(
string username, string password, string email,
string passwordQuestion, string passwordAnswer,
bool isApproved, object providerUserKey,
out MembershipCreateStatus status)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool DeleteUser(
string username, bool deleteAllRelatedData)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUserCollection FindUsersByEmail(
string emailToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUserCollection FindUsersByName(
string usernameToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string GetPassword(
string username, string answer)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUser GetUser(
object providerUserKey, bool userIsOnline)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string GetUserNameByEmail(string email)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string ResetPassword(
string username, string answer)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool UnlockUser(string userName)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override void UpdateUser(MembershipUser user)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
// MembershipProvider helper method
/* ---------------------------------------- */
public void ReadMembershipDataStore()
{
lock (this)
{
if (_Users == null)
{
try
{
_Users = new Dictionary<string, MembershipUser>(
16, StringComparer.InvariantCultureIgnoreCase);
string queryString = "SELECT * FROM phpbb_users WHERE [user_id]>0";
using (OdbcConnection connection =
new OdbcConnection(_connectionString))
{
OdbcCommand command =
new OdbcCommand(queryString, connection);
connection.Open();
OdbcDataReader reader =
command.ExecuteReader();
while (reader.Read())
{
string sUserName = reader["username"].ToString();
string sEmail = reader["user_email"].ToString();
string sPassword = reader["user_password"].ToString();
DateTime dCreationDate =
_phpbbUtils.ConvertDate(reader["user_regdate"].ToString());
DateTime dLastLoginDate =
_phpbbUtils.ConvertDate(reader["user_session_time"].ToString());
if (dLastLoginDate == new DateTime(1970, 1, 1))
{
dLastLoginDate = dCreationDate;
}
DateTime dLastActivityDate =
_phpbbUtils.ConvertDate(reader["user_session_time"].ToString());
if (dLastActivityDate == new DateTime(1970, 1, 1))
{
dLastActivityDate = dLastLoginDate;
}
Int32 status = Convert.ToInt32(reader["user_active"].ToString());
bool approved = (status == 0) ? false : true;
bool locked = (status == 0) ? true : false;
MembershipUser user = new MembershipUser(
Name, // Provider name
sUserName, // UserName
null, // ProviderUserKey
sEmail, // Email
String.Empty, // PasswordQuestion
sPassword, // Comment
approved, // IsApproved
locked, // IsLockedOut
dCreationDate, // CreationDate
dLastLoginDate, // LastLoginDate
dLastActivityDate, // LastActivityDate
dCreationDate, // LastPasswordChangedDate
dCreationDate // LastLockoutDate
);
_Users.Add(user.UserName, user);
}
reader.Close();
}
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
}
}
}
/* ======================================== */
//
// PhpBBRoleProvider
//
/* ======================================== */
public class PhpBBRoleProvider : RoleProvider
{
private string _connectionStringName;
private string _connectionString;
private PhpBBUtils _phpbbUtils;
private Dictionary<string, string[]> _UsersAndRoles =
new Dictionary<string, string[]>(
16, StringComparer.InvariantCultureIgnoreCase);
private Dictionary<string, string[]> _RolesAndUsers =
new Dictionary<string, string[]>(
16, StringComparer.InvariantCultureIgnoreCase);
/* ---------------------------------------- */
// RoleProvider properties
/* ---------------------------------------- */
public override string ApplicationName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
// RoleProvider methods
/* ---------------------------------------- */
public override void Initialize(
string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (String.IsNullOrEmpty(name))
name = "ReadOnlyPhpBBRoleProvider";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Read-only phpBB role provider");
}
base.Initialize(name, config);
_connectionStringName = config["connectionStringName"];
if (String.IsNullOrEmpty(_connectionStringName))
{
throw new ProviderException(
"No connection string was specified.\n");
}
_connectionString = ConfigurationManager.ConnectionStrings
[_connectionStringName].ConnectionString;
_phpbbUtils = new PhpBBUtils();
ReadRoleDataStore();
}
/* ---------------------------------------- */
public override bool IsUserInRole(
string username, string roleName)
{
if (username == null || roleName == null)
throw new ArgumentNullException();
if (username == String.Empty || roleName == String.Empty)
throw new ArgumentException();
if (!_UsersAndRoles.ContainsKey(username))
throw new ProviderException("Invalid user name");
if (!_RolesAndUsers.ContainsKey(roleName))
throw new ProviderException("Invalid role name");
string[] roles = _UsersAndRoles[username];
foreach (string role in roles)
{
if (String.Compare(role, roleName, true) == 0)
return true;
}
return false;
}
/* ---------------------------------------- */
public override string[] GetRolesForUser(string username)
{
if (username == null)
throw new ArgumentNullException();
if (username == String.Empty)
throw new ArgumentException();
string[] roles;
if (!_UsersAndRoles.TryGetValue(username, out roles))
throw new ProviderException("Invalid user name");
return roles;
}
/* ---------------------------------------- */
public override string[] GetUsersInRole(string roleName)
{
if (roleName == null)
throw new ArgumentNullException();
if (roleName == string.Empty)
throw new ArgumentException();
string[] users;
if (!_RolesAndUsers.TryGetValue(roleName, out users))
throw new ProviderException("Invalid role name");
return users;
}
/* ---------------------------------------- */
public override string[] GetAllRoles()
{
int i = 0;
string[] roles = new string[_RolesAndUsers.Count];
foreach (KeyValuePair<string, string[]> pair in _RolesAndUsers)
roles[i++] = pair.Key;
return roles;
}
/* ---------------------------------------- */
public override bool RoleExists(string roleName)
{
if (roleName == null)
throw new ArgumentNullException();
if (roleName == String.Empty)
throw new ArgumentException();
return _RolesAndUsers.ContainsKey(roleName);
}
/* ---------------------------------------- */
public override void CreateRole(string roleName)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool DeleteRole(
string roleName, bool throwOnPopulatedRole)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override void AddUsersToRoles(
string[] usernames, string[] roleNames)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string[] FindUsersInRole(
string roleName, string usernameToMatch)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override void RemoveUsersFromRoles(
string[] usernames, string[] roleNames)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
// RoleProvider helper method
/* ---------------------------------------- */
private void ReadRoleDataStore()
{
lock (this)
{
try
{
string userQueryString = "SELECT * FROM phpbb_users WHERE [user_id]>0";
using (OdbcConnection connection =
new OdbcConnection(_connectionString))
{
connection.Open();
OdbcCommand userCommand =
new OdbcCommand(userQueryString, connection);
OdbcDataReader userReader =
userCommand.ExecuteReader();
while (userReader.Read())
{
string user =
userReader["username"].ToString();
string userid =
userReader["user_id"].ToString();
string groupQueryString =
"SELECT phpbb_groups.group_name " +
" FROM phpbb_user_group INNER JOIN phpbb_groups " +
" ON phpbb_user_group.group_id = phpbb_groups.group_id " +
" WHERE (((phpbb_user_group.user_pending)=0) " +
" AND ((phpbb_user_group.user_id)=" + userid + ") " +
" AND ((phpbb_groups.group_single_user)=0));";
OdbcCommand groupCommand =
new OdbcCommand(groupQueryString, connection);
OdbcDataReader groupReader =
groupCommand.ExecuteReader();
if (groupReader.HasRows == false)
{
_UsersAndRoles.Add(user, new string[0]);
}
else
{
ArrayList roleList = new ArrayList();
while (groupReader.Read())
{
roleList.Add(groupReader["group_name"].ToString());
}
string[] roles =
(string[])roleList.ToArray(typeof(string));
_UsersAndRoles.Add(user, roles);
foreach (string role in roles)
{
string[] users1;
if (_RolesAndUsers.TryGetValue(role, out users1))
{
string[] users2 = new string[users1.Length + 1];
users1.CopyTo(users2, 0);
users2[users1.Length] = user;
_RolesAndUsers.Remove(role);
_RolesAndUsers.Add(role, users2);
}
else
_RolesAndUsers.Add(role, new string[] { user });
}
}
groupReader.Close();
}
userReader.Close();
}
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
}
}
/* ======================================== */
//
// PhpBBUtils
//
/* ======================================== */
internal class PhpBBUtils
{
/* ---------------------------------------- */
internal string PasswordHash(string password)
{
try
{
MD5 md5 = MD5.Create();
byte[] byteArray =
md5.ComputeHash(Encoding.ASCII.GetBytes(password));
StringBuilder stringBuilder =
new StringBuilder(byteArray.Length * 2);
foreach (byte byteMember in byteArray)
{
stringBuilder.AppendFormat("{0:x2}", byteMember);
}
return stringBuilder.ToString();
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
/* ---------------------------------------- */
internal DateTime ConvertDate(string offset)
{
DateTime dateTime = new DateTime(1970, 1, 1);
if (!(String.IsNullOrEmpty(offset)))
{
try
{
dateTime = dateTime.AddSeconds(Convert.ToDouble(offset));
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
return dateTime;
}
}
}
- Save and compile the project.
Step 3: Add the provider to IIS
In this third step you will determine the assembly information for the membership and role provider, and then add that information to the list of trusted providers for IIS.
- Determine the assembly information for the provider:
- In Windows Explorer, open your "%WinDir%\assembly" path.
- Right-click the ReadOnlyPhpBBProvider assembly and click Properties.
- Copy the Culture value; for example: Neutral.
- Copy the Version number; for example: 1.0.0.0.
- Copy the Public Key Token value; for example: f0e1d2c3b4a59687.
- Click Cancel.
- Add the provider to the list of trusted providers for IIS:
- Open the Administration.config file for editing. (Note: This file is located in your "%WinDir%\System32\Inetsrv\Config" folder.)
- Add the providers with the assembly properties from the previous steps to the <trustedProviders> section using the following syntax:
<add type="ReadOnlyPhpBBProvider.PhpBBMembershipProvider, ReadOnlyPhpBBProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687" />
<add type="ReadOnlyPhpBBProvider.PhpBBRoleProvider, ReadOnlyPhpBBProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687" />
- Save and close the the Administration.config file.
Step 4: Configure your site for Forms Authentication using the phpBB provider
In this fourth step you will configure your Web site to use forms authentication with the membership and role providers by manually creating a Web.config file for your Web site that sets the requisite properties for forms authentication/authorization, and adding a Login.aspx page to the Web site that will process forms authentication requests.
Note: This example will authorize phpBB accounts that are members of the user-created "Members" group.
- Create a Login.aspx file for your Web site:
- Create a Web.config file for your Web site:
- Paste the following code into a text editor:
<configuration>
<!-- Add the connection string for the providers. -->
<connectionStrings>
<add name="PhpBBForums"
connectionString="DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Inetpub\wwwdata\phpbb.mdb" />
</connectionStrings>
<system.web>
<!-- Add the read-only membership provider and set it as the default. -->
<membership defaultProvider="ReadOnlyPhpBBMembershipProvider">
<providers>
<add name="ReadOnlyPhpBBMembershipProvider"
type="ReadOnlyPhpBBProvider.PhpBBMembershipProvider, ReadOnlyPhpBBProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687"
description="Read-only PhpBB membership provider"
connectionStringName="PhpBBForums" />
</providers>
</membership>
<!-- Add the read-only role provider and set it as the default. -->
<roleManager defaultProvider="ReadOnlyPhpBBRoleProvider" enabled="true">
<providers>
<add name="ReadOnlyPhpBBRoleProvider"
type="ReadOnlyPhpBBProvider.PhpBBRoleProvider, ReadOnlyPhpBBProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687"
description="Read-only PhpBB role provider"
connectionStringName="PhpBBForums" />
</providers>
</roleManager>
<!-- Set the authentication mode to forms authentication. -->
<authentication mode="Forms" />
</system.web>
<system.webServer>
<modules>
<!-- Set authentication for the application. -->
<remove name="FormsAuthentication" />
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"
preCondition="" />
<remove name="DefaultAuthentication" />
<add name="DefaultAuthentication"
type="System.Web.Security.DefaultAuthenticationModule"
preCondition="" />
<remove name="RoleManager" />
<add name="RoleManager"
type="System.Web.Security.RoleManagerModule"
preCondition="" />
</modules>
<security>
<!-- Set authorization for the application. -->
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" roles="Members" />
</authorization>
</security>
</system.webServer>
</configuration>
- Note: Make sure that the PublicKeyToken value contains the correct public key token from the assembly properties that you copied in previous steps, and the connectionString value contains the correct information for your phpBB database.
- Save the code as "Web.config" in the root of your Web site.
Additional notes for using the read-only phpBB provider
As mentioned before, all of the user account management features are built-in to the phpBB forums, so I did not add them to my provider. The being said, there are still several features that integrate nicely with IIS. The following screenshot shows the list of users for a phpBB forum in Internet Explorer:

You'll notice that several pieces of information are listed for each user: username, date joined, number of posts, etc. If you open the .NET Users feature for your site, you'll notice that some of the account information is mirrored there, as shown in the following illustration:

Likewise, if you open the .NET Roles feature for your site, you'll notice that the three roles are enumerated and the number of users per role is listed:

As with my Read-Only Snitz Provider, all of the above information in the .NET Users and .NET Roles features is read-only, so any attempt to modify user or role information will return an error that the specified method is not supported:

But unlike my Snitz provider, which is limited to three built-in roles, you can add as many groups as you want to your phpBB forums and use those groups as membership roles.
Summary and parting thoughts
So now you have a simple read-only membership and role provider for the phpBB 2.0 forums. As previously mentioned - this is not a full-featured provider because I only needed it to fulfill a specific need for forms authentication. If you want to be a little adventurous, you could easily expand this provider to:
- Work with the phpBB 3.0 application.
- Perform some of the additional provider tasks like adding and removing users or assigning users to roles.
Have fun. ;-]
In case you haven't already surmised from some of my other blog posts, I've been around IIS for a long time, so it should go without saying that I'm a big fan of IIS.
I remember when we first released IIS 1.0 for Windows NT 3.51 and we were handing out IIS CD-ROMs at trade shows way back in early 1996; everyone kept asking, "What is this for?" (Obviously the Internet was still a new concept to a lot of people back then.) Out of nostalgia, I kept a shrink-wrapped copy of IIS 1.0 for myself, and I think that I have one of the few boxes left. It usually sits in my office next to my IIS 4.0 Limited Edition CD-ROM...
Anyway, over the years the IIS team has printed up an assortment of IIS shirts, and I have been wearing several of these various IIS shirts as I have travelled around the world. Because I have been doing so for some time, I've found myself advertising IIS in some unexpected places. For example, my wife and I were visiting our daughter in Peru this past March, and we took the following photograph of my daughter and me (wearing one of my IIS shirts) at Machu Picchu:
So - you may ask, "What does IIS have to do with one of the newest wonders of the world?" My answer is, "Um... nothing, really." I happened to be wearing my IIS shirt that day, and it made a pretty good photo. (Obviously, it was a bad hair day for me... so I'm blaming the mountain winds. ;-] )
As another example, my son and I took a road trip down the California coast this past summer to visit my brother in San Francisco, and we posed for the following photo before boarding the boat to Alcatraz:
There are other times where I have taken advantage of a situation to deliberately and shamelessly pose for IIS. For example, I was scuba diving in Hawaii a couple of years ago, and I borrowed someone's dive slate to write the following message:

Actually, I tend to wear IIS shirts when I go scuba diving as a matter of habit - it's kind of a good luck charm for me - and this behavior of mine has led to some interesting experiences.
For example, my wife and I were going scuba diving in the Bahamas several years ago, and once again I was wearing one of my IIS t-shirts that day. The dive company had sent a van to our hotel to pick up several divers, and as I climbed aboard one of the other passengers saw my shirt and remarked, "Oh, we have an IIS person today. I'm more of an Apache Girl myself." I quickly replied, "That's okay, everybody needs a hobby." I really only expected her to get the joke, but apparently we had a tech-savvy group that day because everyone else on the bus chimed in with, "Ooooooh - you're in trouble." I didn't realize what everyone meant until we got to the dive boat where Apache Girl came walking up to me holding an air tank and said, "I'm your dive guide today, and I picked this air tank especially for you." We both had a good laugh, and I survived the dive so she can thankfully take a joke.
All that being said, I really like to show off IIS. It's a lot of fun to demonstrate the many features of IIS to customers at trade shows, and it's a lot of fun to unofficially advertise IIS when I'm traveling on vacation in various places around the world. So if you see me when I'm on vacation somewhere, the chances are good that you'll be able to find me in a crowd - because I'll be the geek wearing the IIS shirt.
Over the next few days you're going to hear a lot of details about many of the great new IIS extensions that the IIS feature team is releasing for the 2009 MIX Conference in Las Vegas later today. I don't want to spoil any surprises by talking about anyone else’s feature areas, but I’m about to board a plane to head out on vacation (to Peru!) and I'm not taking a computer with me (believe it or not!) so I thought that I’d take a moment to highlight just a few of the features that are in the FTP 7.5 and WebDAV 7.5 releases.
FTP 7.5
One of the great new features in FTP 7.5 is extensibility. We had some extensibility features that were partially implemented in FTP 7.0, and we used those for the ASP.NET and IIS Manager authentication providers, but FTP extensibility was not officially supported in the 7.0 release. With FTP 7.5 extensibility is fully supported, so you can now write providers that implement custom functionality for authentication/authorization, home directory lookups, and logging.

To help developers get started writing providers for FTP 7.5, I wrote the following walkthroughs that are available on Microsoft's learn.iis.net web site:
- For Managed Code Developers:
- For Native Code Developers:
Another highlight in FTP 7.5 is the addition of a user interface for the FTP Request Filtering features. We shipped request filtering with FTP 7.0 while the request filtering user interface was still in development, and the 7.5 version seemed like a great time to release it.

For those of you that are unfamiliar with FTP request filtering, it allows you to add rules that allow or deny specific file extensions, hidden segments, URL sequences, and even FTP commands.
For more information about the features in the new FTP service, see the following page on the http://www.iis.net/ web site:
http://www.iis.net/extensions/FTP
WebDAV 7.5
One of the big changes in WebDAV 7.5 is the inclusion of WebDAV locks, which are implemented through a simple locking mechanism. Our lock implementation was still in development when we shipped the WebDAV 7.0 release, and this release should help publishing scenarios where WebDAV locks are required.

To help you get started using locks with WebDAV 7.5, I wrote the following walkthrough that is available on Microsoft's learn.iis.net web site:
How to Use WebDAV Locks
For more information about the features in the new WebDAV module, see the following page on the http://www.iis.net/ web site:
http://www.iis.net/extensions/WebDAV
In Closing...
So that about wraps it up for some of the major highlights for FTP and WebDAV; for news about everything else that's coming out for IIS, watch the news items on the http://www.iis.net/ home page!
For this blog post I'm going to take a brief departure from my FTP client series and share some code that I put together recently to help address a situation that presented itself a short time ago.
Problem Description
I keep a web site for my extended family that uses the Snitz Forums for private discussions between family members. Recently one of my relatives scanned several historical photographs of family members from the early 1900s, and I thought that uploading those to the family web site would be a great way to share them with everyone. Of course, I don't want to share those photos with the entire Internet, so I needed to come up with a way to share them with just my family members.
My site has been using the Snitz forums application since the dark ages, (meaning my pre-ASP.NET days), so I already have a list of family members that have active accounts on my site and I didn't want to roll out some new authentication method that would confuse everyone. I could write a photo gallery application of my own that used the Snitz accounts for authentication, but Bill Staples had already written a really cool sample photo gallery application as an HTTP module for IIS 7.0 that I wanted to use, which suggested to me that forms authentication was my best bet for the application. But how could I consume the existing Snitz accounts?
Problem Resolution
The answer was simple - create a membership and role provider using the Snitz database. Since the Snitz forums application already handles all of the user registration and account modification features, I didn't need a full membership provider - I just needed a simple provider that would perform user validation and role lookups.
Provider Design
I had just recently written a walkthrough for the learn.iis.net web site titled How to use the Sample Read-Only XML Membership and Role Providers with IIS 7.0 that describes how to create and use the MSDN sample membership and role providers for IIS 7.0, so I leveraged a great deal of that code design to create my new read-only Snitz membership provider. (You should notice a great deal of intentional similarities in my code.
)
I chose to create a single namespace ("ReadOnlySnitzProvider") that contained two classes: one for the membership provider ("SnitzMembershipProvider") and the other for the role provider ("SnitzRoleProvider"); and I added an additional class ("SnitzUtils") with a couple of helper methods. (I had a few more helper methods at one point, but I trimmed down the code to just these methods. I'll say a little more about that later.)
The Snitz forums user accounts don't really have much of a concept of roles, so my provider only works with three roles: Members, Moderators, and Administrators. These roles are mapped to the corresponding user account levels that exist in Snitz. Several other account properties such as creation date/time, last logged in date/time, lockout status, etc., are all accurately represented by this provider. Note: I only check the FORUM_MEMBERS table, not the FORUM_MEMBERS_PENDING table, so any pending accounts will not show up in the list of users.
Step 1: Creating the Project
In this section you will create a project in Visual Studio for the membership/role provider.
- Open Microsoft Visual Studio 2008.
- Click the File menu, then New, then Project.
- In the New Project dialog:
- Choose Visual C# as the project type.
- Choose Class Library as the template.
- Type ReadOnlySnitzProvider as the name of the project.
- Uncheck the Create directory for solution box.
- Click OK.
- Add a reference path to the System.Configuration library:
- In the solution explorer, right-click the ReadOnlySnitzProvider project, then Add Reference...
- Click the .NET tab.
- Select "System.Configuration" in the list of assemblies.
- Click OK.
- Add a reference path to the System.Web library:
- In the solution explorer, right-click the ReadOnlySnitzProvider project, then Add Reference...
- Click the .NET tab.
- Select "System.Web" in the list of assemblies.
- Click OK.
- Add a strong name key to the project:
- In the solution explorer, right-click the ReadOnlySnitzProvider project, then Properties.
- Click the Signing tab.
- Check the Sign the assembly check box.
- Choose <New...> from the strong key name drop-down box.
- Enter ReadOnlySnitzProviderKey for the key file name.
- If desired, enter a password for the key file; otherwise, uncheck the Protect my key file with a password box.
- Click OK.
- Add a custom build event to automatically register the DLL in the GAC:
- In the solution explorer, right-click the ReadOnlySnitzProvider project, then Properties.
- Click the Build Events tab.
- Enter the following in the Post-build event command line box:
call "%VS90COMNTOOLS%\vsvars32.bat">null
gacutil.exe /if "$(TargetPath)"
- Save the solution.
Step 2: Add the provider classes for the project
In this second step you will create the classes for the membership and role providers. The code for these classes is based on the Membership Providers and Role Providers topics on MSDN.
- Open the Class1.cs file if it is not already open.
- Remove all of the existing code from the class.
- Paste the following sample code into the editor:
/* ======================================== */
//
// ReadOnlySnitzProvider
//
// A read-only membership and role provider for Snitz forums.
//
/* ======================================== */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Data.Odbc;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
namespace ReadOnlySnitzProvider
{
/* ======================================== */
//
// SnitzMembershipProvider
//
/* ======================================== */
public class SnitzMembershipProvider : MembershipProvider
{
private Dictionary<string, MembershipUser> _Users;
private string _connectionStringName;
private string _connectionString;
private SnitzUtils _snitzUtils;
/* ---------------------------------------- */
// MembershipProvider Properties
/* ---------------------------------------- */
public override string ApplicationName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override bool EnablePasswordRetrieval
{
get { return false; }
}
/* ---------------------------------------- */
public override bool EnablePasswordReset
{
get { return false; }
}
/* ---------------------------------------- */
public override int MaxInvalidPasswordAttempts
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override int MinRequiredPasswordLength
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override int PasswordAttemptWindow
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override string PasswordStrengthRegularExpression
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override bool RequiresQuestionAndAnswer
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
public override bool RequiresUniqueEmail
{
get { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
// MembershipProvider Methods
/* ---------------------------------------- */
public override void Initialize(
string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (String.IsNullOrEmpty(name))
name = "ReadOnlySnitzMembershipProvider";
if (string.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Read-only Snitz membership provider");
}
base.Initialize(name, config);
_connectionStringName = config["connectionStringName"];
if (String.IsNullOrEmpty(_connectionStringName))
{
throw new ProviderException("No connection string was specified.\n");
}
_connectionString = ConfigurationManager.ConnectionStrings[
_connectionStringName].ConnectionString;
_snitzUtils = new SnitzUtils();
}
/* ---------------------------------------- */
public override bool ValidateUser(
string username, string password)
{
if (String.IsNullOrEmpty(username) ||
String.IsNullOrEmpty(password))
return false;
try
{
ReadMembershipDataStore();
MembershipUser user;
if (_Users.TryGetValue(username, out user))
{
if ((user.Comment == _snitzUtils.PasswordHash(password))
&& (user.IsLockedOut == false)
&& (user.IsApproved == true))
{
return true;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
/* ---------------------------------------- */
public override MembershipUser GetUser(
string username, bool userIsOnline)
{
if (String.IsNullOrEmpty(username)) return null;
ReadMembershipDataStore();
try
{
MembershipUser user;
if (_Users.TryGetValue(username, out user)) return user;
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
return null;
}
/* ---------------------------------------- */
public override MembershipUserCollection GetAllUsers(
int pageIndex, int pageSize, out int totalRecords)
{
ReadMembershipDataStore();
MembershipUserCollection users = new MembershipUserCollection();
if ((pageIndex >= 0) && (pageSize >= 1))
{
try
{
foreach (KeyValuePair<string, MembershipUser> pair
in _Users.Skip(pageIndex * pageSize).Take(pageSize))
{
users.Add(pair.Value);
}
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
totalRecords = _Users.Count;
return users;
}
/* ---------------------------------------- */
public override int GetNumberOfUsersOnline()
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool ChangePassword(
string username, string oldPassword, string newPassword)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool ChangePasswordQuestionAndAnswer(
string username, string password,
string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUser CreateUser(
string username, string password, string email,
string passwordQuestion, string passwordAnswer,
bool isApproved, object providerUserKey,
out MembershipCreateStatus status)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool DeleteUser(
string username, bool deleteAllRelatedData)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUserCollection FindUsersByEmail(
string emailToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUserCollection FindUsersByName(
string usernameToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string GetPassword(
string username, string answer)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override MembershipUser GetUser(
object providerUserKey, bool userIsOnline)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string GetUserNameByEmail(string email)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string ResetPassword(
string username, string answer)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool UnlockUser(string userName)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override void UpdateUser(MembershipUser user)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
// MembershipProvider helper method
/* ---------------------------------------- */
public void ReadMembershipDataStore()
{
lock (this)
{
if (_Users == null)
{
try
{
_Users = new Dictionary<string, MembershipUser>(
16, StringComparer.InvariantCultureIgnoreCase);
string queryString = "SELECT * FROM FORUM_MEMBERS";
using (OdbcConnection connection =
new OdbcConnection(_connectionString))
{
OdbcCommand command =
new OdbcCommand(queryString, connection);
connection.Open();
OdbcDataReader reader =
command.ExecuteReader();
while (reader.Read())
{
string sUserName = reader["M_NAME"].ToString();
string sEmail = reader["M_EMAIL"].ToString();
string sPassword = reader["M_PASSWORD"].ToString();
DateTime dCreationDate =
_snitzUtils.ConvertDate(reader["M_DATE"].ToString());
DateTime dLastLoginDate =
_snitzUtils.ConvertDate(reader["M_LASTHEREDATE"].ToString());
DateTime dLastActivityDate =
_snitzUtils.ConvertDate(reader["M_LASTPOSTDATE"].ToString());
if (dLastActivityDate == new DateTime(1980, 1, 1))
{
dLastActivityDate = dLastLoginDate;
}
Int32 status = Convert.ToInt32(reader["M_STATUS"].ToString());
bool approved = (status == -1) ? false : true;
bool locked = (status == 0) ? true : false;
MembershipUser user = new MembershipUser(
Name, // Provider name
sUserName, // UserName
null, // ProviderUserKey
sEmail, // Email
String.Empty, // PasswordQuestion
sPassword, // Comment
approved, // IsApproved
locked, // IsLockedOut
dCreationDate, // CreationDate
dLastLoginDate, // LastLoginDate
dLastActivityDate, // LastActivityDate
dCreationDate, // LastPasswordChangedDate
dCreationDate // LastLockoutDate
);
_Users.Add(user.UserName, user);
}
reader.Close();
}
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
}
}
}
/* ======================================== */
//
// SnitzRoleProvider
//
/* ======================================== */
public class SnitzRoleProvider : RoleProvider
{
private string _connectionStringName;
private string _connectionString;
private SnitzUtils _snitzUtils;
private Dictionary<string, string[]> _UsersAndRoles =
new Dictionary<string, string[]>(
16, StringComparer.InvariantCultureIgnoreCase);
private Dictionary<string, string[]> _RolesAndUsers =
new Dictionary<string, string[]>(
16, StringComparer.InvariantCultureIgnoreCase);
/* ---------------------------------------- */
// RoleProvider properties
/* ---------------------------------------- */
public override string ApplicationName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/* ---------------------------------------- */
// RoleProvider methods
/* ---------------------------------------- */
public override void Initialize(
string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (String.IsNullOrEmpty(name))
name = "ReadOnlySnitzRoleProvider";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Read-only Snitz role provider");
}
base.Initialize(name, config);
_connectionStringName = config["connectionStringName"];
if (String.IsNullOrEmpty(_connectionStringName))
{
throw new ProviderException(
"No connection string was specified.\n");
}
_connectionString = ConfigurationManager.ConnectionStrings
[_connectionStringName].ConnectionString;
_snitzUtils = new SnitzUtils();
ReadRoleDataStore();
}
/* ---------------------------------------- */
public override bool IsUserInRole(
string username, string roleName)
{
if (username == null || roleName == null)
throw new ArgumentNullException();
if (username == String.Empty || roleName == String.Empty)
throw new ArgumentException();
if (!_UsersAndRoles.ContainsKey(username))
throw new ProviderException("Invalid user name");
if (!_RolesAndUsers.ContainsKey(roleName))
throw new ProviderException("Invalid role name");
string[] roles = _UsersAndRoles[username];
foreach (string role in roles)
{
if (String.Compare(role, roleName, true) == 0)
return true;
}
return false;
}
/* ---------------------------------------- */
public override string[] GetRolesForUser(string username)
{
if (username == null)
throw new ArgumentNullException();
if (username == String.Empty)
throw new ArgumentException();
string[] roles;
if (!_UsersAndRoles.TryGetValue(username, out roles))
throw new ProviderException("Invalid user name");
return roles;
}
/* ---------------------------------------- */
public override string[] GetUsersInRole(string roleName)
{
if (roleName == null)
throw new ArgumentNullException();
if (roleName == string.Empty)
throw new ArgumentException();
string[] users;
if (!_RolesAndUsers.TryGetValue(roleName, out users))
throw new ProviderException("Invalid role name");
return users;
}
/* ---------------------------------------- */
public override string[] GetAllRoles()
{
int i = 0;
string[] roles = new string[_RolesAndUsers.Count];
foreach (KeyValuePair<string, string[]> pair in _RolesAndUsers)
roles[i++] = pair.Key;
return roles;
}
/* ---------------------------------------- */
public override bool RoleExists(string roleName)
{
if (roleName == null)
throw new ArgumentNullException();
if (roleName == String.Empty)
throw new ArgumentException();
return _RolesAndUsers.ContainsKey(roleName);
}
/* ---------------------------------------- */
public override void CreateRole(string roleName)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override bool DeleteRole(
string roleName, bool throwOnPopulatedRole)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override void AddUsersToRoles(
string[] usernames, string[] roleNames)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override string[] FindUsersInRole(
string roleName, string usernameToMatch)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
public override void RemoveUsersFromRoles(
string[] usernames, string[] roleNames)
{
throw new NotSupportedException();
}
/* ---------------------------------------- */
// RoleProvider helper method
/* ---------------------------------------- */
private void ReadRoleDataStore()
{
lock (this)
{
try
{
string queryString = "SELECT * FROM FORUM_MEMBERS";
using (OdbcConnection connection =
new OdbcConnection(_connectionString))
{
OdbcCommand command =
new OdbcCommand(queryString, connection);
connection.Open();
OdbcDataReader reader =
command.ExecuteReader();
while (reader.Read())
{
string user =
reader["M_NAME"].ToString();
Int32 level =
Convert.ToInt32(reader["M_LEVEL"].ToString());
ArrayList roleList = new ArrayList();
roleList.Add("Members");
if ((level == 2) || (level == 3))
roleList.Add("Moderators");
if (level == 3)
roleList.Add("Administrators");
string[] roles =
(string[])roleList.ToArray(typeof(string));
_UsersAndRoles.Add(user, roles);
foreach (string role in roles)
{
string[] users1;
if (_RolesAndUsers.TryGetValue(role, out users1))
{
string[] users2 = new string[users1.Length + 1];
users1.CopyTo(users2, 0);
users2[users1.Length] = user;
_RolesAndUsers.Remove(role);
_RolesAndUsers.Add(role, users2);
}
else
_RolesAndUsers.Add(role, new string[] { user });
}
}
reader.Close();
}
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
}
}
/* ======================================== */
//
// SnitzUtils
//
/* ======================================== */
internal class SnitzUtils
{
/* ---------------------------------------- */
internal string PasswordHash(string password)
{
try
{
SHA256 sha256 = new SHA256Managed();
byte[] byteArray =
sha256.ComputeHash(Encoding.ASCII.GetBytes(password));
StringBuilder stringBuilder =
new StringBuilder(byteArray.Length * 2);
foreach (byte byteMember in byteArray)
{
stringBuilder.AppendFormat("{0:x2}", byteMember);
}
return stringBuilder.ToString();
}
catch (Exception ex)
{
throw new ProviderException("Error: " + ex.Message);
}
}
/* ---------------------------------------- */
internal DateTime ConvertDate(string snitzDate)
{
DateTime dateTime;
try
{
if (String.IsNullOrEmpty(snitzDate))
{
dateTime = new DateTime(1980, 1, 1);
}
else
{
dateTime = Convert.ToDateTime(
snitzDate.Substring(0, 4) + "/" +
snitzDate.Substring(4, 2) + "/" +
snitzDate.Substring(6, 2) + " " +
snitzDate.Substring(8, 2) + ":" +
snitzDate.Substring(10, 2) + ":" +
snitzDate.Substring(12, 2)
);
}
}
catch
{
dateTime = new DateTime(1980, 1, 1);
}
return dateTime;
}
}
}
- Save and compile the project.
Step 3: Add the provider to IIS
In this third step you will determine the assembly information for the membership and role provider, and then add that information to the list of trusted providers for IIS.
- Determine the assembly information for the provider:
- In Windows Explorer, open your "%WinDir%\assembly" path.
- Right-click the ReadOnlySnitzProvider assembly and click Properties.
- Copy the Culture value; for example: Neutral.
- Copy the Version number; for example: 1.0.0.0.
- Copy the Public Key Token value; for example: f0e1d2c3b4a59687.
- Click Cancel.
- Add the provider to the list of trusted providers for IIS:
- Open the Administration.config file for editing. (Note: This file is located in your "%WinDir%\System32\Inetsrv\Config" folder.)
- Add the providers with the assembly properties from the previous steps to the <trustedProviders> section using the following syntax:
<add type="ReadOnlySnitzProvider.SnitzMembershipProvider, ReadOnlySnitzProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687" />
<add type="ReadOnlySnitzProvider.SnitzRoleProvider, ReadOnlySnitzProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687" />
- Save and close the the Administration.config file.
Step 4: Configure your site for Forms Authentication using the Snitz provider
In this fourth step you will configure your Web site to use forms authentication with the membership and role providers by manually creating a Web.config file for your Web site that sets the requisite properties for forms authentication/authorization, and adding a Login.aspx page to the Web site that will process forms authentication requests. Note: This example will authorize all Snitz accounts through the "Members" role.
- Create a Login.aspx file for your Web site:
- Create a Web.config file for your Web site:
- Paste the following code into a text editor:
<configuration>
<!-- Add the connection string for the providers. -->
<connectionStrings>
<add name="SnitzForums"
connectionString="DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Inetpub\wwwdata\snitz_forums_2000.mdb" />
</connectionStrings>
<system.web>
<!-- Add the read-only membership provider and set it as the default. -->
<membership defaultProvider="ReadOnlySnitzMembershipProvider">
<providers>
<add name="ReadOnlySnitzMembershipProvider"
type="ReadOnlySnitzProvider.SnitzMembershipProvider, ReadOnlySnitzProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687"
description="Read-only Snitz membership provider"
connectionStringName="SnitzForums" />
</providers>
</membership>
<!-- Add the read-only role provider and set it as the default. -->
<roleManager defaultProvider="ReadOnlySnitzRoleProvider" enabled="true">
<providers>
<add name="ReadOnlySnitzRoleProvider"
type="ReadOnlySnitzProvider.SnitzRoleProvider, ReadOnlySnitzProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0e1d2c3b4a59687"
description="Read-only Snitz role provider"
connectionStringName="SnitzForums" />
</providers>
</roleManager>
<!-- Set the authentication mode to forms authentication. -->
<authentication mode="Forms" />
</system.web>
<system.webServer>
<modules>
<!-- Set authentication for the application. -->
<remove name="FormsAuthentication" />
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"
preCondition="" />
<remove name="DefaultAuthentication" />
<add name="DefaultAuthentication"
type="System.Web.Security.DefaultAuthenticationModule"
preCondition="" />
<remove name="RoleManager" />
<add name="RoleManager"
type="System.Web.Security.RoleManagerModule"
preCondition="" />
</modules>
<security>
<!-- Set authorization for the application. -->
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" roles="Members" />
</authorization>
</security>
</system.webServer>
</configuration>
- Note: Make sure that the PublicKeyToken value contains the correct public key token from the assembly properties that you copied in previous steps, and the connectionString value contains the correct information for your Snitz database.
- Save the code as "Web.config" in the root of your Web site.
Additional notes for using the read-only Snitz provider
As mentioned before, all of the user account management features are built-in to the Snitz forums, so I did not add them to my provider. The being said, there are still several features that integrate nicely with IIS. The following screenshot shows the list of users for a Snitz forum in Internet Explorer:

You'll notice that several pieces of information are listed for each user: user name, title (role), account creation date, last visit, lockout status, etc. If you open the .NET Users feature for your site, you'll notice that the account information is mirrored there, as shown in the following illustration:

Likewise, if you open the .NET Roles feature for your site, you'll notice that the three roles are enumerated and the number of users per role is listed:

All of the above information in the .NET Users and .NET Roles features is read-only, so any attempt to modify user or role information will return an error that the specified method is not supported:

That being said, you can use the IIS manager to allow or deny and of the user accounts or Snitz roles using the Authorization Rules feature:

You should recall from earlier that you can use any of the three roles from the provider: Members, Moderators, and Administrators.
Summary and parting thoughts
So there you have it - a simple read-only membership and role provider for the Snitz forums. As previously mentioned - this is not a full-featured provider because I only needed it to fulfill a specific need for forms authentication. I had added more features at one point, and that's why the utility class used to be a little larger, but in the end I decided that it was overkill for my purpose and I deleted some of the original code. If you want to be a little adventurous, you could easily expand this provider to perform some of the additional provider tasks like adding and removing users or assigning users to roles.
I hope this provider helps someone out there, and I had a lot of fun writing it - which is the point of writing code, isn't it? 
For the past several months I have been working with several members of the IIS team on a brand-new configuration reference for IIS 7.0 that describes every configuration setting for IIS in great detail, which is now located at the following URL:
http://www.iis.net/configreference
Each topic focuses on a specific configuration element and contains an overview section that describes the purpose of each configuration element, setup steps when appropriate, "How To" examples using the IIS Manager, and practical examples using IIS configuration settings and code samples. The complete reference contains hundreds of screenshots and thousands of lines of code using AppCmd, C#, VB.NET, JavaScript, and VBScript - all of which should help you understand and use the IIS configuration system to manage your IIS 7.0 Web sites.

My thanks go to:
- Pete Harris for helping to get this reference deployed on IIS.NET
- Bill Staples and Mai-lan Tomsen Bukovec for some great vision-casting and feedback throughout the project
- Alec Rowell for all of the great editing support
- Suditi Lahiri, Lin Liu, and Yanyan Zhang for tech reviewing everything
For this installment in my series about FTP Clients, I'd like to take a look at the MOVEit Freely Command-Line Secure FTP Client ("FTPS.EXE") from Ipswitch. For this blog post I used MOVEit Freely FTP Client version 5.0.0.0, and it is available from the following URL:
http://www.ipswitchft.com/products/moveit/client/freely/
At the time of this blog post, Ipswitch is providing the MOVEit Freely FTP client for free, although you are required to fill out a registration page with a short questionnaire. For more information on the license for the MOVEit Freely command-line FTP client, please see Ipswitch's web site.
If you're like me and you like to script a lot of batch jobs on your servers, the MOVEit Freely command-line FTP client can be quite handy. The command set for the MOVEit Freely FTP client is a greatly-enhanced superset of the commands that are available with the command-line FTP.EXE client that is built-in to Windows, with added features that make additional functionality possible, such as SSL, passive FTP, resumable downloads, etc. There is a manual available with the MOVEit Freely FTP client, and I highly recommend using the manual as a reference when writing automation scripts because there are a lot of options that are available to you.
Active and Passive FTP
One of the great things about the MOVEit Freely command-line FTP client is the ability to use either Passive or Active connections, and you can switch between the two connection types using the "passive" command in the FTP session. This helps immensely when working with firewalls and such. The following example shows what that might look like:
CMD>ftps.exe ftp.example.com
220 Microsoft FTP Service
Connected to ftp.example.com.
User: administrator
331 Password required for administrator.
Password: ********
230 User logged in.
ftp> passive
Passive mode On .
ftp> put foobar.txt
227 Entering Passive Mode (192,168,0,1,224,39).
150 Opening ASCII mode data connection.
226 Transfer complete.
ftp: 8 bytes sent in 0.06Seconds 0.13Kbytes/sec.
ftp> passive
Passive mode Off .
ftp> put foobar.txt
200 PORT command successful.
125 Data connection already open; Transfer starting.
226 Transfer complete.
ftp: 8 bytes sent in 0.01Seconds 0.78Kbytes/sec.
ftp> bye
221 Goodbye.
CMD> |
Using FTP over SSL (FTPS)
The MOVEit Freely command-line FTP client supports both Implicit and Explicit FTPS, so the choice is up to you which one to use, but I generally use Explicit FTPS since Implicit FTPS should be considered obsolete. The SSL mode is specified using the "-e:" parameter on the command-line, and the 5.0.0.0 version of the MOVEit Freely command-line FTP supports the following values for that parameter:
| Parameter |
FTPS Mode |
Description |
| off |
n/a |
Specifies that no encryption will be used on either the control channel or data channel.
Note: This is the default behavior. |
| on |
Explicit |
Specifies that both the control channel and data channel will use encryption over an explicit FTPS connection.
Notes:
- This uses the AUTH TLS, PBSZ 0, and PROT P commands when establishing a connection.
- You can use "prot on" and "prot off" to specify whether encryption will be used. (See Note 1 below.)
|
| on-ccc |
Explicit |
Specifies the control channel will use encryption over an explicit FTPS connection during login, but the control channel will switch to unencrypted after a login has been established. Data channel connections will still be encrypted.
Notes:
- This uses the AUTH TLS, PBSZ 0, and PROT P commands to enable encryption when establishing a connection, then uses the CCC command after the username and password are successfully negotiated. (See Note 2 below.)
- The USER and PASS commands are the only commands that will be encrypted; all other FTP commands are unencrypted.
|
| tls-p |
Explicit |
Specifies that both control and data channel will use encryption over an explicit FTPS connection.
Notes:
- This uses the AUTH TLS and PROT P commands when establishing a connection.
- You can use "prot on" and "prot off" to specify whether encryption will be used. (See Note 3 below.)
|
| tls-c |
Explicit |
Specifies that only the control connection will use encryption over an explicit FTPS connection. Data channel connections will be unencrypted.
Notes:
- This uses only the AUTH TLS to enable encryption when establishing a connection.
- You must manually send a PBSZ command before you can use the "prot on" and "prot off" to specify whether encryption will be used. (See Note 1 and Note 3 below.)
|
| tls-c-ccc |
Explicit |
Specifies that only the control connection will use encryption over an explicit FTPS connection during login, but the control channel will switch to unencrypted after a login has been established. Data connections will be unencrypted.
Notes:
- This uses only the AUTH TLS to enable encryption when establishing a connection, then uses the CCC command after the username and password are successfully negotiated.
- The USER and PASS commands are the only commands that will be encrypted; all other FTP commands are unencrypted.
|
| implicit |
Implicit |
Specifies that both the control channel and data channel will use encryption over an implicit FTPS connection, which can only be on port 990 for the FTP7 service.
Notes:
- The implicit FTPS connection will encrypt both the control channel and data channel without the use of an AUTH command.
- You can use "prot on" and "prot off" to specify whether encryption will be used. (See Note 3 below.)
|
| implicit-ccc |
Implicit |
Specifies that the control channel would use encryption over an implicit FTPS connection during login and switch the control channel to unencrypted after login, but this is not supported in FTP7. The implicit FTPS connection will succeed, but the FTP7 service will return an error when the CCC command is sent. You can ignore the error and continue to use the session.
Notes:
- Implicit FTPS connections require encryption for the command channel. (See Note 4 below.)
- You can use "prot on" and "prot off" to specify whether encryption will be used. (See Note 3 below.)
|
The following notes should be considered:
- Encryption of the data connection can be changed during the session with MOVEit Freely's "prot" command. You can use the "prot on" to specify that data connections will be encrypted, and "prot off" to specify that data connections will be unencrypted; these commands will respectively send the PROT P and PROT C commands over FTP.
- The "on-ccc", "tls-c-ccc", and "implicit-ccc" parameters are useful with firewalls that inspect FTP traffic. Switching the control channel back to unencrypted allows the firewall to inspect and possibly modify the FTP commands. For example, firewalls that are performing Network Address Translation (NAT) may need to modify the PORT and PASV commands.
- "RFC 2228 - FTP Security Extensions" states that FTP clients are required to send an FTP PBSZ command before sending an FTP PROT command, and unfortunately the MOVEit Freely 5.0.0.0 FTP client does not send this command, so you get a "503 Bad sequence of commands" error. You can work around this by issuing a literal command to the server using the FTP client's "quote" command, which appears to work. See the following example for more information. The following example shows what that might look like:
Note: I turned on debugging for this example with the "-d" option so you can see the sequence of commands.
CMD>ftps.exe -e:tls-c -d ftp.example.com
220 Microsoft FTP Service
---> AUTH TLS
234 AUTH command ok. Expecting TLS Negotiation.
Connected to ftp.example.com.
User: administrator
---> USER administrator
331 Password required for administrator.
Password: ********
---> PASS (hidden)
230 User logged in.
---> SYST
215 Windows_NT
ftp> prot on
---> PROT P
503 Bad sequence of commands.
Data connections will still NOT be encrypted
ftp> quot PBSZ 0
---> PBSZ 0
200 PBSZ command successful.
ftp> prot on
---> PROT P
200 PROT command successful.
Data connections will be encrypted
ftp> bye
---> QUIT
221 Goodbye.
CMD> |
- The FTP7 service treats implicit FTPS connections as though the SSL policy for the control is set to "Require".
One last note about FTPS, if you are using a certificate with trust issues, you will see the following prompt displayed:

You can get around this certificate prompt when writing scripts by using the "-z" switch. The following example shows what that might look like:
Note: For this example I bypassed a certificate prompt with the "-z" switch, and I specified passive FTP with the "passive" command.
CMD>ftps.exe -z -e:on ftp.example.com
220 Microsoft FTP Service
234 AUTH command ok. Expecting TLS Negotiation.
Connected to ftp.example.com.
User: administrator
331 Password required for administrator.
Password: ********
230 User logged in.
200 PBSZ command successful.
200 PROT command successful.
215 Windows_NT
ftp> passive
Passive mode On .
ftp> ls -l
227 Entering Passive Mode (192,168,0,1,224,97).
150 Opening ASCII mode data connection.
03-10-08 10:41AM <DIR> App_Data
09-04-08 11:41AM <DIR> aspnet_client
09-04-08 11:41AM <DIR> bin
12-17-02 11:47AM 2360 default.aspx
ftp: 128 bytes received in 0.03Seconds 83.25Kbytes/sec.
226 Transfer complete.
ftp> bye
221 Goodbye.
CMD> |
Using FTP Virtual Hosts
Since everything is happening from a command-line, you can use both FTP7's Virtual Hosts and the actual FTP HOST command. Once again, see my Virtual Hosts and Host Names in FTP7 blog post for more information about FTP Virtual Host Names and FTP True Host Names, and see https://datatracker.ietf.org/drafts/draft-hethmon-mcmurray-ftp-hosts/ for more information about status of the FTP HOST command.
In any event, FTP7 virtual hosts are supported by using the "ftp.example.com|username" syntax when specifying your username, and when you connect to the FTP7 server it will route your requests to the correct FTP virtual host site. The following example shows what that might look like:
CMD>ftps.exe ftp.example.com
220 Microsoft FTP Service
Connected to ftp.example.com.
User: ftp.contoso.com|administrator
331 Password required for ftp.contoso.com|administrator.
Password: ********
230-Directory has 104,857,600 bytes of disk space available.
230 User logged in.
ftp> bye
221 Goodbye.
CMD> |
True FTP hosts can be used by specifying the FTP HOST command before the client sends the USER and PASS credentials. This is accomplished in two parts:
- You need to suppress the automatic username prompt MOVEit client by using the "-n" switch on the command-line.
- You need to specify the host name using the MOVEit client's "quote" command, which allows you to send custom FTP commands. The syntax for this would be "quote HOST ftp.example.com".
The following example shows what that might look like:
CMD>ftps.exe -n ftp.example.com
220 Microsoft FTP Service
Connected to ftp.example.com.
ftp> quote HOST ftp.contoso.com
220 Host accepted.
ftp> USER administrator
331 Password required for administrator.
Password: ********
230-Directory has 104,857,600 bytes of disk space available.
230 User logged in.
ftp> bye
221 Goodbye.
CMD> |
Scorecard for the MOVEit Freely command-line FTP client
This concludes our quick look at some of the features that are available with the MOVEit Freely command-line FTP client, and here's the scorecard results:
Note: Keeping with my standard disclaimer, there are a great number of additional features that the MOVEit Freely command-line FTP client provides - I'm just keeping the focus on those topic areas that apply to FTP7.
For this next installment in my FTP Clients series, I'd like to take a look at the FileZilla FTP client. For this blog post I was using FileZilla version 3.1.6.
There are a lot of places where you can find FileZilla, but the best location is the official FileZilla web site at http://filezilla-project.org/. The FileZilla FTP client is free, so you can't beat the price. ;-]
The user interface is pretty straight-forward: you have separate windows for your local and remote files/folders, as well as a logging window that lists the FTP commands that are sent and the FTP server's responses.

FileZilla has a great Site Manager feature, which allows you to store commonly-used connections to FTP sites.

Using FTP over SSL (FTPS)
When creating a connection to an FTPS server, FileZilla has two options: FTPS and FTPES. It's important to have this option configured correctly, otherwise you will run into problems when trying access a site using FTPS. If you'll recall from my "FTP Clients - Part 2: Explicit FTPS versus Implicit FTPS" blog post, Explicit FTPS allows the client to initiate SSL/TLS whenever it wants, but for most FTP clients that will be when logging in to your FTP site, and in that regard it may almost seem like Implicit FTPS, but behind the scenes the FTP client and server are communicating differently.
In the case of FTP7, the following rules apply:
- If you enable FTPS and you assign the FTP site to port 990, you are using Implicit SSL - FileZilla refers to this as FTPS.
- If you enable FTPS and you assign the FTP site to any port other than port 990, you are using Explicit SSL - FileZilla refers to this as FTPES.

Using FTP Virtual Hosts
Because FileZilla's site manager allows you to specify the virtual host name as part of the user credentials, FileZilla works great with FTP7's virtual host names. All that you need to do is use the "ftp.example.com|username" syntax when specifying your username, and when you connect to the FTP7 server it will route your requests to the correct FTP virtual host site.

Unfortunately, even though FileZilla allows you to send custom commands, you cannot send custom commands outside of an established FTP session, so you can't send the FTP HOST command as part of your login, therefore true FTP hosts are not supported.
Directory Browsing
Using MS-DOS or UNIX directory listings in FTP7 didn't have any impact on whether FileZilla could render directory listings, nor did configuring any of the other options such as four-digit years, etc. When I create FTP connections in FileZilla's site manager it defaults to auto-detecting the FTP server type, which makes the directory browsing behavior transparent to the client. (Behind the scenes FileZilla is sending an FTP SYST command, which allows FileZilla to detect the operating system.)
You can customize the server type in the advanced settings for your FTP connection, so you can match up your FTP7 directory listing options and the server type that FileZilla expects, but personally I have had no problems with auto-detection so I prefer to use that option.
On a side note, if you intentionally misconfigure FileZilla's server type settings, you can cause FileZilla to behave strangely. For example, choosing a VMS server type and configuring FTP7 to use MS-DOS directory listings will not work, but then again - I wouldn't expect that to work. ;-]

Scorecard for FileZilla
So - that concludes our quick round-trip for some of FileZilla's features, and here's the scorecard results:
Note: As with all of the FTP clients in this blog series, there are a great number of additional features that FileZilla provides - I'm just keeping the focus on a few specific topic areas that apply to FTP7.
In my "FTP Clients - Part 1: Web Browser Support" blog post, I mentioned creating a secured Global Listener FTP Site when you're working with FTP virtual hosts, but I didn't really explain what I meant by that or why you would want to do this. With that in mind, today's blog post is to describe how and why you might want to create a Global Listener FTP Site.
To start things off, the concept is really simple - a Global Listener FTP Site is an FTP site with no virtual host binding and anonymous access disabled. It's kind of like having a "Default FTP Site" with restricted access. Here's why this is a good idea when you're working with FTP virtual hosts - some clients default to anonymous, like web browsers, and if anonymous succeeds then the FTP client doesn't have the opportunity to enter the FTP virtual host name, so you can't get to the virtual host site.
To refresh everyone's memory, there are two different methods for binding multiple FTP host names to IP addresses in FTP7:
- FTP Virtual Host Names - This uses the "ftp.example.com|username" syntax as part of the client login in order to route FTP requests to the correct FTP site. This syntax is compatible with FTP almost every FTP clients, and should be thought of as a backwards-compatible method for binding multiple FTP host names to a single IP address.
- FTP True Host Names - This uses the FTP HOST command, which is still only an IETF draft at the moment. In the future this may be the way that FTP clients and servers automatically communicate with each other, like the "Host: www.example.com" header does for HTTP, but that may still have a few years at the very least.
Unless your FTP client allows sending custom FTP commands, you won't be able to use FTP True Host Names, so if you want to host several FTP sites on the same IP address then your only option is to use FTP Virtual Host Names. The trouble is, as I mentioned earlier, that some FTP clients (like web browsers) try to log in using anonymous first. If all of your FTP sites are bound to a virtual host name, the FTP client will get a "550-No such host is known" error from the FTP server, because the anonymous user did not specify a virtual host name as part of the USER command. On some clients you could fix that by specifying "ftp.example.com|anonymous" as your anonymous user name, but in most cases the login attempt will just fail.
If you create an FTP site that has no virtual host name, then the FTP service will have some place to send these default anonymous requests. When this FTP site does not have anonymous access enabled, the client will be prompted for their username, which will allow you to enter the "ftp.example.com|username" syntax to specify the virtual host name.
Please note that creating a Global Listener FTP site is really more of a workaround for the way that some FTP clients behave - it's certainly not required, and it only applies to situations where you are using FTP Virtual Host Names. For example, if you are using user isolation to restrict users to specific paths on a single FTP site, the Global Listener FTP site would be completely unnecessary.
More Information
Note: See my Virtual Hosts and Host Names in FTP7 blog post for more information about FTP Virtual Host Names and FTP True Host Names, and see https://datatracker.ietf.org/drafts/draft-hethmon-mcmurray-ftp-hosts/ for more information about status of the FTP HOST command.
In part 2 of my series on FTP clients, I thought it would be best to have a discussion about the differences between Implicit FTPS and Explicit FTPS. In my recent "FTP Clients - Part 1: Web Browser Support" blog post, I referenced Implicit and Explicit FTPS with a link to my Using FTP Over SSL walkthrough. But it occurred to me that some people may not understand the difference between the two, and my upcoming blog posts are going to build upon that knowledge, so I thought that a quick discussion of these two technologies would be prudent.
FTP over SSL (FTPS)
One of the many limitations of the File Transfer Protocol (FTP) is a general lack of security; e.g. user names and passwords are transmitted in clear text, data is transferred with no encryption, etc. In order to address this situation, FTP over SSL (FTPS) was introduced in Requests for Comments (RFC) article 2228 - FTP Security Extensions, and expanded in RFC 4217 - Securing FTP with TLS to address Transport Layer Security (TLS).
Following up on these RFC articles, the FTP service for Windows Server 2008 added support for FTPS, and the FTP SSL Settings Feature in the IIS Manager allows you to configure your FTPS settings to allow or require SSL, enforce 128-bit SSL, or customize your control/data channel SSL settings.

Explicit FTPS
Explicit FTPS is really what RFCs 2228 and 4217 envisioned; basically the way this works is an FTP client connects over the control/command channel (usually on port 21), and then the client can negotiate SSL for either the command/control channel or the data channel using new FTP commands like AUTH, PROT, CCC, etc.
The FTP service for Windows Server 2008 allows customized settings for both the command/control channel and the data channel through the Advanced SSL Policy dialog:

There are several ways that Explicit FTPS might be implemented depending on your business needs:
| Control Channel |
Data Channel |
Notes |
| Allow |
Allow |
This configuration allows the client to decide whether any part of the FTP session should be encrypted. |
Require only for credentials |
Allow |
This configuration protects your FTP client credentials from electronic eavesdropping, and allows the client to decide whether data transfers should be encrypted. |
Require only for credentials |
Require |
This configuration requires that the client's credentials must be secure, and then allows the client to decide whether FTP commands should be encrypted. However, all data transfers must be encrypted. |
| Require |
Require |
This configuration is the most secure - the client must negotiate SSL using the FTPS-related commands before other FTP commands are allowed, and all data transfers must be encrypted. |
Implicit FTPS
Implicit FTPS takes SSL one step further than simply requiring that SSL-related commands must be sent first like you can with Explicit SSL; with Implicit FTPS, an SSL handshake must be negotiated before any FTP commands can be sent by the client. In addition, even though Explicit FTPS allows the client to arbitrarily decide whether to use SSL, Implicit FTPS requires that the entire FTP session must be encrypted. Basically the way that Implicit FTPS works is that an FTP client connects to the command/control channel, in this case using port 990, and immediately performs an SSL handshake; after SSL has been negotiated, additional FTP commands for the session can be sent by the FTP client.
Using FTPS in FTP service for Windows Server 2008 follows the Internet Assigned Numbers Authority (IANA) specification that the Implicit FTPS command/control channel is on port 990 and the Implicit FTPS data channel is on port 989.
Using FTPS in Windows Server 2008
Here's the way that you specify which type of FTP over SSL (FTPS) that you are using in Windows Server 2008:
- If you enable FTPS and you assign the FTP site to the default port of 21, you are using Explicit SSL.
- If you enable FTPS and you assign the FTP site to port 990, you are using Implicit SSL.
- In point of fact, if you enable FTPS and you assign the FTP site to any port other than port 990, you are always using Explicit SSL.
Note: If you are using FTP on any ports other than the defaults of 21/20 and 990/989, you must make sure that those ports are not already assigned by IANA to another protocol. For more information, see the list of assigned port numbers on IANA's web site.
Parting Thoughts
Choosing whether to use Explicit FTPS over Implicit FTPS is a personal choice, and generally this choice may depend on your business needs or your FTP client. In several FTP clients that I've tested, the FTP client chooses one form of FTPS over another as the default method, and the FTP client may require some manual configuration to use the other.
Shortly after shipping the FTP service for Windows Server 2008 we discovered an issue where the FTP service was not cleaning up Implicit SSL connections properly, and we issued a hotfix rollup package for the FTP service that is discussed in Microsoft Knowledge Base article 955136.
I hope this helps to clear things up a bit. ;-]
Visual Studio 2008 as an XML Editor
Everyone seems to have their own favorite XML editor these days, and there are no shortages of XML editors in the marketplace. The being said, I tend to use Visual Studio 2008 for several reasons, and if you're using Windows notepad or some other editor, here are some of my reasons why you might consider switching:
- I've already bought a copy of Visual Studio for application development, so I don't need to purchase another utility.
- I'm already familiar with the Visual Studio interface and features, so I don't need to learn another user interface.
- Syntactical highlighting - Visual Studio makes it easy to see your XML in a user-friendly set of colors. If you already use Visual Studio for application development, then you're simply sticking to a paradigm that you're already familiar with.
- Auto-completion - as I create XML elements in Visual Studio I get all of the auto-completion features that you'd expect from an XML editor, which speeds up my configuration editing.
- Simple validation - Visual Studio lets me know when elements become mismatched or sections are not closed properly.
But one of my personal favorites is change notifications. These are great, because I do some of my work in ApplicationHost.config directly, while other times I'm using AppCmd.exe or the IIS Manager to update my settings. If I leave Visual Studio open, it detects that the configuration file was changed externally and prompts me to reload.

This feature alone has probably saved me more times that I can imagine. 
The 32-bit Versus 64-bit Problem
All of the above information leads me to an interesting challenge - what do you do if you have Visual Studio 2008 installed on a 64-bit system? Visual Studio is a 32-bit application, and it runs just fine on a 64-bit system, but unfortunately 32-bit applications cannot open files that are kept in 64-bit-only file paths - and that includes ApplicationHost.config.
Here's why this happens - ApplicationHost.config is physically located in the following 64-bit-only path:
%SystemDrive%\Windows\System32\Inetsrv\config
The problem is, 32-bit applications are "magically" redirected by the operating system to the following 32-bit file path:
%SystemDrive%\Windows\SysWOW64\Inetsrv\config
So what happens is that each 32-bit application thinks that it's in the real System32 folder, so when you try to open ApplicationHost.config using File » Open » File... in Visual Studio, you don't see ApplicationHost.config in the Inetsrv folder. If you attempt to outsmart the system by dragging-and-dropping ApplicationHost.config into Visual Studio from Windows Explorer it doesn't work; you don't get any errors, Visual Studio just sits there and stares back at you. 
NTFS Symbolic Links to the Rescue
NTFS has had junction points around for some time now, but NTFS has added symbolic links starting with Windows Vista and Windows Server 2008. These are not Windows shortcuts - symbolic links appear to applications as actual files and folders. The great thing is - you can create a symbolic link from a 32-bit-only path to a 64-bit only-path, which is how you can get around the problem and use Visual Studio to edit ApplicationHost.config directly on a 64-bit system.
The command that makes this possible is MKLINK, and if you enter that command at a command prompt you get the following help information:
CMD>mklink /?
Creates a symbolic link.
MKLINK [[/D] | [/H] | [/J]] Link Target
/D Creates a directory symbolic link. Default is a file
symbolic link.
/H Creates a hard link instead of a symbolic link.
/J Creates a Directory Junction.
Link specifies the new symbolic link name.
Target specifies the path (relative or absolute) that the new link
refers to.
CMD> |
Here's how you use this command on a 64-bit system:
First of all, you need to open a 64-bit command prompt, because the steps won't work from a 32-bit command prompt. An easy way to find out whether you have a 64-bit or 32-bit command prompt is to use the following command:
CMD>set | find "PROCESSOR_ARCHITECTURE" |
If the above command returns "PROCESSOR_ARCHITECTURE=x86", then you're using a 32-bit command prompt and you will need to close the command prompt and open a 64-bit command prompt. If you see something like "PROCESSOR_ARCHITECTURE=AMD64" then you're using a 64-bit command prompt and everything should be fine.
Once you have a 64-bit command prompt, type the following commands:
CMD>cd /d "%SystemDrive%\Windows\SysWOW64\inetsrv"
CMD>move Config Config.OLD
CMD>mklink /d Config "%SystemDrive%\Windows\System32\inetsrv\Config" |
These commands perform the following actions:
- Change the command prompt working directory to the 32-bit folder for IIS.
- Rename the existing (and typically empty) 32-bit IIS configuration folder. (See note below.)
- Create a directory symbolic link that replaces the 32-bit IIS configuration folder and points to the 64-bit IIS configuration folder. (See note below.)
Important Note: Something that you should consider - if your 32-bit IIS configuration folder is not empty, you will need to find out what is in that folder and whether it needs to be copied to the 64-bit folder. For example, the FTP 7 service for IIS 7 adds a schema file to the 32-bit configuration path, but it's just a copy of the file that resides in the 64-bit path, so it does not need to be copied. If an application exists that requires different files for 64-bit and 32-bit operation, then you cannot use this workaround.
Once you have completed the above commands, you can check your directory listing from a 64-bit command prompt to make sure that your symbolic link has been created; you should see something like the following:
CMD>cd /d "%SystemDrive%\Windows\SysWOW64\inetsrv"
CMD>dir /ad
Volume in drive C has no label.
Volume Serial Number is 426F-624D
Directory of C:\Windows\SysWOW64\inetsrv
10/20/2008 03:52 PM <DIR> .
10/20/2008 03:52 PM <DIR> ..
10/20/2008 03:52 PM <SYMLINKD> Config [C:\Windows\System32\inetsrv\Config]
04/18/2008 04:24 PM <DIR> Config.OLD
04/18/2008 02:55 PM <DIR> en
04/18/2008 03:47 PM <DIR> en-US
0 File(s) 0 bytes
6 Dir(s) 51,247,341,568 bytes free
CMD> |
Notice the <SYMLINKD> entry in the directory listing - this shows that a symbolic link was created, and the target path is indicated in the directory listing next to the name of the symbolic link.
You can now open ApplicationHost.config in Visual Studio 2008 on your 64-bit system with no problems, and still have features like change notifications.
Closing Thoughts
If you look at the help output for Mklink, you'll notice that you can also create symbolic links for files, not just directories. This leads to the question: why didn't I just create a file symbolic link for ApplicationHost.config instead of the folder symbolic link for the entire Config directory? 
The answer goes back to one of my favorite features: change notifications, which are implemented at the folder-level, not the file-level. So you can create a file symbolic link for ApplicationHost.config and that will allow you to open the file, but you won't receive any change notifications, so if you update your settings using AppCmd.exe or IIS Manager, Visual Studio will be unaware of any changes and the next time you save ApplicationHost.config from Visual Studio you will overwrite your changes that were made using AppCmd.exe or IIS Manager. Needless to say - this is a bad thing, so you should always use the directory symbolic link.
I had an interesting question from a coworker who was trying to use AppCmd to set the site-level SSL options for an FTP site. This should have been straightforward, and the syntax that he gave me looked correct:
appcmd.exe set config -section:system.applicationHost/sites -[name='Default FTP Site'].ftpServer.security.ssl.controlChannelPolicy:SslAllow /commit:apphost
That being said, whenever he or I ran the command we received the following cryptic error from AppCmd:
Failed to process input: The parameter 'Site'].ftpServer.security.ssl.controlChannelPolicy='SslAllow'' must begin with a / or - (HRESULT=80070057).
The HRESULT=80070057 code can mean either "One or more arguments are invalid" or "The parameter is incorrect", which seemed wrong to me because the arguments looked correct. Based on the error message referring to the word 'Site', I retried the command using the site ID instead of the site name:
appcmd.exe set config -section:system.applicationHost/sites -[id='4'].ftpServer.security.ssl.controlChannelPolicy:SslAllow /commit:apphost
This worked as expected, so I knew that somehow the problem was with the site name.
I searched around and I found a forum post on IIS.NET where Anil Ruia had stated that when the site name has a space in it you should enclose the entire parameter statement in quotes. Armed with that knowledge, I tried the following command:
appcmd.exe set config -section:system.applicationHost/sites "-[name='Default FTP Site'].ftpServer.security.ssl.controlChannelPolicy:SslAllow" /commit:apphost
This fixed the problem and the command worked as I would have originally expected.
By the way, in general you should be able use the following command to get the FTP syntax listing for an area:
appcmd.exe set config -section:system.applicationHost/sites -? | find /i "ftp"
This wouldn't have helped my coworker identify the problem with the "name" parameter, but it would have helped by giving him the syntax for using the "id" parameter.