public void GetStringTest()
        {
            string value = "String";
            NameValueCollection collection = new NameValueCollection();
            collection.Add("String", value);

            Assert.AreEqual(value, collection.GetString("String"));
            Assert.AreEqual<string>(value, collection.GetString("String"));
            Assert.IsNotNull(collection.GetString("String"));
            Assert.IsNull(collection.GetString("DoesNotExist"));
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            Condition.Requires(name, "name").IsNotNullOrWhiteSpace();
            Condition.Requires(config, "config").IsNotNull();

            var membershipProviderName = config.GetString("membershipProviderName");

            if (!string.IsNullOrWhiteSpace(membershipProviderName))
            {
                this.membershipProvider = this.membershipProviders[membershipProviderName] as BetterMembershipProvider;
            }

            if (this.membershipProvider == null)
            {
                throw new ProviderException("membershipProviderName is required");
            }

            config.Remove("membershipProviderName");

            base.Initialize(name, config);

            if (this.membershipProvider.AutoInitialize)
            {
                this.InitializeDatabaseConnection();
            }
        }
        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
        /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
        /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception>
        public override void Initialize(string name, NameValueCollection config) {
            base.Initialize(name, config);

            string defaultAppName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            this.ApplicationName = config.GetString("applicationName", defaultAppName);

            this.CaseSensitive = config.GetBool("caseSensitive", false);
            this.Comparer = this.CaseSensitive
                ? StringComparer.CurrentCulture : StringComparer.CurrentCultureIgnoreCase;
            this.Comparison = this.CaseSensitive
                    ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
            this.UseUniversalTime = config.GetBool("useUniversalTime", false);
        }
        public void TestToString()
        {
            // Arrange
            const string name = "name";
            const string baseUri = "baseUri";
            const string method = "GET";
            const string userAgent = "useAgent";
            const string uri = "uri";
            var headers = new NameValueCollection { { "a", "b"} };
            var cookies = new NameValueCollection { { "c", "d" } };
            var pathInfos = new List<string> { "e", "f" };
            var queryStrings = new NameValueCollection { { "g", "h" } };
            const string fragment = "fragment";
            const string content = "content";

            // Act
            var result = new HttpRequest
            {
                Name = name,
                BaseUri = baseUri,
                Method = method,
                UserAgent = userAgent,
                Uri = uri,
                Headers = headers,
                Cookies = cookies,
                PathInfos = pathInfos,
                QueryStrings = queryStrings,
                Fragment = fragment,
                Content = content
            }.ToString();

            // Assert
            Assert.AreEqual(
                string.Format("Name={0}, BaseUri={1}, Method={2}, UserAgent={3}, Uri={4}, Headers={5}, Cookies={6}, PathInfos={7}, QueryStrings={8}, Fragment={9}, Content={10}",
                    name,
                    baseUri,
                    method,
                    userAgent,
                    uri,
                    headers.GetString(),
                    cookies.GetString(),
                    pathInfos.GetString(),
                    queryStrings.GetString(),
                    fragment,
                    content),
                result);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            Condition.Requires(name, "name").IsNotNullOrWhiteSpace();
            Condition.Requires(config, "config").IsNotNull();

            if (config.ContainsKey("requiresQuestionAndAnswer"))
            {
                throw new ProviderException("unrecognized attribute requiresQuestionAndAnswer");
            }

            if (config.ContainsKey("enablePasswordRetrieval"))
            {
                throw new ProviderException("unrecognized attribute enablePasswordRetrieval");
            }

            if (config.ContainsKey("enablePasswordReset"))
            {
                throw new ProviderException("unrecognized attribute enablePasswordReset");
            }

            if (config.ContainsKey("passwordFormat"))
            {
                throw new ProviderException("unrecognized attribute passwordFormat");
            }

            this.connectionStringName = config.GetString("connectionStringName", "DefaultConnection");
            this.userTableName = config.GetString("userTableName", "UserProfile");
            this.userIdColumn = config.GetString("userIdColumn", "UserId");
            this.userNameColumn = config.GetString("userNameColumn", "UserName");
            this.userEmailColumn = config.GetString("userEmailColumn");
            this.autoCreateTables = config.GetBoolean("autoCreateTables", true);
            this.autoInitialize = config.GetBoolean("autoInitialize", true);
            this.maxInvalidPasswordAttempts = config.GetInteger("maxInvalidPasswordAttempts", int.MaxValue);
            this.minRequiredNonalphanumericCharacters = config.GetInteger("minRequiredNonalphanumericCharacters");
            this.minRequiredPasswordLength = config.GetInteger("minRequiredPasswordLength", 1);
            this.requiresUniqueEmail = config.GetBoolean("requiresUniqueEmail");
            this.maxEmailLength = config.GetInteger("maxEmailLength", 254);
            this.maxUserNameLength = config.GetInteger("maxUserNameLength", 56);
            this.maxPasswordLength = config.GetInteger("maxPasswordLength", 128);
            this.emailStrengthRegularExpression = config.GetString(
                "emailStrengthRegularExpression", @"^[0-9a-zA-Z.+_-]+@[0-9a-zA-Z.+_-]+\.[a-zA-Z]{2,4}$");
            this.userNameRegularExpression = config.GetString("userNameRegularExpression", @"^[0-9a-zA-Z_-]+$");
            this.ApplicationName = config.GetString("applicationName", "/");
            this.allowEmailAsUserName = config.GetBoolean("allowEmailAsUserName", true);

            try
            {
                new Regex(this.emailStrengthRegularExpression);
            }
            catch (ArgumentException e)
            {
                throw new ProviderException("invalid value for emailStrengthRegularExpression", e);
            }

            try
            {
                new Regex(this.userNameRegularExpression);
            }
            catch (ArgumentException e)
            {
                throw new ProviderException("invalid value for userNameRegularExpression", e);
            }

            if (config.ContainsKey("passwordAttemptWindowInSeconds") && config.ContainsKey("passwordAttemptWindow"))
            {
                throw new ProviderException(
                    "passwordAttemptWindowInSeconds and passwordAttemptWindow cannot both be set");
            }

            if (config.ContainsKey("passwordAttemptWindowInSeconds"))
            {
                this.passwordAttemptWindowInSeconds = config.GetInteger("passwordAttemptWindowInSeconds", int.MaxValue);
            }
            else
            {
                var passwordAttemptWindowInMinutes = config.GetInteger("passwordAttemptWindow", -1);
                if (passwordAttemptWindowInMinutes < 0)
                {
                    this.passwordAttemptWindowInSeconds = int.MaxValue;
                }
                else
                {
                    this.passwordAttemptWindowInSeconds = passwordAttemptWindowInMinutes * 60;
                }
            }

            if (this.requiresUniqueEmail && !this.HasEmailColumnDefined)
            {
                throw new ProviderException("requiresUniqueEmail cannot be defined without userEmailColumn");
            }

            config.Remove("userTableName");
            config.Remove("userIdColumn");
            config.Remove("userNameColumn");
            config.Remove("userEmailColumn");
            config.Remove("autoCreateTables");
            config.Remove("autoInitialize");
            config.Remove("passwordAttemptWindow");
            config.Remove("passwordAttemptWindowInSeconds");
            config.Remove("maxEmailLength");
            config.Remove("maxUserNameLength");
            config.Remove("maxPasswordLength");
            config.Remove("emailStrengthRegularExpression");
            config.Remove("userNameRegularExpression");
            config.Remove("allowEmailAsUserName");

            var providerName = string.Empty;
            var connectionString = ConfigurationManager.ConnectionStrings[this.ConnectionStringName];
            if (connectionString != null)
            {
                providerName = connectionString.ProviderName;
            }

            this.sqlQueryBuilder = this.sqlQueryBuilderFactory(
                providerName, this.userTableName, this.userIdColumn, this.userNameColumn, this.userEmailColumn);

            base.Initialize(name, config);

            if (this.AutoInitialize)
            {
                this.InitializeDatabaseConnection();

                if (this.HasEmailColumnDefined)
                {
                    this.CreateUserEmailColumn();
                }
            }
        }
        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
        /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
        /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception>
        public override void Initialize(string name, NameValueCollection config) {

            if (config == null)
                throw new ArgumentNullException("config");

            // prerequisites
            if (string.IsNullOrEmpty(name)) {
                name = "XmlProfileProvider";
            }
            if (string.IsNullOrEmpty(config["description"])) {
                config.Remove("description");
                config.Add("description", "XML Profile Provider");
            }

            // initialize the base class
            base.Initialize(name, config);

            // initialize provider fields
            string fileName = config.GetString("fileName", "Profiles.xml");
            string folder = config.GetString("folder", "~/App_Data/");

            if (!folder.EndsWith("/")) folder += "/";
            _file = HostingEnvironment.MapPath(string.Format("{0}{1}", folder, fileName));
        }
        /// <summary>
        /// Initializes the provider.
        /// </summary>
        /// <param name="name">The friendly name of the provider.</param>
        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// The name of the provider is null.
        /// </exception>
        /// <exception cref="T:System.ArgumentException">
        /// The name of the provider has a length of zero.
        /// </exception>
        /// <exception cref="T:System.InvalidOperationException">
        /// An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.
        /// </exception>
        public override void Initialize(string name, NameValueCollection config) {
            base.Initialize(name, config);

            string defaultAppName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
            this.ApplicationName = config.GetString("applicationName", defaultAppName);

            // fecth provider settings
            _enablePasswordReset = config.GetBool("enablePasswordReset", true);
            _enablePasswordRetrieval = config.GetBool("enablePasswordRetrieval", false);
            _maxInvalidPasswordAttempts = config.GetInt("maxInvalidPasswordAttempts", 5);
            _minRequiredNonAlphanumericCharacters = config.GetInt("minRequiredNonAlphanumericCharacters", 0);
            _minRequiredPasswordLength = config.GetInt("minRequiredPasswordLength", 4);
            _passwordAttemptWindow = config.GetInt("passwordAttemptWindow", 10);
            _passwordFormat = config.GetEnum<MembershipPasswordFormat>("passwordFormat");
            _passwordStrengthRegularExpression = config.GetString("passwordStrengthRegularExpression", @"[\w| !ยง$%&/()=\-?\*]*");
            _requiresQuestionAndAnswer = config.GetBool("requiresQuestionAndAnswer", false);
            _requiresUniqueEmail = config.GetBool("requiresUniqueEmail", true);

            this.CaseSensitive = config.GetBool("caseSensitive", false);
            this.Comparer = this.CaseSensitive
                ? StringComparer.CurrentCulture : StringComparer.CurrentCultureIgnoreCase;
            this.Comparison = this.CaseSensitive
                    ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
            this.UseUniversalTime = config.GetBool("useUniversalTime", false);
        }
        public void TestToString()
        {
            // Arrange
            var uri = new Uri("http://yahoo.com");
            const HttpStatusCode statusCode = HttpStatusCode.OK;
            var lastModified = DateTime.Now;
            const string contentType = "text/xml";
            var headers = new NameValueCollection { { "a", "b" } };
            var cookies = new NameValueCollection { { "c", "d" } };
            var exception= new Exception("message");

            // Act
            var result = new HttpResponse
            {
                Uri = uri,
                StatusCode = statusCode,
                LastModified = lastModified,
                ContentType = contentType,
                Headers = headers,
                Cookies = cookies,
                Exception = exception,
            }.ToString();

            // Assert
            Assert.AreEqual(
                string.Format("Uri={0}, StatusCode={1}, LastModified={2}, ContentType={3}, Headers={4}, Cookies={5}, Exception={6}",
                    uri,
                    statusCode,
                    lastModified,
                    contentType,
                    headers.GetString(),
                    cookies.GetString(),
                    exception),
                result);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            Condition.Requires(name, "name").IsNotNullOrWhiteSpace();
            Condition.Requires(config, "config").IsNotNull();

            var membershipProviderName = config.GetString("membershipProviderName");

            if (!string.IsNullOrWhiteSpace(membershipProviderName))
            {
                this.membershipProvider = this.membershipProviders[membershipProviderName] as BetterMembershipProvider;
            }

            if (this.membershipProvider == null)
            {
                throw new ProviderException("membershipProviderName is required");
            }

            config.Remove("membershipProviderName");

            base.Initialize(name, config);

            var providerName = string.Empty;
            var connectionString = ConfigurationManager.ConnectionStrings[this.membershipProvider.ConnectionStringName];
            if (connectionString != null)
            {
                providerName = connectionString.ProviderName;
            }

            this.sqlQueryBuilder = this.sqlQueryBuilderFactory(
                providerName, 
                this.membershipProvider.UserTableName, 
                this.membershipProvider.UserIdColumn, 
                this.membershipProvider.UserNameColumn, 
                this.membershipProvider.UserEmailColumn);
        }