コード例 #1
0
        //

        private bool IsValidEmail(string email)
        {
            var attribute = new EmailAttribute();


            return(attribute.IsValid(email));
        }
コード例 #2
0
        public void EmailAttribute_ExcludeDomains()
        {
            EmailAttribute testSubject = new EmailAttribute {
                Category = EmailCategory.Basic, AllowComments = false, AllowIPAddresses = false, RequireTopLevelDomain = false, IncludeDomains = null, ExcludeDomains = "*evil.o?g;nowhere.com"
            };
            string input  = "*****@*****.**";
            bool   result = testSubject.IsValid(input);

            Assert.IsTrue(result);

            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);

            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);

            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);

            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsTrue(result);
        }
コード例 #3
0
        public void EmailAttribute_IPFilter()
        {
            EmailAttribute testSubject = new EmailAttribute {
                AllowComments = false, AllowIPAddresses = true, RequireTopLevelDomain = false, IncludeDomains = "192.168.10.23;10.12.*", ExcludeDomains = "36.45.12.63;10.12.9.*"
            };
            string input  = "user@[17.45.26.95]";
            bool   result = testSubject.IsValid(input);

            Assert.IsFalse(result);

            input  = "user@[192.168.10.23]";
            result = testSubject.IsValid(input);
            Assert.IsTrue(result);

            input  = "user@[36.45.12.63]";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);

            input  = "user@[10.12.45.125]";
            result = testSubject.IsValid(input);
            Assert.IsTrue(result);

            input  = "user@[10.12.9.152]";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);
        }
コード例 #4
0
 public void Save(EmailAttribute data)
 {
     using (DatabaseContext db = new DatabaseContext()) {
         db.EmailAttributes.Add(data);
         db.SaveChanges();
     }
 }
コード例 #5
0
        public void IsValid()
        {
            var v = new EmailAttribute();

            Assert.IsTrue(v.IsValid("*****@*****.**", null));
            Assert.IsTrue(v.IsValid("", null));
            Assert.IsTrue(v.IsValid(null, null));
            Assert.IsFalse(v.IsValid("emmanuel.hibernate.org", null));
            Assert.IsTrue(v.IsValid("emmanuel@hibernate", null));
            Assert.IsTrue(v.IsValid("emma-n_uel@hibernate", null));
            Assert.IsFalse(v.IsValid("emma [email protected]", null));
            Assert.IsFalse(v.IsValid("emma([email protected]", null));
            Assert.IsFalse(v.IsValid("emmanuel@", null));
            Assert.IsTrue(v.IsValid("*****@*****.**", null));
            Assert.IsTrue(v.IsValid("[email protected]", null));
            Assert.IsFalse(v.IsValid("emma;[email protected]", null));
            Assert.IsFalse(v.IsValid("emma(;[email protected]", null));
            Assert.IsFalse(v.IsValid("emma\[email protected]", null));
            Assert.IsFalse(v.IsValid("emma@[email protected]", null));
            Assert.IsFalse(v.IsValid("emmanuel@@hibernate.org", null));
            Assert.IsFalse(v.IsValid("emmanuel @ hibernate.org", null));
            Assert.IsTrue(v.IsValid("emmanuel@[123.12.2.11]", null));
            Assert.IsFalse(v.IsValid(".emma@[email protected]", null));
            Assert.IsFalse(v.IsValid(5, null));             // check any values different of string
        }
コード例 #6
0
ファイル: ValidBoxExtend.cs プロジェクト: intotf/TC
        /// <summary>
        /// 验证输入是否是Email
        /// </summary>
        /// <param name="box">验证框</param>
        /// <param name="errorMessage">提示信息</param>
        /// <returns></returns>
        public static ValidBox Email(this ValidBox box, string errorMessage)
        {
            var newBox = new EmailAttribute {
                ErrorMessage = errorMessage
            }.ToValidBox();

            return(ValidBox.Merge(box, newBox));
        }
コード例 #7
0
        public void ShouldUseEmailValidatorRegex()
        {
            //Exercise
            var sut = new EmailAttribute();

            //Verify
            sut.Pattern.Should().Be(EmailValidator.REGEX_PATTERN);
        }
