public async Task<ResponseBool> SalesmanUserAddAsync(DistributorSalesmanItem distributorSalesmanItem,
     UserItem userItem)
 {
     ResponseBool _response = new ResponseBool { Success = false, ErrorInfo = "" };
     bool success = false;
     string url = string.Format("api/distributorservices/salesmanuseradd");
     var httpClient = setupHttpClient();
     httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     try
     {
         SalesmanAddDTO dto = new SalesmanAddDTO { Salesman = distributorSalesmanItem, User = userItem };
         var response = await httpClient.PostAsJsonAsync(url, dto);
         _response = await response.Content.ReadAsAsync<ResponseBool>();
         if (response.IsSuccessStatusCode)
             success = true;
     }
     catch (Exception ex)
     {
         _log.Error("Failed to add salesman /user", ex);
     }
     return _response;
 }
        async void ResetUserPassword()
        {
            if (!CanAddUser)
            {
                MessageBox.Show("Sorry, you do not have sufficient rights to perform this action", "Distributr: Reset User Password", MessageBoxButton.OK);
                return;
            }
            if (MessageBox.Show(GetLocalText("sl.users.resetpwd.messagebox.prompt")//"Are you sure you want to reset this user's password?"
                , GetLocalText("sl.users.resetpwd.messagebox.caption")//"Confirm Reset Password"
                , MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;
            using (StructureMap.IContainer c = NestedContainer)
            {
                string newPassword = "******";
                User user = PagedList.FirstOrDefault(p=>p.Id==SelectedUser.Id);
                IDistributorServiceProxy proxy = Using<IDistributorServiceProxy>(c);
                ResponseBool response = null;
                if (user != null)
                {
                    string pwd = Using<IOtherUtilities>(c).MD5Hash(newPassword);

                    var newUser = new UserItem
                                      {
                                          Username = user.Username,
                                          PIN = user.PIN,
                                          Mobile = user.Mobile,
                                          MasterId = user.Id,
                                          UserType = (int) user.UserType,
                                          UserRoles = user.UserRoles,
                                          DateLastUpdated = DateTime.Now,
                                          CostCenterID = user.CostCentre,
                                          StatusId = (int) EntityStatus.Active,
                                          TillNumber = user.TillNumber,
                                          CostCentreCode = Using<ICostCentreRepository>(c).GetById(user.CostCentre).CostCentreCode,
                                          Password = pwd
                                      };

                    response = await proxy.UserUpdateAsync(newUser);
                    MessageBox.Show(response.ErrorInfo, "Distributr: Manage Users", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                }
            }
        }
        public async Task<ResponseBool> UserAddAsync(UserItem userItem)
        {
            ResponseBool _response = new ResponseBool { Success = false, ErrorInfo = "" };
            string url = string.Format("api/distributorservices/useradd");
            var httpClient = setupHttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                var response = await httpClient.PostAsJsonAsync(url, userItem);
                _response = await response.Content.ReadAsAsync<ResponseBool>();
            }
            catch (Exception ex)
            {
                _response.ErrorInfo = "Error: An error occurred when adding user.\n" + ex.Message;
                _log.Error("Error: An error occurred when adding user.", ex);
            }

            return _response;
        }
 public async Task<ResponseBool> UserUpdateAsync(UserItem userItem)
 {
     ResponseBool _response = new ResponseBool { Success = false, ErrorInfo = "" };
     bool success = false;
     string url = string.Format("api/distributorservices/userupdate");
     var httpClient = setupHttpClient();
     httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     try
     {
         var response = await httpClient.PostAsJsonAsync(url, userItem);
         _response = await response.Content.ReadAsAsync<ResponseBool>();
         if (response.IsSuccessStatusCode)
             success = true;
     }
     catch (Exception ex)
     {
         _response.ErrorInfo = "Failed to update user\nCause:" + ex.Message;
         _log.Error("Failed to update user", ex);
     }
     return _response;
 }
 public Task<ResponseBool> AgriUserAddAsync(UserItem user, ContactItem contact, List<RouteItem> routes)
 {
     throw new NotImplementedException();
 }
        private async void DoResetUserUserword()
        {
            if (SelectedUserItem == null) return;
            using (StructureMap.IContainer c = NestedContainer)
            {
                string newPassword = "******";
                User user = Using<IUserRepository>(c).GetById(SelectedUserItem.Id);
                IDistributorServiceProxy proxy = Using<IDistributorServiceProxy>(c);
                ResponseBool response = null;
                if (user != null)
                {
                    string pwd = Using<IOtherUtilities>(c).MD5Hash(newPassword);

                    var newUser = new UserItem
                    {
                        Username = user.Username,
                        PIN = user.PIN,
                        Mobile = user.Mobile,
                        MasterId = user.Id,
                        UserType = (int)user.UserType,
                        UserRoles = user.UserRoles,
                        DateLastUpdated = DateTime.Now,
                        CostCenterID = user.CostCentre,
                        StatusId = (int)EntityStatus.Active,
                        TillNumber = user.TillNumber,
                        CostCentreCode = Using<ICostCentreRepository>(c).GetById(user.CostCentre).CostCentreCode,
                        Password = pwd
                    };

                    response = await proxy.UserUpdateAsync(newUser);
                    MessageBox.Show(response.ErrorInfo, "Agrimangr: Manage Users", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                }
            }
        }
 UserItem CreateUserItem(Guid costCentreId)
 {
     UserItem userItem = new UserItem()
     {
         MasterId = User.Id,
         Username = User.Username,
         UserType = (int)User.UserType,
         TillNumber = User.TillNumber,
         Mobile = User.Mobile,
         PIN = User.PIN,
         CostCenterID = costCentreId,
         StatusId = (int)EntityStatus.Active,
         DateCreated = DateTime.Now,
         DateLastUpdated = DateTime.Now,
         Password = User.Password, 
         CostCentreCode = Code,
     };
     return userItem;
 }
        public async void Save()
        {
            using (StructureMap.IContainer c = NestedContainer)
            {
                ResponseBool response = null;
                IDistributorServiceProxy proxy = Using<IDistributorServiceProxy>(c);
                IConfigService _configService = Using<IConfigService>(c);
                if(!ChangingPassword)
                if (Id != Guid.Empty && !IsValid())
                    return;
                if (SelectedUserType == null || SelectedUserType == UserType.None)
                {
                    MessageBox.Show(GetLocalText("sl.user.edit.validate.usertype") /*"Select user type"*/,
                                    "Distributr: Invalid Field(s)", MessageBoxButton.OK);
                    return;
                }
                showActionResultMsg = true;

                #region New User

                var _userRoles =  userRoles.Select(n =>n).ToList();
                if (Id == Guid.Empty)
                {
                    NewPassword = "******";
                    var newUser = new UserItem
                                      {
                                          MasterId = Guid.NewGuid(),
                                          Username = UserName,
                                          PIN = PIN,
                                          Mobile = Mobile,
                                          Password = Using<IOtherUtilities>(c).MD5Hash(NewPassword),
                                          UserType = (int) SelectedUserType,
                                          UserRoles = _userRoles,
                                          StatusId = (int) EntityStatus.Active,
                                          DateCreated = DateTime.Now,
                                          DateLastUpdated = DateTime.Now,
                                          TillNumber = TillNumber,
                                          CostCenterID = _configService.Load().CostCentreId,
                                          CostCentreCode = Code,
                                           SalesmanType =(int) SelectedSalesmanType,
                                      };
                    response = await proxy.UserAddAsync(newUser);
                    AuditLogEntry = string.Format("Created New User: {0}; Code: {1}; And User Type", UserName,
                                                  SelectedUserType);
                    Using<IAuditLogWFManager>(c).AuditLogEntry("User Administration", AuditLogEntry);
                }

                    #endregion

                #region Update Existing

                else //updating existing
                {
                    var newUser = new UserItem
                                      {
                                          Username = UserName,
                                          PIN = PIN,
                                          Mobile = Mobile,
                                          MasterId = Id,
                                          UserType = (int) SelectedUserType,
                                          UserRoles = _userRoles,
                                          DateLastUpdated = DateTime.Now,
                                          CostCenterID = CostCenterID,
                                          StatusId = (int) EntityStatus.Active,
                                          TillNumber = TillNumber,
                                          CostCentreCode = Code,
                                          SalesmanType =(int) SelectedSalesmanType,
                                          PasswordChanged = 1,
                                          
                                      };

                    if (ChangingPassword)
                    {
                        var user = Using<IUserRepository>(c).GetById(Id);
                      if(ConfirmPassword.ToLower()==NewPassword.ToLower())
                      {
                          if (user != null && user.Password == Using<IOtherUtilities>(c).MD5Hash(OldPassword))
                          {
                              newUser.Password = Using<IOtherUtilities>(c).MD5Hash(NewPassword);
                          }
                          else
                          {
                              OldPassword = string.Empty;
                              NewPassword = string.Empty;
                              ConfirmPassword = string.Empty;
                              MessageBox.Show("Old password mismatch", "Distributr Error");
                              return;
                          }
                      }
                      else
                      {
                          OldPassword = string.Empty;
                          NewPassword = string.Empty;
                          ConfirmPassword = string.Empty;
                          MessageBox.Show("Confirm password and new password mismatch", "Distributr Error");
                          return;
                      }
                    }
                   
                    else
                        newUser.Password = Password;
                    response = await proxy.UserUpdateAsync(newUser);

                    AuditLogEntry = string.Format("Updated User: {0}; Code: {1};", UserName, SelectedUserType);
                    Using<IAuditLogWFManager>(c).AuditLogEntry("User Administration", AuditLogEntry);
                }

                MessageBox.Show(response.ErrorInfo, "Distributr: Manage Users", MessageBoxButton.OK, MessageBoxImage.Information);

                if (response.Success)
                {
                    ConfirmNavigatingAway = false;
                    SendNavigationRequestMessage(new Uri(@"\views\CommodityReception\AwaitingReception.xaml", UriKind.Relative));
                }

                #endregion
            }
        }
        public HttpResponseMessage UserUpdate(UserItem userItem)
        {
            var response = new ResponseBool { Success = false };
            User user = null;
            DistributorSalesman ds = null;
            try
            {
                user = _userRepository.GetById(userItem.MasterId); 
                user.CostCentre = userItem.CostCenterID;
                //For salesman
                if (userItem.UserType == (int) UserType.DistributorSalesman)
                {
                    ds = _costCentreRepository.GetById(user.CostCentre) as DistributorSalesman;
                    if (ds == null)
                    {
                        ds = _costCentreFactory.CreateCostCentre(Guid.NewGuid(), CostCentreType.DistributorSalesman,
                                                                 _costCentreRepository.GetById(userItem.CostCenterID))
                             as DistributorSalesman;
                    }
                    ds.Type = (DistributorSalesmanType)userItem.SalesmanType;
                    ds.Name = userItem.Username;
                    ds.CostCentreCode = userItem.CostCentreCode;
                    ds._SetStatus(EntityStatus.Active);

                    user.CostCentre = _costCentreRepository.Save(ds);
                }
                user.Username = userItem.Username;
                user.Password = userItem.Password;
                user.PIN = userItem.PIN;
                user.Mobile = userItem.Mobile;
                user.UserType = (UserType)userItem.UserType;
                user.TillNumber = userItem.TillNumber;
                user.PassChange = userItem.PasswordChanged;
                _userRepository.Save(user);
                response.Success = true;
                response.ErrorInfo = "Successfully updated user " + user.Username;
            }
            catch (DomainValidationException dve)
            {
                string errorMsg = dve.ValidationResults.Results.Aggregate("Error: Invalid user fields.\n",
                                                                          (current, msg) =>
                                                                          current + ("\t- " + msg.ErrorMessage + "\n"));
                response.ErrorInfo = errorMsg;
                _log.Error(errorMsg, dve);
            }
            catch (Exception ex) //any other
            {
                response.ErrorInfo = "Error: An error occurred when updating the user.\nCause:"+ex.Message;
                _log.Error("Error: An error occurred when updating the user.", ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK, response);

        }