Ejemplo n.º 1
0
        // Register button Event Handler
        private void OnRegisterClick(object sender, EventArgs args)
        {
            hideKeyboard(sender);

            if (!EmailValidator.IsValidEmail(usernameTextBox.Text))
            {
                usernameWrapper.Error        = "Please enter a valid email address";
                usernameWrapper.ErrorEnabled = true;
            }
            else
            {
                CorrectUsername();
            }

            if (PasswordValidator.validate(passwordTextBox.Text, usernameTextBox.Text) != null)
            {
                passwordWrapper.Error        = PasswordValidator.validate(passwordTextBox.Text, usernameTextBox.Text);
                passwordWrapper.ErrorEnabled = true;
            }
            else
            {
                CorrectPassword();
            }

            if (usernameWrapper.ErrorEnabled == false && passwordWrapper.ErrorEnabled == false)
            {
                CorrectInputs();
            }
        }
Ejemplo n.º 2
0
 private void ValidateEmail(string email)
 {
     if (!EmailValidator.IsValidEmail(email))
     {
         throw new ArgumentException("Email is not valid");
     }
 }
Ejemplo n.º 3
0
        public static UserEntity RegisterUser(string email, string password, string name,
                                              string primaryTelephone, string secundaryTelephone, string cpf, UserType userType, string cep,
                                              int AverageTicketPoints, int RegisterClientsPoints, int salesNumberPoints, int averageTtensPerSalepoints,
                                              int inviteAllyFlowersPoints, Guid temporadaId, Guid motherFlowerId, bool isActive, DateTime birthday)
        {
            if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(password) || String.IsNullOrEmpty(name) ||
                String.IsNullOrEmpty(primaryTelephone) || String.IsNullOrEmpty(cpf))
            {
                throw new ExceptionWithHttpStatus(System.Net.HttpStatusCode.BadRequest, Messages.OBRIGATORY_DATA_MISSING);
            }
            EmailValidator.IsValidEmail(email);

            var oldUser = UserRepository.Get().GetUserByEmail(email);

            if (oldUser != null)
            {
                throw new ExceptionWithHttpStatus(System.Net.HttpStatusCode.BadRequest, Messages.EMAIL_ALREADY_USED);
            }

            var currentSeason = SeasonBusiness.GetCurrentSeason();

            var cryptoPassword = EncryptPassword(password);
            var newUserId      = Guid.NewGuid();

            UserRepository.Get().InsertUser(newUserId, email, cryptoPassword.Password, cryptoPassword.Salt, name, primaryTelephone,
                                            secundaryTelephone, cpf, userType, cep, AverageTicketPoints, RegisterClientsPoints, salesNumberPoints, averageTtensPerSalepoints,
                                            inviteAllyFlowersPoints, currentSeason.TemporadaId, motherFlowerId, isActive, birthday);
            var newUser = UserRepository.Get().GetUserById(newUserId);

            if (newUser == null)
            {
                throw new ExceptionWithHttpStatus(System.Net.HttpStatusCode.BadRequest, Messages.USER_REGISTRATION_ERROR);
            }
            return(newUser);
        }
Ejemplo n.º 4
0
        public void TestInvalidAsciiAddress()
        {
            var emailValidator = new EmailValidator();

            string[] addresses =
            {
                "Abc.example.com",                        // (no @ character)
                "A@b@[email protected]",                      // (only one @ is allowed outside quotation marks)
                "a\"b(c)d,e:f;g<h>i[j\\k][email protected]",  // (none of the special characters in this local-part are allowed outside quotation marks)
                "just\"not\"*****@*****.**",           // (quoted strings must be dot separated or the only element making up the local-part)
                "this is\"not\[email protected]",       // (spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
                "this\\ still\"not\\[email protected]", // (even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
                // This test fails. See https://tools.ietf.org/html/rfc5321#section-4.5.3.
                // "*****@*****.**", // (local part is longer than 64 characters)
                "i_like_underscore@but_its_not_allow_in _this_part.example.com", // (Underscore is not allowed in domain part)
            };

            foreach (var address in addresses)
            {
                bool result = emailValidator.IsValidEmail(address);
                Assert.IsFalse(result,
                               String.Format("Expected for '{0}': false; Actual: {1}",
                                             address, result));
            }
        }