コード例 #8
0
        public void ShouldBeRegularExpressionAttribute()
        {
            //Exercise
            var sut = new EmailAttribute();

            //Verify
            sut.Should().BeAssignableTo<RegularExpressionAttribute>();
        }
コード例 #9
0
        public void ShouldUseEmailValidatorRegex()
        {
            //Exercise
            var sut = new EmailAttribute();

            //Verify
            sut.Pattern.Should().Be(EmailValidator.REGEX_PATTERN);
        }
コード例 #10
0
        public void ShouldBeRegularExpressionAttribute()
        {
            //Exercise
            var sut = new EmailAttribute();

            //Verify
            sut.Should().BeAssignableTo <RegularExpressionAttribute>();
        }
コード例 #11
0
 public void Save(EmailAttribute data)
 {
     using (DatabaseContext db = new DatabaseContext()) {
         if (data.Id == 0 || db.EmailAttributes.FirstOrDefault(x => x.Id == data.Id) == null)
         {
             db.EmailAttributes.Add(data);
         }
         db.SaveChanges();
     }
 }
コード例 #12
0
        public void ErrorMessageTest()
        {
            var attribute = new EmailAttribute();

            attribute.ErrorMessage = "SampleErrorMessage";

            const string invalidValue = "a";

            var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null));

            Assert.AreEqual("SampleErrorMessage", result.ErrorMessage);
        }
コード例 #13
0
        public void IsValidTests()
        {
            var attribute = new EmailAttribute();

            Assert.IsTrue(attribute.IsValid(null)); // Don't check for required
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsFalse(attribute.IsValid("foo"));
            Assert.IsFalse(attribute.IsValid("foo@"));
            Assert.IsFalse(attribute.IsValid("foo@bar"));
        }
コード例 #14
0
        public void ErrorResourcesTest()
        {
            var attribute = new EmailAttribute();

            attribute.ErrorMessageResourceName = "ErrorMessage";
            attribute.ErrorMessageResourceType = typeof(ErrorResources);

            const string invalidValue = "a";

            var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null));

            Assert.AreEqual("error message", result.ErrorMessage);
        }
コード例 #15
0
        public void EmailAttribute_Basic_RequireTopLevelDomain()
        {
            EmailAttribute testSubject = new EmailAttribute {
                Category = EmailCategory.Basic, AllowComments = true, AllowIPAddresses = true, RequireTopLevelDomain = true, IncludeDomains = null, ExcludeDomains = null
            };
            string input = this.TestContext.DataRow["MailAddress"].ToString();
            bool   containsTopLevelDomain = Convert.ToBoolean(this.TestContext.DataRow["ContainsTopLevelDomain"]);
            bool   expected = Convert.ToBoolean(this.TestContext.DataRow["IsValid"]) && containsTopLevelDomain;

            bool result = testSubject.IsValid(input);

            Assert.AreEqual(expected, result, input);
        }
コード例 #16
0
ファイル: ValidationTests.cs プロジェクト: tmont/portoa
        public void Should_validate_email()
        {
            var email = new EmailAttribute();
            Assert.That(email.IsValid("*****@*****.**"), Is.True);
            Assert.That(email.IsValid("*****@*****.**"), Is.True);
            Assert.That(email.IsValid("foo/[email protected]"), Is.True);
            Assert.That(email.IsValid("[email protected]"), Is.True);

            Assert.That(email.IsValid("foo@bar."), Is.False);
            Assert.That(email.IsValid("foo@bar"), Is.False);
            Assert.That(email.IsValid("foo"), Is.False);
            Assert.That(email.IsValid("*****@*****.**"), Is.False);
        }
コード例 #17
0
        public DavidEmailFilter(string filter)
        {
            if (!IsValidFilter(filter))
            {
                throw new Exception(string.Format("Invalid filter provided '{0}'", filter));
            }

            var elements = filter.Split(' ');

            this.attribute = (EmailAttribute)Enum.Parse(typeof(EmailAttribute), elements[0]);
            this.comparer  = (EmailAttributeComparer)Enum.Parse(typeof(EmailAttributeComparer), elements[1]);
            this.value     = elements[2].ToLower();
            this.values    = elements[2].Split(',');
        }
