using System;
using System.Collections.Generic;
namespace S22.Sasl {
///
/// A factory class for producing instances of Sasl mechanisms.
///
internal static class SaslFactory {
///
/// A dictionary of Sasl mechanisms registered with the factory class.
///
static Dictionary Mechanisms {
get;
set;
}
///
/// Creates an instance of the Sasl mechanism with the specified
/// name.
///
/// The name of the Sasl mechanism of which an
/// instance will be created.
/// An instance of the Sasl mechanism with the specified name.
/// The name parameter is null.
/// A Sasl mechanism with the
/// specified name is not registered with Sasl.SaslFactory.
public static SaslMechanism Create(string name) {
name.ThrowIfNull("name");
if (!Mechanisms.ContainsKey(name)) {
throw new SaslException("A Sasl mechanism with the specified name " +
"is not registered with Sasl.SaslFactory.");
}
Type t = Mechanisms[name];
object o = Activator.CreateInstance(t, true);
return o as SaslMechanism;
}
///
/// Registers a Sasl mechanism with the factory using the specified name.
///
/// The name with which to register the Sasl mechanism
/// with the factory class.
/// The type of the class implementing the Sasl mechanism.
/// The implementing class must be a subclass of Sasl.SaslMechanism.
/// The name parameter or the t
/// parameter is null.
/// The class represented by the
/// specified type does not derive from Sasl.SaslMechanism.
/// The Sasl mechanism could not be
/// registered with the factory. Refer to the inner exception for error
/// details.
public static void Add(string name, Type t) {
name.ThrowIfNull("name");
t.ThrowIfNull("t");
if (!t.IsSubclassOf(typeof(SaslMechanism))) {
throw new ArgumentException("The type t must be a subclass " +
"of Sasl.SaslMechanism");
}
try {
Mechanisms.Add(name, t);
} catch (Exception e) {
throw new SaslException("Registration of Sasl mechanism failed.", e);
}
}
///
/// Static class constructor. Initializes static properties.
///
static SaslFactory() {
Mechanisms = new Dictionary(
StringComparer.InvariantCultureIgnoreCase);
// Could be moved to App.config to support SASL "plug-in" mechanisms.
var list = new Dictionary() {
{ "PLAIN", typeof(Sasl.Mechanisms.SaslPlain) },
{ "DIGEST-MD5", typeof(Sasl.Mechanisms.SaslDigestMd5) },
{ "SCRAM-SHA-1", typeof(Sasl.Mechanisms.SaslScramSha1) },
};
foreach (string key in list.Keys)
Mechanisms.Add(key, list[key]);
}
}
}