Ejemplo n.º 5
0
        public void TestValidAsciiAddress()
        {
            var emailValidator = new EmailValidator();

            string[] addresses =
            {
                // Tests from Wikipedia
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**", // (may go to [email protected] inbox depending on mail server)
                "*****@*****.**",                     // (one-letter local-part)
                "*****@*****.**",
                "admin@mailserver1",                 // (local domain name with no TLD, although ICANN highly discourages dotless email addresses[13])
                "*****@*****.**",                 // (see the List of Internet top-level domains)
                "\" \"@example.org",                 // (space between the quotes)
                "\"john..doe\"@example.org",         // (quoted double dot)
                "[email protected]",     // (bangified host route used for uucp mailers)
                "*****@*****.**",      // (% escaped mail route to [email protected] via example.org)
            };

            foreach (var address in addresses)
            {
                bool result = emailValidator.IsValidEmail(address);
                Assert.IsTrue(result,
                              String.Format("Expected for '{0}': true; Actual: {1}",
                                            address, result));
            }
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> OnPostAsync()
        {
            _logger.LogTrace("CreateModel {CreateModel} submitted", newUserList);

            if (!ModelState.IsValid)
            {
                _logger.LogTrace("Submitted TaskModel is invalid {errors}", ModelState.Values);
                return(Page());
            }
            else
            {
                List <UserRest> userList = new List <UserRest>();

                char[]   separators = new char[] { '\n' };
                string[] subs       = newUserList.UserList.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                foreach (var sub in subs)
                {
                    if (EmailValidator.IsValidEmail(sub.Trim()))
                    {
                        var usr = new UserRest();
                        usr.UserEmail = sub.Trim();
                        usr.Claims    = new Dictionary <string, string> {
                            { newUserList.ClaimName,
                              newUserList.ClaimValue }
                        };

                        userList.Add(usr);
                    }
                    else
                    {
                        string errmsg = string.Format("{0} is not a valid email address.", sub);
                        _logger.LogTrace("Input list of users is not valid. Entry {sub} is not a valid email address.", sub);
                        ModelState.AddModelError(String.Empty, errmsg);

                        return(Page());
                    }
                }

                try
                {
                    _logger.LogTrace("List if users {userList}", userList);
                    await _userService.OnUpdateUserListAsync(userList);

                    _logger.LogTrace("List of users was updated successfuly");

                    return(RedirectToPage("/Admin/Users/Index"));
                }
                catch (Exception e)
                {
                    ModelState.AddModelError(string.Empty, "List of users update failed.");
                    _logger.LogError("List of users update failed. {e}", e);
                    return(Page());
                }
            }
        }
Ejemplo n.º 7
0
        public async Task <OmbiIdentityResult> UpdateUser([FromBody] UserViewModel ui)
        {
            if (!EmailValidator.IsValidEmail(ui.EmailAddress))
            {
                return(Error($"The email address {ui.EmailAddress} is not a valid format"));
            }
            if (!CanModifyUser(ui.Claims.Select(x => x.Value)))
            {
                return(Error("You do not have the correct permissions to create this user"));
            }
            // Get the user
            var user = await UserManager.Users.FirstOrDefaultAsync(x => x.Id == ui.Id);

            user.Alias               = ui.Alias;
            user.Email               = ui.EmailAddress;
            user.MovieRequestLimit   = ui.MovieRequestLimit;
            user.EpisodeRequestLimit = ui.EpisodeRequestLimit;
            var updateResult = await UserManager.UpdateAsync(user);

            if (!updateResult.Succeeded)
            {
                return(new OmbiIdentityResult
                {
                    Errors = updateResult.Errors.Select(x => x.Description).ToList()
                });
            }

            // Get the roles
            var userRoles = await UserManager.GetRolesAsync(user);

            foreach (var role in userRoles)
            {
                await UserManager.RemoveFromRoleAsync(user, role);
            }

            var result = await AddRoles(ui.Claims, user);

            if (result.Any(x => !x.Succeeded))
            {
                var messages = new List <string>();
                foreach (var errors in result.Where(x => !x.Succeeded))
                {
                    messages.AddRange(errors.Errors.Select(x => x.Description).ToList());
                }

                return(new OmbiIdentityResult
                {
                    Errors = messages
                });
            }

            return(new OmbiIdentityResult
            {
                Successful = true
            });
        }
 public Models.Email_DTO Get(string email)
 {
     //make internal email object.
     Models.Email emailObject = new Models.Email(email);
     //Check email
     emailObject.valid = EmailValidator.IsValidEmail(emailObject.email);
     //store in DTO and return.
     Models.Email_DTO edto = new Models.Email_DTO(emailObject);
     return(edto);
 }
Ejemplo n.º 9
0
        private bool InvalidEmailAddress(AddPatientRequest request, ref PdrValidationResult result)
        {
            if (!EmailValidator.IsValidEmail(request.Email))
            {
                result.PassedValidation = false;
                result.Errors.Add("Email must be a valid email address");
                return(true);
            }

            return(false);
        }
Ejemplo n.º 10
0
        public async Task <OmbiIdentityResult> CreateUser([FromBody] UserViewModel user)
        {
            if (!EmailValidator.IsValidEmail(user.EmailAddress))
            {
                return(Error($"The email address {user.EmailAddress} is not a valid format"));
            }
            if (!CanModifyUser(user.Claims.Select(x => x.Value)))
            {
                return(Error("You do not have the correct permissions to create this user"));
            }
            var ombiUser = new OmbiUser
            {
                Alias               = user.Alias,
                Email               = user.EmailAddress,
                UserName            = user.UserName,
                UserType            = UserType.LocalUser,
                MovieRequestLimit   = user.MovieRequestLimit,
                EpisodeRequestLimit = user.EpisodeRequestLimit,
                UserAccessToken     = Guid.NewGuid().ToString("N"),
            };
            var userResult = await UserManager.CreateAsync(ombiUser, user.Password);

            if (!userResult.Succeeded)
            {
                // We did not create the user
                return(new OmbiIdentityResult
                {
                    Errors = userResult.Errors.Select(x => x.Description).ToList()
                });
            }

            var roleResult = await AddRoles(user.Claims, ombiUser);

            if (roleResult.Any(x => !x.Succeeded))
            {
                var messages = new List <string>();
                foreach (var errors in roleResult.Where(x => !x.Succeeded))
                {
                    messages.AddRange(errors.Errors.Select(x => x.Description).ToList());
                }

                return(new OmbiIdentityResult
                {
                    Errors = messages
                });
            }

            return(new OmbiIdentityResult
            {
                Successful = true
            });
        }
Ejemplo n.º 11
0
        public ActionResult Register(RegisterRequest request)
        {
            if (!EmailValidator.IsValidEmail(request.Email))
            {
                return(BadRequest("Email does not exist"));
            }
            if (_us.EmailAlreadyUsed(request.Email))
            {
                return(BadRequest("Email already registered"));
            }

            return(Ok(_us.AddUser(request)));
        }
        public IActionResult RegisterContractor([FromForm] ContractorAccount contractor)
        {
            IActionResult response;

            if (ModelState.IsValid)
            {
                bool AccountExist = ContractorAccountRepository.CheckIfAccountExist(contractor.EmailAddress);

                EmailValidator EmailValidator = new EmailValidator();

                bool isEmailValid = EmailValidator.IsValidEmail(contractor.EmailAddress);

                if (AccountExist == true || (isEmailValid == false))
                {
                    string errorMessage = "This email address is already in use or invalid";
                    response = BadRequest(new { error = errorMessage });
                }
                else
                {
                    PasswordManager PasswordManager = new PasswordManager();

                    string encryptedPassword = PasswordManager.GeneratePassword(contractor.Password);

                    contractor.Password = encryptedPassword;

                    ContractorAccountRepository.MarkAsModified(contractor);

                    string userToken = BuildUserIdentity(contractor);

                    ContractorAccountRepository.SaveNewContractorAccount(contractor);

                    CreateContractorProfile(contractor);

                    var jsonResponse = new {
                        user = new {
                            account = contractor.EmailAddress,
                            token   = userToken,
                            role    = "contractor"
                        }
                    };

                    response = Ok(jsonResponse);
                }
                return(response);
            }
            else
            {
                return(new BadRequestObjectResult(ModelState));
            }
        }
Ejemplo n.º 13
0
        private IAccount CredentialsChecker(string emailAddress)
        {
            ContractorAccount contractor;
            EmailValidator    EmailValidator = new EmailValidator();

            if (EmailValidator.IsValidEmail(emailAddress) == true)
            {
                contractor = ContractorAccountRepository.FindContractorAccount(emailAddress);
                return(contractor);
            }
            else
            {
                contractor = null;
                return(contractor);
            }
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Register(RegisterRequest credentials)
        {
            if (!_emailValidator.IsValidEmail(credentials.Email))
            {
                return(BadRequest(new ErrorResponse {
                    Message = "Invalid user email!"
                }));
            }

            var user = await _userService.Register(credentials.Username, credentials.Email, credentials.Password);

            if (user.IsEmpty)
            {
                return(Conflict(new ErrorResponse {
                    Message = $"User with email: '{credentials.Email}' already exists!"
                }));
            }

            return(Ok(MapUserToResponse(user.Value)));
        }
        public IEnumerable <ValidationError> Validate(NewCustomer newCustomer)
        {
            if (newCustomer.FirstName.IsNullOrWhiteSpace())
            {
                yield return(new ValidationError("FirstName", "First Name is required."));
            }

            if (newCustomer.LastName.IsNullOrWhiteSpace())
            {
                yield return(new ValidationError("LastName", "Last Name is required."));
            }

            if (newCustomer.Email.IsNullOrWhiteSpace())
            {
                yield return(new ValidationError("Email", "Email is required."));
            }
            else if (!EmailValidator.IsValidEmail(newCustomer.Email))
            {
                yield return(new ValidationError("Email", "Email is invalid."));
            }
        }
Ejemplo n.º 16
0
        private async void LoginButton_Click(object sender, EventArgs e)
        {
            string username = loginUsername.EditText.Text.ToString();
            string password = loginPassword.EditText.Text.ToString();

            if (!EmailValidator.IsValidEmail(username))
            {
                // Display message if invalid username
                Toast.MakeText(this, "Please provide a valid email address", ToastLength.Short).Show();
            }
            else if (PasswordValidator.validate(password, username) != null)
            {
                // Display message if invalid password
                Toast.MakeText(this, "Password doesnot meet the requirements", ToastLength.Short).Show();
            }
            else
            {
                // Both username and Password are valid
                FirebaseHelper.FirebaseAuthentication.SignInWithEmailAndPassword(username, password).AddOnCompleteListener(this);
            }
        }
Ejemplo n.º 17
0
        public async Task <IHttpActionResult> Send(ContactFormRequest form)
        {
            if (!EmailValidator.IsValidEmail(form.EmailAddress) || form.Message.IsNullOrWhiteSpace())
            {
                return(BadRequest());
            }

            var message = new StringBuilder();

            message.AppendLine($"Email: {form.EmailAddress}<br /><br />");
            message.AppendLine($"Name: {form.Name}<br /><br />");
            message.AppendLine(form.Message);

            // TODO replace with whiscode domain email once transfer has completed
            if (await _emailService.SendAsync("*****@*****.**", "Website Enquiry", message.ToString()))
            {
                return(Ok());
            }

            return(InternalServerError());
        }
Ejemplo n.º 18
0
        public void TestValidEAIAddress()
        {
            var emailValidator = new EmailValidator();

            string[] addresses =
            {
                "Pelé@example.com",         // Latin alphabet with diacritics
                "δοκιμή@παράδειγμα.δοκιμή", // Greek alphabet
                "我買@屋企.香港",                 //  Traditional Chinese characters
                "二ノ宮@黒川.日本",                // Japanese characters
                "медведь@с-балалайкой.рф",  // Cyrillic characters
                "संपर्क@डाटामेल.भारत",      // Devanagari characters
            };

            foreach (var address in addresses)
            {
                bool result = emailValidator.IsValidEmail(address);
                Assert.IsTrue(result,
                              String.Format("Expected for '{0}': true; Actual: {1}",
                                            address, result));
            }
        }
        public async Task <CustomResponse> Post([FromBody] SubscriptionResource subscriptionResource)
        {
            try
            {
                if (!EmailValidator.IsValidEmail(subscriptionResource.Email))
                {
                    return(CustomResponse.CreateCustomResponse(400, "Invalid Email Address"));
                }
                if (!ModelState.IsValid)
                {
                    return(CustomResponse.CreateCustomResponse(400, "Invalid data"));
                }

                if (_repository.SubscriptionExist(subscriptionResource.Email))
                {
                    return(CustomResponse.CreateCustomResponse(409, "Email already exist"));
                }


                var subscription = _mapper.Map <SubscriptionResource, Subscription>(subscriptionResource);
                subscription.SubscribeDate = DateTime.Now;
                subscription.UniqueToken   = Token.GetToken(subscription.Email);
                _repository.Subscribe(subscription);
                await _unitOfWork.CompleteAsync();

                subscription = _repository.GetSubscription(subscription.Id).Result;
                string[] topics = subscription.Topics.Select(t => t.Topic.Name).ToArray();

                new EmailSender().SendConfirmation(subscription.Email, subscription.UniqueToken, topics);

                return(CustomResponse.CreateCustomResponseWithData(200, "Success", subscription));
            }
            catch (Exception ex)
            {
                return(CustomResponse.CreateCustomResponse(500, "Error" + ex.Message));
            }
        }
Ejemplo n.º 20
0
        public async Task <OmbiIdentityResult> UpdateLocalUser([FromBody] UpdateLocalUserModel ui)
        {
            if (string.IsNullOrEmpty(ui.CurrentPassword))
            {
                return(Error("You need to provide your current password to make any changes"));
            }

            var changingPass = !string.IsNullOrEmpty(ui.Password) || !string.IsNullOrEmpty(ui.ConfirmNewPassword);

            if (changingPass)
            {
                if (!ui.Password.Equals(ui?.ConfirmNewPassword, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(Error("Passwords do not match"));
                }
            }

            if (!EmailValidator.IsValidEmail(ui.EmailAddress))
            {
                return(Error($"The email address {ui.EmailAddress} is not a valid format"));
            }
            // Get the user
            var user = await UserManager.Users.FirstOrDefaultAsync(x => x.Id == ui.Id);

            if (user == null)
            {
                return(Error("The user does not exist"));
            }

            // Make sure the pass is ok
            var passwordCheck = await UserManager.CheckPasswordAsync(user, ui.CurrentPassword);

            if (!passwordCheck)
            {
                return(Error("Your password is incorrect"));
            }

            user.Email = ui.EmailAddress;

            var updateResult = await UserManager.UpdateAsync(user);

            if (!updateResult.Succeeded)
            {
                return(new OmbiIdentityResult
                {
                    Errors = updateResult.Errors.Select(x => x.Description).ToList()
                });
            }

            if (changingPass)
            {
                var result = await UserManager.ChangePasswordAsync(user, ui.CurrentPassword, ui.Password);

                if (!result.Succeeded)
                {
                    return(new OmbiIdentityResult
                    {
                        Errors = result.Errors.Select(x => x.Description).ToList()
                    });
                }
            }
            return(new OmbiIdentityResult
            {
                Successful = true
            });
        }
Ejemplo n.º 21
0
        public async Task <OmbiIdentityResult> CreateUser([FromBody] UserViewModel user)
        {
            if (!EmailValidator.IsValidEmail(user.EmailAddress))
            {
                return(Error($"The email address {user.EmailAddress} is not a valid format"));
            }
            if (!CanModifyUser(user.Claims.Select(x => x.Value)))
            {
                return(Error("You do not have the correct permissions to create this user"));
            }
            if (user.EmailAddress.HasValue() && await UserManager.FindByEmailAsync(user.EmailAddress) != null)
            {
                return(Error("This email has already been taken"));
            }
            var ombiUser = new OmbiUser
            {
                Alias               = user.Alias,
                Email               = user.EmailAddress,
                UserName            = user.UserName,
                UserType            = UserType.LocalUser,
                MovieRequestLimit   = user.MovieRequestLimit,
                EpisodeRequestLimit = user.EpisodeRequestLimit,
                MusicRequestLimit   = user.MusicRequestLimit,
                UserAccessToken     = Guid.NewGuid().ToString("N"),
                StreamingCountry    = user.StreamingCountry.HasValue() ? user.StreamingCountry : "US"
            };
            var userResult = await UserManager.CreateAsync(ombiUser, user.Password);

            if (!userResult.Succeeded)
            {
                // We did not create the user
                return(new OmbiIdentityResult
                {
                    Errors = userResult.Errors.Select(x => x.Description).ToList()
                });
            }

            var roleResult = await AddRoles(user.Claims, ombiUser);

            if (roleResult.Any(x => !x.Succeeded))
            {
                var messages = new List <string>();
                foreach (var errors in roleResult.Where(x => !x.Succeeded))
                {
                    messages.AddRange(errors.Errors.Select(x => x.Description).ToList());
                }

                return(new OmbiIdentityResult
                {
                    Errors = messages
                });
            }

            // Add the quality profiles
            if (user.UserQualityProfiles != null)
            {
                user.UserQualityProfiles.UserId = ombiUser.Id;
                await _userQualityProfiles.Add(user.UserQualityProfiles);
            }
            else
            {
                user.UserQualityProfiles = new UserQualityProfiles
                {
                    UserId = ombiUser.Id
                };
            }

            return(new OmbiIdentityResult
            {
                Successful = true
            });
        }
Ejemplo n.º 22
0
 public void ShouldValidateEmailFalse()
 {
     Assert.False(EmailValidator.IsValidEmail("test.testtest.com"));
 }
Ejemplo n.º 23
0
        public void IsValidEmail_ValidEmail_ReturnTrue(string emailAddress)
        {
            var result = _validator.IsValidEmail(emailAddress);

            Assert.True(result);
        }
Ejemplo n.º 24
0
        protected override void ExecuteInternal(IJobExecutionContext context)
        {
            Log.Informational("Entering into APILeadSubmission processor");
            try
            {
                var response = _contactService.GetAPILeadSubMissionData();
                while (response?.APILeadSubmissionViewModel != null)
                {
                    try
                    {
                        int   contactId = 0;
                        short roleId    = _userRepository.GettingRoleIDByUserID(response.APILeadSubmissionViewModel.OwnerID);
                        var   viewModel = JsonConvert.DeserializeObject <PersonViewModel>(response.APILeadSubmissionViewModel.SubmittedData);
                        viewModel.AccountID     = response.APILeadSubmissionViewModel.AccountID;
                        viewModel.OwnerId       = response.APILeadSubmissionViewModel.OwnerID;
                        viewModel.LastUpdatedBy = response.APILeadSubmissionViewModel.OwnerID;
                        viewModel.FirstName     = !string.IsNullOrEmpty(viewModel.FirstName) ? viewModel.FirstName.Trim() : viewModel.FirstName;
                        viewModel.LastName      = !string.IsNullOrEmpty(viewModel.LastName) ? viewModel.LastName.Trim() : viewModel.LastName;

                        if (viewModel.Phones.IsAny())
                        {
                            viewModel.Phones.Each(pn =>
                            {
                                pn.Number = !string.IsNullOrEmpty(pn.Number) ? pn.Number.Trim() : pn.Number;
                            });
                        }

                        if (viewModel.CustomFields.IsAny())
                        {
                            viewModel.CustomFields.Each(cm =>
                            {
                                cm.Value = !string.IsNullOrEmpty(cm.Value) ? cm.Value.Trim() : cm.Value;
                            });
                        }

                        var    fields = GetContactFields(viewModel);
                        string spamRemarks;
                        bool   isSpam = _spamService.SpamCheck(fields, viewModel.AccountID, response.APILeadSubmissionViewModel.IPAddress, 0, false, out spamRemarks);

                        if (!isSpam)
                        {
                            #region NotSpam
                            var dropdownValues = _dropdownRepository.FindAll("", 10, 1, viewModel.AccountID);
                            IEnumerable <DropdownViewModel> dropdownViewModel = Mapper.Map <IEnumerable <Dropdown>, IEnumerable <DropdownViewModel> >(dropdownValues);

                            string primaryEmail = viewModel.Emails.IsAny() ? viewModel.Emails.Where(e => e.IsPrimary).Select(s => s.EmailId).FirstOrDefault() : "";

                            if (string.IsNullOrEmpty(viewModel.FirstName) && string.IsNullOrEmpty(viewModel.LastName) && !string.IsNullOrEmpty(primaryEmail) && !_emailValidator.IsValidEmail(primaryEmail))
                            {
                                _contactRepository.UpdateAPILeadSubmissionData(null, (byte)SubmittedFormStatus.Fail, "Bad Email", response.APILeadSubmissionViewModel.APILeadSubmissionID);
                                return;
                            }

                            var duplicatesResponse = _contactService.CheckIfDuplicate(new CheckContactDuplicateRequest()
                            {
                                PersonVM = viewModel
                            });

                            var leadSourceField         = viewModel.SelectedLeadSource.IsAny() ? viewModel.SelectedLeadSource.FirstOrDefault() : null;
                            var communityField          = viewModel.Communities.IsAny() ? viewModel.Communities.FirstOrDefault() : null;
                            var leadSourceDropDown      = dropdownViewModel.FirstOrDefault(c => c.DropdownID == (byte)DropdownFieldTypes.LeadSources).DropdownValuesList;
                            var leadSourceDropDownValue = new DropdownValueViewModel();
                            if (leadSourceField != null)
                            {
                                Log.Verbose("Attempting to fetch Lead Source drop down value submitted");
                                leadSourceDropDownValue = leadSourceDropDown.FirstOrDefault(e => e.DropdownValueID == leadSourceField.DropdownValueID);
                            }

                            if (leadSourceDropDownValue == null || leadSourceField == null)
                            {
                                Log.Verbose("Attempting to fetch Next Gen account default Lead Source drop down value");
                                leadSourceDropDownValue = leadSourceDropDown.Where(e => e.IsDefault).FirstOrDefault();
                                if (leadSourceDropDownValue == null)
                                {
                                    Log.Verbose("Attempting to fetch First Lead Source drop down value");
                                    leadSourceDropDownValue = leadSourceDropDown.FirstOrDefault();
                                    if (leadSourceDropDownValue == null)
                                    {
                                        throw new UnsupportedOperationException("[|The accound do not have the specified or any lead source configured. Please contact administrator|]");
                                    }
                                }
                            }

                            DropdownValueViewModel leadSourceDropdownViewModel = new DropdownValueViewModel()
                            {
                                AccountID       = viewModel.AccountID,
                                DropdownID      = (byte)ContactFields.LeadSource,
                                DropdownValue   = leadSourceDropDownValue.DropdownValue,
                                DropdownValueID = leadSourceDropDownValue.DropdownValueID
                            };

                            var communityDropdownViewModel = new DropdownValueViewModel();
                            if (communityField != null)
                            {
                                IEnumerable <DropdownValueViewModel> communities = dropdownViewModel.Where(c => c.DropdownID == (byte)DropdownFieldTypes.Community).FirstOrDefault().DropdownValuesList;
                                DropdownValueViewModel selectedcommunity         = communities.Where(x => x.DropdownValueID == communityField.DropdownValueID).FirstOrDefault();
                                if (selectedcommunity != null)
                                {
                                    communityDropdownViewModel = new DropdownValueViewModel()
                                    {
                                        AccountID       = viewModel.AccountID,
                                        DropdownID      = (byte)ContactFields.Community,
                                        DropdownValue   = selectedcommunity.DropdownValue,
                                        DropdownValueID = selectedcommunity.DropdownValueID
                                    };
                                }
                            }

                            if (duplicatesResponse != null && duplicatesResponse.Contacts.IsAny())
                            {
                                Log.Informational("Entering into APILeadSubmission Updation");
                                viewModel.ContactID     = duplicatesResponse.Contacts.FirstOrDefault().Id;
                                viewModel.ContactSource = ContactSource.API;
                                var existingContact = duplicatesResponse.Contacts.FirstOrDefault() as Person;

                                var             leadSource = existingContact.LeadSources?.Select(e => e.Id).ToList() ?? new List <short>();
                                PersonViewModel existingContactViewModel = Mapper.Map <Person, PersonViewModel>(existingContact);
                                if (leadSource.IndexOf(leadSourceDropdownViewModel.DropdownValueID) == -1)
                                {
                                    existingContactViewModel.SelectedLeadSource = existingContactViewModel.SelectedLeadSource ?? new List <DropdownValueViewModel>();
                                    existingContactViewModel.SelectedLeadSource = existingContactViewModel.SelectedLeadSource.Append(leadSourceDropdownViewModel);
                                }

                                var community = existingContact.Communities?.Select(e => e.Id).ToList() ?? new List <short>();
                                if (communityDropdownViewModel != null && community.IndexOf(communityDropdownViewModel.DropdownValueID) == -1)
                                {
                                    existingContactViewModel.Communities = existingContactViewModel.Communities ?? new List <DropdownValueViewModel>();
                                    existingContactViewModel.Communities = existingContactViewModel.Communities.Append(communityDropdownViewModel);
                                }

                                PersonViewModel updateViewModel = GetUpdatedPersonData(existingContactViewModel, viewModel);
                                updateViewModel.IncludeInReports = true;
                                UpdatePersonResponse updatePersonResult = _contactService.UpdatePerson(new UpdatePersonRequest()
                                {
                                    PersonViewModel = updateViewModel,
                                    AccountId       = response.APILeadSubmissionViewModel.AccountID,
                                    RequestedBy     = response.APILeadSubmissionViewModel.OwnerID,
                                    RoleId          = roleId,
                                    RequestedFrom   = RequestOrigin.API
                                });

                                if (updatePersonResult.PersonViewModel.ContactID > 0)
                                {
                                    contactId = updatePersonResult.PersonViewModel.ContactID;
                                    _contactRepository.UpdateAPILeadSubmissionData(updatePersonResult.PersonViewModel.ContactID, (byte)SubmittedFormStatus.Completed, "Completed", response.APILeadSubmissionViewModel.APILeadSubmissionID);
                                }
                            }
                            else
                            {
                                Log.Informational("Entering into APILeadSubmission Insertion");
                                viewModel.FirstContactSource = Entities.ContactSource.API;
                                viewModel.CreatedBy          = response.APILeadSubmissionViewModel.OwnerID;
                                viewModel.CreatedOn          = DateTime.Now.ToUniversalTime();
                                viewModel.SelectedLeadSource = new List <DropdownValueViewModel>();
                                viewModel.SelectedLeadSource = viewModel.SelectedLeadSource.Append(leadSourceDropdownViewModel);
                                viewModel.LastUpdatedOn      = DateTime.Now.ToUniversalTime();
                                if (communityField != null && communityDropdownViewModel.DropdownValueID > 0)
                                {
                                    viewModel.Communities = new List <DropdownValueViewModel>();
                                    viewModel.Communities = viewModel.Communities.Append(communityDropdownViewModel);
                                }

                                //if (viewModel.LifecycleStage > 0)
                                //{
                                IEnumerable <DropdownValueViewModel> lifecycles = dropdownViewModel.Where(c => c.DropdownID == (byte)DropdownFieldTypes.LifeCycle).FirstOrDefault().DropdownValuesList;
                                if (!lifecycles.Where(l => l.DropdownValueID == viewModel.LifecycleStage).IsAny())
                                {
                                    viewModel.LifecycleStage = lifecycles.Where(l => l.IsDefault).Select(s => s.DropdownValueID).FirstOrDefault();
                                }
                                //}
                                if (viewModel.Phones.IsAny())
                                {
                                    IEnumerable <DropdownValueViewModel> phones = dropdownViewModel.Where(c => c.DropdownID == (byte)DropdownFieldTypes.PhoneNumberType).FirstOrDefault().DropdownValuesList;
                                    viewModel.Phones.Each(p =>
                                    {
                                        if (!phones.Where(t => t.DropdownValueID == p.PhoneType).IsAny())
                                        {
                                            p.PhoneType = phones.Where(t => t.IsDefault).Select(s => s.DropdownValueID).FirstOrDefault();
                                        }
                                        if (!string.IsNullOrEmpty(p.Number) && (p.Number.Length < 10 || p.Number.Length > 15))
                                        {
                                            p.IsDeleted = true;
                                        }
                                    });

                                    viewModel.Phones = viewModel.Phones.Where(p => p.IsDeleted == false).ToList();
                                }

                                viewModel.IncludeInReports = true;
                                InsertPersonResponse personResult = _contactService.InsertPerson(new InsertPersonRequest()
                                {
                                    PersonViewModel = viewModel,
                                    AccountId       = response.APILeadSubmissionViewModel.AccountID,
                                    RequestedBy     = response.APILeadSubmissionViewModel.OwnerID,
                                    RoleId          = roleId,
                                    RequestedFrom   = RequestOrigin.API
                                });

                                if (personResult.PersonViewModel.ContactID > 0)
                                {
                                    contactId = personResult.PersonViewModel.ContactID;
                                    _contactRepository.UpdateAPILeadSubmissionData(personResult.PersonViewModel.ContactID, (byte)SubmittedFormStatus.Completed, "Completed", response.APILeadSubmissionViewModel.APILeadSubmissionID);
                                }
                            }
                            if (contactId > 0 && viewModel.SelectedLeadSource.IsAny())
                            {
                                //for Indexing Contact.
                                _formRepository.ScheduleIndexing(contactId, IndexType.Contacts, true);

                                if (response.APILeadSubmissionViewModel.FormID != 0)
                                {
                                    _formService.InsertFormSubmissionEntry(contactId,
                                                                           new SubmittedFormViewModel()
                                    {
                                        FormId = response.APILeadSubmissionViewModel.FormID, SubmittedOn = DateTime.UtcNow, SubmittedData = response.APILeadSubmissionViewModel.SubmittedData, AccountId = response.APILeadSubmissionViewModel.AccountID
                                    },
                                                                           viewModel.SelectedLeadSource.FirstOrDefault().DropdownValueID);
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            _contactRepository.UpdateAPILeadSubmissionData(null, (byte)SubmittedFormStatus.Spam, spamRemarks, response.APILeadSubmissionViewModel.APILeadSubmissionID);
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.Data.Clear();
                        ex.Data.Add("APILeadSubmissinID", response.APILeadSubmissionViewModel.APILeadSubmissionID);
                        Log.Error("Error While Processing APILeadSubmission", ex);
                        _contactRepository.UpdateAPILeadSubmissionData(null, (byte)SubmittedFormStatus.Fail, ex.Message, response.APILeadSubmissionViewModel.APILeadSubmissionID);
                    }
                    finally
                    {
                        response = _contactService.GetAPILeadSubMissionData();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error while APILeadSubmission", ex);
            }
        }
Ejemplo n.º 25
0
        protected override void ExecuteInternal(IJobExecutionContext context)
        {
            var      mailChimpCampaignId = string.Empty;
            Campaign campaign            = null;

            var imageHostingUrl           = _jobConfig.ImageHostingServiceUrl;
            var maxHours                  = _jobConfig.RetryMaxHours;
            var timeToRescheduleInMinutes = _jobConfig.RescheduleMinutes;

            try
            {
                //Get the campaign to start processing
                campaign = _campaignService.GetNextCampaignToTriggerAsync().Result.Campaign;

                while (campaign != null)
                {
                    var isDelayed = campaign.CampaignStatus == CampaignStatus.Delayed;
                    Log.Informational(string.Format("Campaign {0} has been picked up for sending.", campaign));

                    //Campaign primary information
                    var serviceProvider = campaign.ServiceProviderID.HasValue
                        ? _communicationService.GetEmailProviderById(new GetServiceProviderByIdRequest {
                        AccountId = campaign.AccountID, ServiceProviderId = campaign.ServiceProviderID.Value
                    }).CampaignEmailProvider
                        : _communicationService.GetDefaultCampaignEmailProvider(new GetDefaultCampaignEmailProviderRequest {
                        AccountId = campaign.AccountID
                    }).CampaignEmailProvider;

                    var emailProvider = campaign.ServiceProviderID.HasValue
                        ? _campaignService.GetEmailProviderById(new GetServiceProviderSenderEmailRequest {
                        AccountId = campaign.AccountID, RequestedBy = campaign.CreatedBy, ServiceProviderID = campaign.ServiceProviderID.Value
                    })
                        : _campaignService.GetDefaultBulkEmailProvider(new GetServiceProviderSenderEmailRequest {
                        AccountId = campaign.AccountID, RequestedBy = campaign.CreatedBy
                    });

                    var accountDomain  = serviceProvider.Account.DomainURL.ToLower();
                    var accountAddress = serviceProvider.Account.Addresses?.Any(a => a.IsDefault) ?? false?
                                         serviceProvider.Account.Addresses.First(a => a.IsDefault).ToString() :
                                             string.Empty;

                    Log.Informational(string.Format("Update campaign status to sending {0}", campaign));
                    var successfulRecipients = new List <int>();

                    //Update campaign to sending status
                    UpdateCampaignTriggerStatus(campaign, isDelayed ? CampaignStatus.Retrying : CampaignStatus.Sending, "The campaign has been picked up for sending", serviceProvider, successfulRecipients, campaign.AccountID, isDelayed);
                    //Campaign Recipients
                    Log.Informational(string.Format("Get recipients info {0}", campaign));
                    try
                    {
                        var campaignRecipientsInfo = _campaignService.GetCampaignRecipientsInfo(new GetCampaignRecipientsRequest {
                            CampaignId = campaign.Id, IsLinkedToWorkflow = false
                        });
                        if (campaignRecipientsInfo.RecipientsInfo.IsAny())
                        {
                            var customFieldsValueOptions = _customFieldRepository.GetCustomFieldsValueOptions(campaign.AccountID).ToArray();

                            var campaignRecipients = campaignRecipientsInfo.RecipientsInfo.Select(c => new EmailRecipient
                            {
                                ContactId           = Convert.ToInt32(c.Value["CONTACTID"]),
                                CampaignRecipientID = Convert.ToInt32(c.Value["CRID"]),
                                EmailId             = c.Value["EMAILID"].ToString().TrimEnd(),
                                ContactFields       = c.Value
                            }).ToList();

                            var    mailRegistration = _mailService.GetMailRegistrationDetails(serviceProvider.LoginToken);
                            string content;
                            if (!string.IsNullOrEmpty(serviceProvider.ImageDomain?.Domain))
                            {
                                mailRegistration.ImageDomain = serviceProvider.ImageDomain.Domain;
                                content = campaign.HTMLContent.Replace(imageHostingUrl, serviceProvider.ImageDomain.Domain);
                                var imageDomainProtocol = serviceProvider.ImageDomain.Domain.Substring(0, serviceProvider.ImageDomain.Domain.IndexOf("://") + 3);
                                var index      = serviceProvider.ImageDomain.Domain.IndexOf("//");
                                var dotCount   = serviceProvider.ImageDomain.Domain.Count(d => d == '.');
                                var linkDomain = serviceProvider.ImageDomain.Domain;
                                if (index >= 0 && dotCount == 1)
                                {
                                    linkDomain = serviceProvider.ImageDomain.Domain.Replace(imageDomainProtocol, imageDomainProtocol + serviceProvider.AccountCode + ".");
                                    content    = content.Replace("http://" + accountDomain, linkDomain).Replace("https://" + accountDomain, linkDomain);
                                }
                            }
                            else
                            {
                                content = campaign.HTMLContent;
                            }

                            content = content.Replace("*|CAMPID|*", campaign.Id.ToString()).Replace("<o:p>", "").Replace("</o:p>", "");
                            campaign.HTMLContent = content;
                            var mailProvider = default(IMailProvider);
                            switch (mailRegistration.MailProviderID)
                            {
                            case LM.MailProvider.MailChimp:
                                mailProvider = new MailChimpCampaign(mailRegistration.APIKey);
                                break;

                            case LM.MailProvider.SmartTouch:
                                mailProvider = new SmartTouchProvider();
                                break;

                            case LM.MailProvider.Undefined:
                            case LM.MailProvider.Smtp:
                            case LM.MailProvider.SendGrid:
                            case LM.MailProvider.CustomSmartTouch:
                            case LM.MailProvider.CustomMailChimp:
                            default:
                                break;
                            }

                            var failedRecipientIDs = new List <Tuple <Exception, int[]> >();
                            try
                            {
                                var numberOfIternations = mailProvider.BatchCount == 0 ? 1 : Math.Ceiling(campaignRecipients.Count / (decimal)mailProvider.BatchCount);
                                #region Batch Process
                                for (int i = 0; i < numberOfIternations; i++)
                                {
                                    var batchRecipientIDs = campaignRecipients
                                                            .Skip(mailProvider.BatchCount * i)
                                                            .Take(mailProvider.BatchCount)
                                                            .Select(r => r.CampaignRecipientID)
                                                            .ToArray();

                                    var batchCount = mailRegistration.MailProviderID == LM.MailProvider.MailChimp ? campaignRecipients.Count() : mailProvider.BatchCount;
                                    Log.Informational("Batch count: " + batchCount);

                                    var recipients = campaignRecipients
                                                     .Skip(mailProvider.BatchCount * i)
                                                     .Take(batchCount)
                                                     .ToList();

                                    var validRecipients = recipients
                                                          .Where(x => _emailValidator.IsValidEmail(x.EmailId))
                                                          .ToList();

                                    try
                                    {
                                        Log.Informational(string.Format("Sending campaign to vmta {0}, iteration {1}", campaign, i));
                                        mailChimpCampaignId = mailProvider.SendCampaign(campaign, validRecipients
                                                                                        , customFieldsValueOptions, serviceProvider.AccountCode, accountAddress, accountDomain
                                                                                        , (emailProvider.SenderEmail != null ? emailProvider.SenderEmail.EmailId : string.Empty), mailRegistration);

                                        _campaignService.UpdateCampaignRecipientsStatus(new UpdateCampaignRecipientsStatusRequest
                                        {
                                            CampaignRecipientIDs = validRecipients.Select(r => r.CampaignRecipientID).ToList(),
                                            Remarks        = "Campaign Sent Successfully",
                                            SentOn         = DateTime.UtcNow,
                                            DeliveredOn    = DateTime.UtcNow,
                                            DeliveryStatus = CampaignDeliveryStatus.Delivered
                                        });

                                        successfulRecipients.AddRange(batchRecipientIDs);

                                        var invalidRecipients = recipients
                                                                .Except(validRecipients)
                                                                .ToList();

                                        if (invalidRecipients.Any())
                                        {
                                            Log.Informational(string.Format("Updating invalid email recipients {0}, count {1}", campaign, invalidRecipients.Count()));
                                            _campaignService.UpdateCampaignRecipientsStatus(new UpdateCampaignRecipientsStatusRequest
                                            {
                                                CampaignRecipientIDs = invalidRecipients.Select(r => r.CampaignRecipientID).ToList(),
                                                Remarks        = "Failed due to invalid email",
                                                SentOn         = DateTime.UtcNow,
                                                DeliveredOn    = DateTime.UtcNow,
                                                DeliveryStatus = CampaignDeliveryStatus.Failed
                                            });
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        failedRecipientIDs.Add(Tuple.Create(ex, batchRecipientIDs));
                                        var message = string.Format("Campaign batch failed - {0} - Iteration {1} - Batch Count {2}", campaign, i, mailProvider.BatchCount);
                                        Log.Critical(message, ex);
                                    }
                                }

                                #endregion

                                var isCampaignPartialFailed = failedRecipientIDs.Any();
                                if (isCampaignPartialFailed &&
                                    campaign.ScheduleTime - campaign.CreatedDate <
                                    TimeSpan.FromMinutes(timeToRescheduleInMinutes))
                                {
                                    _campaignService.ReScheduleCampaign(campaign.Id, DateTime.UtcNow.AddMinutes(5));
                                    UpdateCampaignTriggerStatus(campaign, CampaignStatus.Scheduled, "The campaign has been rescheduled", serviceProvider, successfulRecipients, campaign.AccountID, isDelayed);
                                }
                                else
                                {
                                    foreach (var failedBatch in failedRecipientIDs)
                                    {
                                        _campaignService.UpdateCampaignRecipientsStatus(
                                            new UpdateCampaignRecipientsStatusRequest
                                        {
                                            CampaignRecipientIDs = failedBatch.Item2.ToList(),
                                            Remarks        = string.Format("Exception:{0}", failedBatch.Item1.Message),
                                            SentOn         = DateTime.UtcNow,
                                            DeliveredOn    = DateTime.UtcNow,
                                            DeliveryStatus = CampaignDeliveryStatus.Failed
                                        });
                                    }
                                }

                                var remarks = isCampaignPartialFailed ? "Campaign partially failed due to bad emails" : "The campaign has been picked up for sending";
                                var status  = isCampaignPartialFailed ? CampaignStatus.Delayed :
                                              mailRegistration.MailProviderID == LM.MailProvider.MailChimp ?
                                              CampaignStatus.Analyzing : CampaignStatus.Sent;

                                //if (status == CampaignStatus.Delayed && (campaign.CampaignStatus == CampaignStatus.Scheduled || campaign.CampaignStatus == CampaignStatus.Queued))
                                //{
                                //    SendSupportNotificationEmail(campaign.AccountID, campaign.CreatedBy, campaign.Id, false, campaign.Name);
                                //}
                                //else
                                if (status == CampaignStatus.Delayed &&
                                    campaign.CampaignStatus == CampaignStatus.Delayed &&
                                    (DateTime.UtcNow - campaign.ScheduleTime)?.TotalHours > maxHours)
                                {
                                    status = CampaignStatus.Draft;
                                    //SendSupportNotificationEmail(campaign.AccountID, campaign.CreatedBy, campaign.Id, true, campaign.Name);
                                }

                                _accountService.ScheduleAnalyticsRefresh(campaign.Id, (byte)IndexType.Campaigns);
                                UpdateCampaignTriggerStatus(campaign, status, remarks, serviceProvider, successfulRecipients, campaign.AccountID, isDelayed, mailChimpCampaignId);
                            }
                            catch (Exception ex)
                            {
                                Log.Critical("Campaign batch failed " + campaign, ex);
                                var remarks = "Error while sending campaign, please contact administrator. Additional Info: " + ex;
                                UpdateCampaignTriggerStatus(campaign, CampaignStatus.Failure, remarks, serviceProvider, successfulRecipients, campaign.AccountID, isDelayed);
                            }
                        }
                        else
                        {
                            var remarks = "No campaign recipients found";
                            UpdateCampaignTriggerStatus(campaign, CampaignStatus.Failure, remarks, serviceProvider, successfulRecipients, campaign.AccountID, isDelayed);
                        }

                        //Social posts
                        ShareSocialPost(_socialIntegrationService, campaign);
                    }
                    catch (Exception ex)
                    {
                        var remarks     = "Error while sending campaign, Additional Info: " + ex;
                        var campaignKey = "Campaign";
                        if (!ex.Data.Contains(campaignKey))
                        {
                            ex.Data.Add(campaignKey, campaign.Id.ToString());
                        }

                        _campaignService.UpdateCampaignTriggerStatus(
                            new UpdateCampaignTriggerStatusRequest(campaign.Id)
                        {
                            Status       = CampaignStatus.Delayed,
                            SentDateTime = DateTime.UtcNow,
                            Remarks      = remarks
                        });

                        Log.Error(remarks, ex);
                    }
                    finally
                    {
                        campaign = _campaignService.GetNextCampaignToTriggerAsync().Result.Campaign;
                    }
                }
                AnalizeMailChimpCampaigns();
            }
            catch (Exception ex)
            {
                ExceptionHandler.Current.HandleException(ex, DefaultExceptionPolicies.LOG_ONLY_POLICY);
                if (campaign != null)
                {
                    var remarks = "Error while sending campaign, please contact administrator. Additional Info: " + ex;
                    _campaignService.UpdateCampaignTriggerStatus(new UpdateCampaignTriggerStatusRequest(campaign.Id)
                    {
                        Status       = CampaignStatus.Failure,
                        SentDateTime = DateTime.UtcNow,
                        Remarks      = remarks
                    });
                }
            }
        }
 public void TestBasicEmails()
 {
     Assert.True(validator.IsValidEmail("*****@*****.**"));
     Assert.False(validator.IsValidEmail("nico.devbit.be"));
     Assert.False(validator.IsValidEmail("@devbit.be"));
     Assert.False(validator.IsValidEmail("nico@devbit"));
 }
Ejemplo n.º 27
0
        public async Task <OmbiIdentityResult> UpdateUser([FromBody] UserViewModel ui)
        {
            if (!EmailValidator.IsValidEmail(ui.EmailAddress))
            {
                return(Error($"The email address {ui.EmailAddress} is not a valid format"));
            }
            if (!CanModifyUser(ui.Claims.Select(x => x.Value)))
            {
                return(Error("You do not have the correct permissions to create this user"));
            }
            // Get the user
            var user = await UserManager.Users.FirstOrDefaultAsync(x => x.Id == ui.Id);

            user.Alias               = ui.Alias;
            user.Email               = ui.EmailAddress;
            user.MovieRequestLimit   = ui.MovieRequestLimit;
            user.EpisodeRequestLimit = ui.EpisodeRequestLimit;
            user.MusicRequestLimit   = ui.MusicRequestLimit;
            var updateResult = await UserManager.UpdateAsync(user);

            if (!updateResult.Succeeded)
            {
                return(new OmbiIdentityResult
                {
                    Errors = updateResult.Errors.Select(x => x.Description).ToList()
                });
            }

            // Get the roles
            var userRoles = await UserManager.GetRolesAsync(user);

            // Am I modifying myself?
            var modifyingSelf = user.UserName.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase);

            foreach (var role in userRoles)
            {
                if (modifyingSelf && role.Equals(OmbiRoles.Admin))
                {
                    // We do not want to remove the admin role from yourself, this must be an accident
                    var claim = ui.Claims.FirstOrDefault(x => x.Value == OmbiRoles.Admin && x.Enabled);
                    ui.Claims.Remove(claim);
                    continue;
                }
                await UserManager.RemoveFromRoleAsync(user, role);
            }

            var result = await AddRoles(ui.Claims, user);

            if (result.Any(x => !x.Succeeded))
            {
                var messages = new List <string>();
                foreach (var errors in result.Where(x => !x.Succeeded))
                {
                    messages.AddRange(errors.Errors.Select(x => x.Description).ToList());
                }

                return(new OmbiIdentityResult
                {
                    Errors = messages
                });
            }
            // Add the quality profiles
            if (ui.UserQualityProfiles != null)
            {
                var currentQualityProfiles = await
                                             _userQualityProfiles.GetAll().FirstOrDefaultAsync(x => x.UserId == user.Id);

                var add = false;
                if (currentQualityProfiles == null)
                {
                    currentQualityProfiles = new UserQualityProfiles
                    {
                        UserId = user.Id
                    };
                    add = true;
                }

                currentQualityProfiles.RadarrQualityProfile      = ui.UserQualityProfiles.RadarrQualityProfile;
                currentQualityProfiles.RadarrRootPath            = ui.UserQualityProfiles.RadarrRootPath;
                currentQualityProfiles.SonarrQualityProfile      = ui.UserQualityProfiles.SonarrQualityProfile;
                currentQualityProfiles.SonarrQualityProfileAnime = ui.UserQualityProfiles.SonarrQualityProfileAnime;
                currentQualityProfiles.SonarrRootPath            = ui.UserQualityProfiles.SonarrRootPath;
                currentQualityProfiles.SonarrRootPathAnime       = ui.UserQualityProfiles.SonarrRootPathAnime;
                if (add)
                {
                    await _userQualityProfiles.Add(currentQualityProfiles);
                }
                await _userQualityProfiles.SaveChangesAsync();
            }


            return(new OmbiIdentityResult
            {
                Successful = true
            });
        }
Ejemplo n.º 28
0
        protected void btnCheck_Click(object sender, EventArgs e)
        {
            string res = EmailValidator.IsValidEmail(TextBox1.Text.Trim());

            Response.Write(res);
        }
Ejemplo n.º 29
0
        public void IsValidEmail_Is_True_Given_Valid_Email(string email)
        {
            var result = _validator.IsValidEmail(email);

            result.Should().BeTrue();
        }
Ejemplo n.º 30
0
 protected void btnCheck_Click(object sender, EventArgs e)
 {
     lblCheckResult.Text = EmailValidator.IsValidEmail(txtCheckEmail.Text.Trim());
 }