コード例 #18
0
        private static Attribute ConvertToEmail(XmlNhvmRuleConverterArgs rule)
        {
            NhvmEmail emailRule = (NhvmEmail)rule.schemaRule;

            log.Info("Converting to Email attribute");
            EmailAttribute thisAttribute = new EmailAttribute();

            if (emailRule.message != null)
            {
                thisAttribute.Message = emailRule.message;
            }
            AssignTagsFromString(thisAttribute, emailRule.tags);

            return(thisAttribute);
        }
コード例 #19
0
        public void GlobalizedErrorResourcesTest()
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX");

            var attribute = new EmailAttribute();

            attribute.ErrorMessageResourceName = "ErrorMessage";
            attribute.ErrorMessageResourceType = typeof(ErrorResources);

            const string invalidValue = "a";

            var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null));

            Assert.AreEqual("mensaje de error", result.ErrorMessage);
        }
コード例 #20
0
        public void EmailAttribute_Extended_AllowComments()
        {
            EmailAttribute testSubject = new EmailAttribute {
                Category = EmailCategory.Extended, AllowComments = false, AllowIPAddresses = true, RequireTopLevelDomain = false, IncludeDomains = null, ExcludeDomains = null
            };

            string input            = this.TestContext.DataRow["MailAddress"].ToString();
            bool   containsComments = Convert.ToBoolean(this.TestContext.DataRow["ContainsComment"]);
            bool   isValid          = Convert.ToBoolean(this.TestContext.DataRow["IsValid"]);
            bool   expected         = isValid && !containsComments;

            bool result = testSubject.IsValid(input);

            Assert.AreEqual(expected, result, input);
        }
コード例 #21
0
        public void EmailAttribute_Configuration_NamedValidator()
        {
            EmailAttribute testSubject = new EmailAttribute("Custom Validator");
            string         input       = "*****@*****.**";
            bool           result      = testSubject.IsValid(input);

            Assert.IsFalse(result, input);

            input  = "user@[127.251.42.88]";
            result = testSubject.IsValid(input);
            Assert.IsTrue(result, input);

            input  = "user(my comment)@[127.251.42.88]";
            result = testSubject.IsValid(input);
            Assert.IsTrue(result, input);
        }
コード例 #22
0
        public ActionResult ContactUs(ContactUsModel model)
        {
            var emailAttr = new EmailAttribute();

            if (String.IsNullOrEmpty(model.FirstName) || String.IsNullOrEmpty(model.LastName) || String.IsNullOrEmpty(model.Email1) || !emailAttr.IsValid(model.Email1))
            {
                throw new Exception("Invalid model");
            }

            var customer = SaveCustomerDto(model, "Online Contact Request", 41, model.Notes ?? "", validateModel: false);

            try
            {
                var strBody = new StringBuilder(1000);
                strBody.AppendLine("<html><head><style>body{font-size: 12pt;font-family: Times New Roman;margin: 0px;}</style></head><body>");
                strBody.AppendLine(customer.DefaultContact.FullName + "<br />");
                if (!String.IsNullOrEmpty(customer.CompanyName))
                {
                    strBody.AppendLine(customer.CompanyName + "<br />");
                }
                strBody.AppendLine("<br /><br /><br />");
                strBody.AppendLine(customer.DefaultContact.Email);
                strBody.AppendLine("<br /><br />");
                var catalog = customer.CustomerCatalogs.FirstOrDefault();
                strBody.AppendLine(catalog != null ? catalog.Name : "");
                strBody.AppendLine("<br /><br />");
                if (!String.IsNullOrEmpty(customer.RawCustomerContacts[0].PrimaryPhone))
                {
                    strBody.AppendLine("T: " + customer.RawCustomerContacts[0].PrimaryPhone + "<br />");
                }
                strBody.AppendLine("<br /><br />");
                strBody.AppendLine(model.Notes);
                strBody.AppendLine("</body></html>");

                var mlClient = new MailManager();
                mlClient.SendMail(WebGlobal.SystemMail, WebGlobal.SalesMail, "New Contact Request", strBody.ToString());
            }
            catch (Exception ex)
            {
                WebGlobal.HandleException(ex, System.Web.HttpContext.Current);
            }

            return(Redirect("/general/contact-us-success"));
        }
コード例 #23
0
        public void EmailAttribute_Configuration()
        {
            EmailAttribute testSubject = new EmailAttribute();
            string         input       = "*****@*****.**";
            bool           result      = testSubject.IsValid(input);

            Assert.IsTrue(result, input);

            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result, input);

            input  = "user@[12.124.63.5]";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result, input);

            input  = "user(my comment)@somewhere.co.uk";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result, input);
        }
コード例 #24
0
        public void EmailAttribute_IncludeExcludeDomains()
        {
            EmailAttribute testSubject = new EmailAttribute {
                Category = EmailCategory.Basic, AllowComments = false, AllowIPAddresses = false, RequireTopLevelDomain = false, IncludeDomains = "all.*.good.org", ExcludeDomains = "all.evil.good.org"
            };
            string input  = "*****@*****.**";
            bool   result = testSubject.IsValid(input);

            Assert.IsTrue(result);

            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);

            testSubject = new EmailAttribute {
                Category = EmailCategory.Basic, AllowComments = false, AllowIPAddresses = false, RequireTopLevelDomain = false, IncludeDomains = "all.good.org", ExcludeDomains = "all.good.org"
            };
            input  = "*****@*****.**";
            result = testSubject.IsValid(input);
            Assert.IsFalse(result);
        }
コード例 #25
0
        public static bool IsValidFilter(string filter)
        {
            var                    elements        = filter.Split(' ');
            EmailAttribute         filterAttribute = EmailAttribute.RecipientList;
            EmailAttributeComparer filterComparer  = EmailAttributeComparer.Contains;

            bool parsable = elements.Length == 3 &&
                            Enum.TryParse <EmailAttribute>(elements[0], out filterAttribute) &&
                            Enum.TryParse <EmailAttributeComparer>(elements[1], out filterComparer);

            if (!parsable)
            {
                return(false);
            }

            return((filterAttribute == EmailAttribute.RecipientList &&
                    (filterComparer == EmailAttributeComparer.Contains ||
                     filterComparer == EmailAttributeComparer.ContainsNot ||
                     filterComparer == EmailAttributeComparer.ContainsAny ||
                     filterComparer == EmailAttributeComparer.ContainsNoneOf)) ||
                   (filterAttribute == EmailAttribute.Sender && (filterComparer == EmailAttributeComparer.Is || filterComparer == EmailAttributeComparer.IsNot)));
        }
コード例 #26
0
        public void SaveEmailAttributeToBlob(EmailAttribute emailAttribute)
        {
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
            CloudBlobContainer  container           = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(ConfigurationManager.AppSettings["BlobContainerName"]);

            string fileName  = $"EmailAttribute{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}.txt";
            string fileName2 = $"EmailAttribute{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}.txt";

            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

            if (!blob.Exists())
            {
                blob.UploadFromStream(new MemoryStream());
            }
            else
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        foreach (var attribute in emailAttribute.Attributes)
                        {
                            blob.DownloadToStream(ms);
                            byte[] dataToWrite = Encoding.UTF8.GetBytes($"Key:{emailAttribute.Key}, Email:{emailAttribute.Email}, Attribute:{attribute}\r\n");
                            ms.Write(dataToWrite, 0, dataToWrite.Length);
                            ms.Position = 0;
                            blob.UploadFromStream(ms);
                        }
                    }
                }
                catch (StorageException excep)
                {
                    if (excep.RequestInformation.HttpStatusCode != 404)
                    {
                        throw;
                    }
                }
            }
        }
コード例 #27
0
        private static string WriteExtenders(PropertyInfo p, out bool isValidatable)
        {
            isValidatable = false;
            StringBuilder sb = new StringBuilder();

            sb.Append(".extend({ editState : false, disableValidation : false, empty : true })");

            RequiredAttribute requiredAttribute = p.GetCustomAttribute <RequiredAttribute>();

            if (requiredAttribute != null)
            {
                sb.Append($".extend({{ required: {{ message: \"{requiredAttribute.FormatErrorMessage(p.Name)}\", onlyIf: function() {{ return ko.utils.isPropertyValidatable(self, \"{ p.Name}\"); }} }} }})");
                isValidatable = true;
            }

            MinLengthAttribute minLengthAttribute = p.GetCustomAttribute <MinLengthAttribute>();

            if (minLengthAttribute != null)
            {
                sb.Append(string.Format(".extend({ minLength: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", minLengthAttribute.FormatErrorMessage(p.Name), minLengthAttribute.Length, p.Name));
                isValidatable = true;
            }

            MaxLengthAttribute maxLengthAttribute = p.GetCustomAttribute <MaxLengthAttribute>();

            if (maxLengthAttribute != null)
            {
                sb.Append(string.Format(".extend({ maxLength: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", maxLengthAttribute.FormatErrorMessage(p.Name), maxLengthAttribute.Length, p.Name));
                isValidatable = true;
            }

            RegularExpressionAttribute regularExpressionAttribute = p.GetCustomAttribute <RegularExpressionAttribute>();

            if (regularExpressionAttribute != null)
            {
                sb.Append(string.Format(".extend({ pattern: { message: \"{0}\", params: /{1}/, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", regularExpressionAttribute.FormatErrorMessage(p.Name), regularExpressionAttribute.Pattern, p.Name));
                isValidatable = true;
            }

            UrlAttribute urlAttribute = p.GetCustomAttribute <UrlAttribute>();

            if (urlAttribute != null)
            {
                sb.Append(string.Format(".extend({ pattern: { message: \"{0}\", params: /{1}/, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", urlAttribute.FormatErrorMessage(p.Name), urlAttribute, p.Name));
                isValidatable = true;
            }

            DateAttribute dateAttribute = p.GetCustomAttribute <DateAttribute>();

            if (dateAttribute != null)
            {
                sb.Append(string.Format(".extend({ date: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })", dateAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            NumericAttribute numericAttribute = p.GetCustomAttribute <NumericAttribute>();

            if (numericAttribute != null)
            {
                sb.Append(
                    string.Format(".extend({ number: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } }).extend({ numeric: {2} })",
                                  numericAttribute.FormatErrorMessage(p.Name), p.Name, numericAttribute.Precision));
                isValidatable = true;
            }

            EmailAttribute emailAttribute = p.GetCustomAttribute <EmailAttribute>();

            if (emailAttribute != null)
            {
                sb.Append(string.Format(".extend({ email: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })", emailAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            DigitsAttribute digitsAttribute = p.GetCustomAttribute <DigitsAttribute>();

            if (digitsAttribute != null)
            {
                sb.Append(string.Format(".extend({ digit: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } }).extend({ numeric: 0 })", digitsAttribute.FormatErrorMessage(p.Name), p.Name));
                isValidatable = true;
            }

            MinAttribute minAttribute = p.GetCustomAttribute <MinAttribute>();

            if (minAttribute != null)
            {
                sb.Append(string.Format(".extend({ min: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", minAttribute.FormatErrorMessage(p.Name), minAttribute.Min, p.Name));
                isValidatable = true;
            }

            MaxAttribute maxAttribute = p.GetCustomAttribute <MaxAttribute>();

            if (maxAttribute != null)
            {
                sb.Append(string.Format(".extend({ max: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", maxAttribute.FormatErrorMessage(p.Name), maxAttribute.Max, p.Name));
                isValidatable = true;
            }

            EqualToAttribute equalToAttribute = p.GetCustomAttribute <EqualToAttribute>();

            if (equalToAttribute != null)
            {
                sb.Append(string.Format(".extend({ equal: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", equalToAttribute.FormatErrorMessage(p.Name), equalToAttribute.OtherProperty, p.Name));
                isValidatable = true;
            }

            CompareAttribute compareAttribute = p.GetCustomAttribute <CompareAttribute>();

            if (compareAttribute != null)
            {
                sb.Append(string.Format(".extend({ equal: { message: \"{0}\", params: \"{1}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", compareAttribute.FormatErrorMessage(p.Name), compareAttribute.OtherProperty, p.Name));
                isValidatable = true;
            }

            FormatterAttribute formatterAttribute = p.GetCustomAttribute <FormatterAttribute>();

            if (formatterAttribute != null)
            {
                sb.Append(string.Format(".formatted({0}, {1})", formatterAttribute.Formatter, JsonConvert.SerializeObject(formatterAttribute.Arguments)));
            }

            return(sb.ToString());
        }
コード例 #28
0
        public DataResultUserCreateResult CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, string activateFormVirtualPath)
        {
            DataResultUserCreateResult result;
            EmailAttribute emailDataAnnotations = new EmailAttribute();
            if (!emailDataAnnotations.IsValid(email))
            {
                //result = new DataResultUserCreateResult(new CreatedAccountResultModel(MembershipCreateStatus.InvalidEmail));
                result = new DataResultUserCreateResult()
                {
                    IsValid = true,
                    MessageType = DataResultMessageType.Error,
                    Data = new CreatedAccountResultModel(MembershipCreateStatus.InvalidEmail)
                };
            }
            else
            {
                if (this.ValidatePasswordStrength(password))
                {

                    using (TransactionScope trans = this.TransactionScopeCreate())
                    {
                        result = this._dal.CreateUser(username, password, email, passwordQuestion, passwordAnswer, activateFormVirtualPath);

                        if (result.Data.CreateStatus == MembershipCreateStatus.Success)
                        {
                            MembershipUserWrapper newUser = _dal.GetUserByName(username, false).Data;

                            IRoleAdminBL _roleBl = new RoleAdminBL();
                            DataResultBoolean newUserRole = _roleBl.AddToRoles(newUser.UserName, new string[1] { SiteRoles.Guest.ToString() });
                            _roleBl.Dispose();

                            ProfileBL _profileBL = new ProfileBL();
                            UserProfileModel usrProfile = _profileBL.Create(username).Data;
                            _profileBL.Dispose();

                            ITokenTemporaryPersistenceBL<MembershipUserWrapper> _tokenServices = new TokenTemporaryPersistenceBL<MembershipUserWrapper>();
                            TokenTemporaryPersistenceServiceItem<MembershipUserWrapper> token = new TokenTemporaryPersistenceServiceItem<MembershipUserWrapper>(newUser);
                            _tokenServices.Insert(token);
                            result.Data.ActivateUserToken = token.Token;
                            _tokenServices.Dispose();

                            if (newUserRole.Data)
                            {

                                MailingHelper.Send(delegate()
                                {
                                    MailMessage mail = new MailMessage();
                                    mail.From = new MailAddress(MailingHelper.MailingConfig.SupportTeamEmailAddress);
                                    mail.Bcc.Add(new MailAddress(newUser.Email));
                                    mail.Subject = string.Format(AccountResources.CreateNewAccount_EmailSubject, MailingHelper.DomainConfig.DomainName);
                                    mail.Body = string.Format(AccountResources.CreateNewAccount_EmailBody,
                                                                                MailingHelper.DomainConfig.DomainName,
                                                                                new Uri(string.Format("{0}://{1}/{2}/{3}",
                                                                                                                        ApplicationConfiguration.DomainInfoSettingsSection.SecurityProtocol,
                                                                                                                        ApplicationConfiguration.DomainInfoSettingsSection.DomainName,
                                                                                                                        activateFormVirtualPath.ToString(),
                                                                                                                        result.Data.ActivateUserToken)));
                                    return mail;
                                });

                                trans.Complete();
                            }
                            else
                            {
                                trans.Dispose();
                            }
                        }
                        else
                        {
                            trans.Dispose();
                        }
                    }
                }
                else
                {
                    result = new DataResultUserCreateResult()
                    {
                        IsValid = true,
                        MessageType = DataResultMessageType.Error,
                        Data = new CreatedAccountResultModel(MembershipCreateStatus.InvalidPassword)
                    };

                }
            }
            return result;
        }
コード例 #29
0
        /// <summary>
        /// Génère l'attribut de validation issu du domaine.
        /// </summary>
        /// <param name="validationAttribute">Attribut de validation.</param>
        /// <returns>Attribut de validation formatté.</returns>
        protected override string LoadValidationAttribute(ValidationAttribute validationAttribute)
        {
            if (validationAttribute == null)
            {
                throw new ArgumentNullException("validationAttribute");
            }

            RangeAttribute rangeAttr = validationAttribute as RangeAttribute;

            if (rangeAttr != null)
            {
                return("[Range(" + rangeAttr.Minimum.ToString() + ", " + rangeAttr.Maximum.ToString() + ")]");
            }

            EmailAttribute emailAttr = validationAttribute as EmailAttribute;

            if (emailAttr != null)
            {
                return("[Email(" + emailAttr.MaximumLength + ")]");
            }

            StringLengthAttribute strLenAttr = validationAttribute as StringLengthAttribute;

            if (strLenAttr != null)
            {
                StringBuilder sb = new StringBuilder("[StringLength(");
                sb.Append(strLenAttr.MaximumLength);
                if (strLenAttr.MinimumLength > 0)
                {
                    sb.Append(" , ");
                    sb.Append("MinimumLength = ");
                    sb.Append(strLenAttr.MinimumLength);
                }

                sb.Append(")]");
                return(sb.ToString());
            }

            RegularExpressionAttribute regexAttr = validationAttribute as RegularExpressionAttribute;

            if (regexAttr != null)
            {
                return("[RegularExpression(\"" + regexAttr.Pattern + "\")]");
            }

            DateAttribute dateAttr = validationAttribute as DateAttribute;

            if (dateAttr != null)
            {
                return(string.Format(CultureInfo.InvariantCulture, "[Date({0})]", dateAttr.Precision));
            }

            NumeroSiretAttribute siretAttr = validationAttribute as NumeroSiretAttribute;

            if (siretAttr != null)
            {
                return("[NumeroSiret]");
            }

            throw new NotSupportedException("Recopie d'attribut de validation par aspect non géré pour : " + validationAttribute.GetType().ToString());
        }
コード例 #30
0
        public async Task <IHttpActionResult> CreateAsync(EmailAttribute emailAttribute)
        {
            await emailAttributesService.DoExecution(emailAttribute);

            return(Success(emailAttribute));
        }
コード例 #31
0
ファイル: ValidBoxExtend.cs プロジェクト: intotf/TC
        /// <summary>
        /// 验证输入是否是Email
        /// </summary>
        /// <param name="box">验证框</param>
        /// <returns></returns>
        public static ValidBox Email(this ValidBox box)
        {
            var newBox = new EmailAttribute().ToValidBox();

            return(ValidBox.Merge(box, newBox));
        }
コード例 #32
0
        public void KnownRulesConvertAssing()
        {
            NhvMapping       map = XmlMappingLoader.GetXmlMappingFor(typeof(WellKnownRules));
            NhvmClass        cm  = map.@class[0];
            XmlClassMapping  rm  = new XmlClassMapping(cm);
            MemberInfo       mi;
            List <Attribute> attributes;

            mi         = typeof(WellKnownRules).GetField("AP");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            Assert.AreEqual("A string value", ((ACustomAttribute)attributes[0]).Value1);
            Assert.AreEqual(123, ((ACustomAttribute)attributes[0]).Value2);
            Assert.AreEqual("custom message", ((ACustomAttribute)attributes[0]).Message);

            mi         = typeof(WellKnownRules).GetField("StrProp");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            NotEmptyAttribute nea = FindAttribute <NotEmptyAttribute>(attributes);

            Assert.AreEqual("not-empty message", nea.Message);

            NotNullAttribute nna = FindAttribute <NotNullAttribute>(attributes);

            Assert.AreEqual("not-null message", nna.Message);

            NotNullNotEmptyAttribute nnea = FindAttribute <NotNullNotEmptyAttribute>(attributes);

            Assert.AreEqual("notnullnotempty message", nnea.Message);

            LengthAttribute la = FindAttribute <LengthAttribute>(attributes);

            Assert.AreEqual("length message", la.Message);
            Assert.AreEqual(1, la.Min);
            Assert.AreEqual(10, la.Max);

            PatternAttribute pa = FindAttribute <PatternAttribute>(attributes);

            Assert.AreEqual("pattern message", pa.Message);
            Assert.AreEqual("[0-9]+", pa.Regex);
            Assert.AreEqual(RegexOptions.Compiled, pa.Flags);

            EmailAttribute ea = FindAttribute <EmailAttribute>(attributes);

            Assert.AreEqual("email message", ea.Message);

            IPAddressAttribute ipa = FindAttribute <IPAddressAttribute>(attributes);

            Assert.AreEqual("ipAddress message", ipa.Message);

            EANAttribute enaa = FindAttribute <EANAttribute>(attributes);

            Assert.AreEqual("ean message", enaa.Message);

            CreditCardNumberAttribute ccna = FindAttribute <CreditCardNumberAttribute>(attributes);

            Assert.AreEqual("creditcardnumber message", ccna.Message);

            IBANAttribute iban = FindAttribute <IBANAttribute>(attributes);

            Assert.AreEqual("iban message", iban.Message);

            mi         = typeof(WellKnownRules).GetField("DtProp");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            FutureAttribute fa = FindAttribute <FutureAttribute>(attributes);

            Assert.AreEqual("future message", fa.Message);
            PastAttribute psa = FindAttribute <PastAttribute>(attributes);

            Assert.AreEqual("past message", psa.Message);

            mi         = typeof(WellKnownRules).GetField("DecProp");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            DigitsAttribute dga = FindAttribute <DigitsAttribute>(attributes);

            Assert.AreEqual("digits message", dga.Message);
            Assert.AreEqual(5, dga.IntegerDigits);
            Assert.AreEqual(2, dga.FractionalDigits);

            MinAttribute mina = FindAttribute <MinAttribute>(attributes);

            Assert.AreEqual("min message", mina.Message);
            Assert.AreEqual(100, mina.Value);

            MaxAttribute maxa = FindAttribute <MaxAttribute>(attributes);

            Assert.AreEqual("max message", maxa.Message);
            Assert.AreEqual(200, maxa.Value);

            DecimalMaxAttribute decimalmaxa = FindAttribute <DecimalMaxAttribute>(attributes);

            Assert.AreEqual("decimal max message", decimalmaxa.Message);
            Assert.AreEqual(200.1m, decimalmaxa.Value);

            DecimalMinAttribute decimalmina = FindAttribute <DecimalMinAttribute>(attributes);

            Assert.AreEqual("decimal min message", decimalmina.Message);
            Assert.AreEqual(99.9m, decimalmina.Value);

            mi         = typeof(WellKnownRules).GetField("BProp");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            AssertTrueAttribute ata = FindAttribute <AssertTrueAttribute>(attributes);

            Assert.AreEqual("asserttrue message", ata.Message);
            AssertFalseAttribute afa = FindAttribute <AssertFalseAttribute>(attributes);

            Assert.AreEqual("assertfalse message", afa.Message);


            mi         = typeof(WellKnownRules).GetField("ArrProp");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            SizeAttribute sa = FindAttribute <SizeAttribute>(attributes);

            Assert.AreEqual("size message", sa.Message);
            Assert.AreEqual(2, sa.Min);
            Assert.AreEqual(9, sa.Max);

            mi         = typeof(WellKnownRules).GetField("Pattern");
            attributes = new List <Attribute>(rm.GetMemberAttributes(mi));
            PatternAttribute spa = FindAttribute <PatternAttribute>(attributes);

            Assert.AreEqual("{validator.pattern}", spa.Message);
            Assert.AreEqual(@"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", spa.Regex);
            Assert.AreEqual(RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, spa.Flags);
        }
コード例 #33
0
 public EmailAttributeTest()
 {
     _attribute = new EmailAttribute();
 }
コード例 #34
0
        //
        private bool IsValidEmail(string email)
        {
            var attribute = new EmailAttribute();

            return attribute.IsValid(email);
        }