예제 #1
0
        /// <summary>
        /// Check if the value is a string and if the length is between Min and Max length
        /// </summary>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <param name="errors"></param>
        /// <returns>true if the check is ok</returns>
        public override bool Check(DSColumn column, object value, Errors errors)
        {
            bool validity = base.Check(column, value, errors);

            if (value == null)
            {
                if (Min > 0)
                {
                    errors.AddField(column.Property.Name, ErrorMin, new[] { $"{{{column.Field}}}", $"{Min}" });
                    validity = false;
                }
            }
            else if (value as string != null)
            {
                string strValue = (value as string).Trim();

                if (strValue.Length < Min)
                {
                    errors.AddField(column.Property.Name, ErrorMin, new[] { $"{{{column.Field}}}", $"{Min}" });
                    validity = false;
                }

                if (strValue.Length > Max)
                {
                    errors.AddField(column.Property.Name, ErrorMax, new[] { $"{{{column.Field}}}", $"{Max}" });
                    validity = false;
                }
            }
            else
            {
                errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", value.ToString() });
            }

            return(validity);
        }
예제 #2
0
        /// <summary>
        /// Check if the value describes an email address
        /// </summary>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <param name="errors"></param>
        /// <returns>true if the check is ok</returns>
        public override bool Check(DSColumn column, object value, Errors errors)
        {
            bool validity = base.Check(column, value, errors);

            if (value == null)
            {
                return(validity);
            }

            if (!(value is string strValue))
            {
                errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", value.ToString() });
                return(false);
            }

            try
            {
                new MailAddress(strValue);
                return(validity);
            }
            catch
            {
                errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", strValue });
                return(false);
            }
        }
예제 #3
0
        public ActionResult ForgetPassword(string login)
        {
            Debug($"Post ~/Administration/User/ForgetPassword({login})");

            // check the value by itself

            Errors errors = new Errors();

            if (string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{USER_LOGIN}" });
            }

            if (errors.HasError)
            {
                // read the multilingual dictionary

                LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);
                ressources.Load(_userManager.Database, 1);

                SetModelState(ModelState, ressources, errors);
                return(View(new UserViewModel(ressources, new UserRecord(), false)));
            }

            // ask for a new password due to forget password

            SendNewPassword(login);

            // Go to SingIn

            return(RedirectToAction("SignIn"));
        }
        /// <summary>
        /// Check if the value is not null and not empty
        /// </summary>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <param name="errors"></param>
        /// <returns>true if the check is ok</returns>
        public override bool Check(DSColumn column, object value, Errors errors)
        {
            bool validity = base.Check(column, value, errors);

            if (value == null)
            {
                errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}" });
                return(false);
            }

            if (value is string strValue && String.IsNullOrWhiteSpace(strValue))
            {
                errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}" });
                return(false);
            }

            return(validity);
        }
예제 #5
0
        /// <summary>
        /// Convert a given value from a record to another type
        /// Record -> Network
        /// </summary>
        /// <param name="value"></param>
        /// <param name="errors">List of errors identified</param>
        /// <param name="conversionOK">return true if the given value can be converted into the target type</param>
        /// <returns>the value converted</returns>
        public object ConvertToJSON(object value, Errors errors, out bool conversionOK)
        {
            // Convert the value if DSFormatAttribute is defined

            foreach (DSFormatAttribute format in Formats)
            {
                try
                {
                    value = format.ConvertToJSON(value);
                }
                catch
                {
                    conversionOK = false;
                    errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                    return(value);
                }
            }

            conversionOK = true;
            return(value);
        }
예제 #6
0
        public ActionResult NewPassword(string key, string login, string newPassword1, string newPassword2)
        {
            Debug($"Post ~/Administration/User/NewPassword({login}, {key})");

            bool loginIncorrect = false;

            // read the multilingual dictionary

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, 1);

            // check the value by itself

            Errors errors = new Errors();

            if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{USER_LOGIN}" });
            }
            else
            {
                // Check if the login exists ...

                UserRecord user = _userManager.GetByLogin(login, false);
                if (user == null || String.IsNullOrEmpty(user.NewPasswordKey) || !user.NewPasswordKey.Equals(key))
                {
                    loginIncorrect = true;
                    errors.AddGlobal("ERR_LOGIN_INCORRECT");
                }
            }

            if (string.IsNullOrWhiteSpace(newPassword1))
            {
                errors.AddField("NewPassword1", "ERR_FIELD_REQUIRED", new object[] { "{USER_NEW_PASSWORD}" });
            }

            if (string.IsNullOrWhiteSpace(newPassword2))
            {
                errors.AddField("NewPassword2", "ERR_FIELD_REQUIRED", new object[] { "{USER_RETYPE_PASSWORD}" });
            }

            if (!loginIncorrect &&
                !string.IsNullOrWhiteSpace(newPassword1) &&
                !string.IsNullOrWhiteSpace(newPassword2) &&
                !newPassword1.Equals(newPassword2))
            {
                errors.AddGlobal("ERR_LOGIN_INCORRECT");
            }

            if (errors.HasError)
            {
                SetModelState(ModelState, ressources, errors);
                return(View(new UserViewModel(ressources, new UserRecord(), false)));
            }

            // Update the password

            try
            {
                _userManager.SetNewPassword(login, newPassword1);
            }
            catch (System.Exception ex)
            {
                Error($"An exception occurs on updating the password: {ex.Message}");
            }

            // Sign out the user and resign the user

            FormsAuthentication.SignOut();
            return(RedirectToAction("SignIn"));
        }
예제 #7
0
        public ActionResult SignIn(string login, string password, bool?rememberMe, string returnUrl)
        {
            // TODO : Nettoyage des traces de cette fonction lors de la résolution de l'anomalie #248

            Debug($"Post ~/Administration/User/SignIn({login}, {password}, {rememberMe}, {returnUrl})");

            // check the value by itself

            Errors errors = new Errors();

            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                Debug($"Login '{login}' or password '{password}' not defined !");

                // no login set

                if (string.IsNullOrWhiteSpace(login))
                {
                    errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{USER_LOGIN}" });
                }

                // no password set

                if (string.IsNullOrWhiteSpace(password))
                {
                    errors.AddField("Password", "ERR_FIELD_REQUIRED", new object[] { "{USER_PASSWORD}" });
                }
            }
            else if (StatusManager.Status == StatusManager.EStatus.STATUS_OK)
            {
                Debug($"Status '{StatusManager.Status}' is OK !");

                // authentication of the user

                UserRecord userAuthenticated = _userManager.Authenticate(login, password);

                if (userAuthenticated != null)
                {
                    FormsAuthentication.SetAuthCookie(userAuthenticated.Id.ToString(), (rememberMe != null && rememberMe.Value));

                    Debug("Authentication OK");

                    if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }

                    return(RedirectToAction("Index"));
                }

                errors.AddGlobal("ERR_LOGIN_INCORRECT");
            }
            else
            {
                Debug($"Status '{StatusManager.Status}' is not OK !");

                // it is due to a upgrading process ... no error because StatusFilterAttribute has already rejected the action

                UserRecord administrator = UserRecord.CreateDefaultAdministrator();

                if (administrator.Login.Equals(login) && administrator.Password.Equals(password))
                {
                    FormsAuthentication.SetAuthCookie(administrator.Id.ToString(), false);
                    return(View("Upgrading", new UserViewModel(new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage),
                                                               administrator,
                                                               true)));
                }

                errors.AddGlobal("ERR_LOGIN_INCORRECT");
            }

            Debug("Authentication fail");

            // load multilingual dictionary

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            if (StatusManager.Status == StatusManager.EStatus.STATUS_OK)
            {
                using (DatabaseContext database = new DatabaseContext())
                    ressources.Load(database, 1);
            }

            // update ModelState on depends on errors

            SetModelState(ModelState, ressources, errors);

            // show the same screen until the user success

            if (StatusManager.Status == StatusManager.EStatus.STATUS_UPGRADING)
            {
                return(View("SignInAdministration", new UserViewModel(ressources,
                                                                      new UserRecord {
                    Login = login, Password = password
                },
                                                                      false,
                                                                      null,
                                                                      rememberMe: rememberMe != null && rememberMe.Value)));
            }

            return(View(new UserViewModel(ressources,
                                          new UserRecord {
                Login = login, Password = password
            },
                                          false,
                                          null,
                                          rememberMe: rememberMe != null && rememberMe.Value)));
        }
예제 #8
0
        /// <summary>
        /// Convert a given value into a value matching within the expected type of the column
        /// Network -> Record
        /// </summary>
        /// <param name="value"></param>
        /// <param name="errors">List of errors identified</param>
        /// <param name="conversionOK">return true if the given value can be converted into the target type</param>
        /// <returns>the value converted</returns>
        public object ConvertFromJSON(object value, Errors errors, out bool conversionOK)
        {
            conversionOK = true;

            // check if the value is Nullable

            if (!IsNullable && value == null)
            {
                errors.AddField(Property.Name, "ERR_FIELD_REQUIRED", new object[] { $"{{{Field}}}" });
                conversionOK = false;
                return(value);
            }

            // Convert the value if DSFormatAttribute is defined

            foreach (DSFormatAttribute format in Formats)
            {
                try
                {
                    value = format.ConvertFromJSON(value);
                }
                catch
                {
                    conversionOK = false;
                    errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                    return(value);
                }
            }

            // Check the type of the property and convert it, if it's necessary

            if (value == null || value.GetType() == Type)
            {
                return(value);
            }

            // To Int

            if (Type == typeof(int))
            {
                // Convert into int

                if (value.GetType() == typeof(bool))
                {
                    return((bool)value ? 1 : 0);
                }

                if (value.GetType() == typeof(string))
                {
                    if (int.TryParse(value as string, out int result))
                    {
                        return(result);
                    }

                    errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                    conversionOK = false;
                    return(value);
                }

                conversionOK = false;
                errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                return(value);
            }

            // To Boolean

            if (Type == typeof(bool))
            {
                if (value.GetType() == typeof(string))
                {
                    string strValue = (value as string).ToUpper().Trim();
                    return(strValue.Equals("TRUE") || strValue.Equals("OK") || strValue.Equals("1"));
                }

                if (value.GetType() == typeof(int))
                {
                    return((int)value != 0);
                }

                conversionOK = false;
                errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                return(value);
            }

            // To String

            if (Type == typeof(string))
            {
                return(value.ToString().Trim());
            }

            // To Enumerable

            if (Type.IsEnum)
            {
                if (value.GetType() == typeof(string))
                {
                    string strValueEnum = (value as string).ToUpper().Trim();

                    int      i           = 0;
                    string[] valueString = Type.GetEnumNames();
                    foreach (var index in Type.GetEnumValues())
                    {
                        if (strValueEnum.Equals(Field + "_" + valueString[i].ToUpper()) ||
                            strValueEnum.Equals(valueString[i].ToUpper()))
                        {
                            return(index);
                        }

                        i++;
                    }
                }
                else if (value.GetType() == typeof(int))
                {
                    int intValueEnum = (int)value;
                    foreach (var index in Type.GetEnumValues())
                    {
                        if ((int)index == intValueEnum)
                        {
                            return(index);
                        }
                    }
                }

                conversionOK = false;
                errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                return(value);
            }

            // To DateTime

            if (Type == typeof(DateTime))
            {
                if (value.GetType() == typeof(string))
                {
                    try
                    {
                        return(Convert.ToDateTime(value as string));
                    }
                    catch
                    {
                        conversionOK = false;
                        errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                        return(value);
                    }
                }

                conversionOK = false;
                errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
                return(value);
            }

            // To Double

            if (Type == typeof(double))
            {
                // Convert into double

                if (value.GetType() == typeof(bool))
                {
                    return((bool)value ? (double)1.0 : (double)0.0);
                }

                if (value.GetType() == typeof(int))
                {
                    return(Convert.ToDouble(value));
                }

                if (value.GetType() == typeof(string))
                {
                    if (double.TryParse(value as string, out double result))
                    {
                        return(result);
                    }
                }

                conversionOK = false;
                errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", "{ERR_FIELD_TYPE}" });
                return(value);
            }

            // To Decimal

            if (Type == typeof(Decimal))
            {
                // Convert into decimal

                if (value.GetType() == typeof(bool))
                {
                    return((bool)value ? (Decimal)1 : (Decimal)0);
                }

                if (value.GetType() == typeof(int))
                {
                    return(Convert.ToDecimal(value));
                }

                if (value.GetType() == typeof(double))
                {
                    return(Convert.ToDecimal(value));
                }

                if (value.GetType() == typeof(string))
                {
                    if (Decimal.TryParse(value as string, out Decimal result))
                    {
                        return(result);
                    }
                }

                conversionOK = false;
                errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", "{ERR_FIELD_TYPE}" });
                return(value);
            }

            // Conversion not implemented !

            conversionOK = false;
            errors.AddField(Property.Name, "ERR_FIELD_BADFORMAT", new object[] { $"{{{Field}}}", value.ToString() });
            return(value);
        }
예제 #9
0
        public ActionResult Update(int id, string name, string login, string email, string address, string comment)
        {
            Debug($"Get ~/Administration/Customer/Update(id={id}, name={name}, login={login}, email={email}, address={address}, comment={comment})");

            // Only for administrator from the first customer (Syncytium)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user) || user.CustomerId != 1)
            {
                return(HttpNotFound());
            }

            // The customer has to exist

            CustomerRecord customer = _userManager.Database.Customer.Find(id);

            if (customer == null)
            {
                return(HttpNotFound());
            }

            // check the value by itself

            Errors errors = new Errors();

            // no name set

            if (string.IsNullOrWhiteSpace(name))
            {
                errors.AddField("Name", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_NAME}" });
            }
            name = name.Trim();

            // no login set

            if (string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_LOGIN}" });
            }
            login = login.Trim();

            // no email set

            if (string.IsNullOrWhiteSpace(email))
            {
                errors.AddField("Email", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_EMAIL}" });
            }
            email = email.Trim();

            // check if the name already exists

            if (_userManager.Database.Customer.Where(c => c.Name.Equals(name) && c.Id != customer.Id).Any())
            {
                errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_NAME}" });
            }

            if (!customer.Login.Equals(login))
            {
                // check if the new login already exists

                bool loginExist = false;
                foreach (UserRecord record in _userManager.Database.User.Where(u => u.Login.Equals(login) && u.CustomerId != customer.Id).ToList())
                {
                    // User deleted ?

                    InformationRecord information = _userManager.Database._Information.FirstOrDefault(info => info.Id == record.Id && info.Table.Equals("User"));
                    if (information == null || information.DeleteTick == null)
                    {
                        loginExist = true;
                        break;
                    }
                }

                if (loginExist)
                {
                    errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_LOGIN}" });
                }
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            if (errors.HasError)
            {
                // update ModelState on depends on errors

                SetModelState(ModelState, ressources, errors);
                return(View(new CustomerViewModel(ressources, user, new CustomerRecord {
                    Name = name, Login = login, Email = email, Address = address, Comment = comment
                })));
            }

            // Update the customer

            Info($"Updating the customer ({customer}) within ('{name}', '{login}', '{email}', '{address}', '{comment}') ...");

            // look for the administrator exists

            UserRecord administrator = null;

            foreach (UserRecord record in _userManager.Database.User.Where(u => u.Login.Equals(customer.Login) && u.CustomerId == customer.Id).ToList())
            {
                // User deleted ?

                InformationRecord information = _userManager.Database._Information.FirstOrDefault(info => info.Id == record.Id && info.Table.Equals("User"));
                if (information == null || information.DeleteTick == null)
                {
                    administrator = record;
                    break;
                }
            }

            bool sendEmail = false;

            if (administrator == null)
            {
                Info($"The administrator '{customer.Login}' was removed!");

                administrator = new UserRecord()
                {
                    Login        = login,
                    Registration = name,
                    Name         = name,
                    Email        = email,
                    Language     = user.Language,
                    CustomerId   = customer.Id
                };
                Info($"Creating a new administrator {administrator} ...");

                _userManager.Database.User.Add(administrator);
                _userManager.Database.SaveChanges();

                sendEmail = true;
            }
            else if (!administrator.Login.Equals(login) || !administrator.Email.Equals(email))
            {
                Info($"The administrator '{administrator}' has to be updated!");

                if (!administrator.Login.Equals(login))
                {
                    administrator.Login = login;
                }

                if (administrator.Registration.Equals(customer.Name))
                {
                    administrator.Registration = name;
                }

                if (administrator.Name.Equals(customer.Name))
                {
                    administrator.Name = name;
                }

                if (!administrator.Email.Equals(email))
                {
                    administrator.Email = email;
                    sendEmail           = administrator.Password == null;
                }

                _userManager.Database.SaveChanges();

                Info($"The administrator '{administrator}' is updated!");
            }
            else
            {
                Debug($"The administrator {administrator} doesn't change");
            }

            // check if the administration module is defined and assigned to the user

            ModuleRecord moduleAdministration = null;

            foreach (ModuleRecord record in _userManager.Database.Module.Where(m => m.Module == ModuleRecord.EModule.Administration &&
                                                                               m.Profile == UserProfile.EUserProfile.Administrator &&
                                                                               m.CustomerId == customer.Id).ToList())
            {
                // Module deleted ?

                InformationRecord information = _userManager.Database._Information.Find("Module", record.Id);

                if (information != null && information.IsDeleted)
                {
                    continue;
                }

                moduleAdministration = record;
                if (!moduleAdministration.Enable)
                {
                    Info($"The module administrator '{moduleAdministration}' is enabled!");
                    moduleAdministration.Enable = true;
                    _userManager.Database.SaveChanges();
                }
            }

            if (moduleAdministration == null)
            {
                Debug($"Creation of the module administrator");
                moduleAdministration = new ModuleRecord()
                {
                    Name       = "Administration",
                    Module     = ModuleRecord.EModule.Administration,
                    Profile    = UserProfile.EUserProfile.Administrator,
                    Enable     = true,
                    CustomerId = customer.Id
                };
                _userManager.Database.Module.Add(moduleAdministration);
                _userManager.Database.SaveChanges();
                Info($"Module({moduleAdministration.Id}) created");
            }

            // check if the module administration is assigned to the administrator

            UserModuleRecord userModuleAdministration = null;

            foreach (UserModuleRecord record in _userManager.Database.UserModule.Where(a => a.ModuleId == moduleAdministration.Id &&
                                                                                       a.UserId == administrator.Id &&
                                                                                       a.CustomerId == customer.Id).ToList())
            {
                // Module deleted ?

                InformationRecord information = _userManager.Database._Information.Find("UserModule", record.Id);

                if (information != null && information.IsDeleted)
                {
                    continue;
                }

                userModuleAdministration = record;
            }

            if (userModuleAdministration == null)
            {
                Debug($"Creation of the association between the user and the module administration");
                userModuleAdministration = new UserModuleRecord()
                {
                    ModuleId   = moduleAdministration.Id,
                    UserId     = administrator.Id,
                    CustomerId = customer.Id
                };
                _userManager.Database.UserModule.Add(userModuleAdministration);
                _userManager.Database.SaveChanges();
                Info($"UserModule({userModuleAdministration.Id}) created");
            }

            // update the customer

            customer.Name    = name;
            customer.Login   = login;
            customer.Email   = email;
            customer.Address = address;
            customer.Comment = comment;

            _userManager.Database.SaveChanges();

            if (sendEmail)
            {
                // send a mail for the new user

                Info($"Sending an email to create the password ...");

                using (UserController controller = new UserController(_userManager))
                    controller.SendNewPassword(administrator.Login);
            }

            Info($"Customer updated ...");

            return(RedirectToAction("Index"));
        }
예제 #10
0
        public ActionResult Add(string name, string login, string email, string address, string comment)
        {
            Debug($"Get ~/Administration/Customer/Add(name={name}, login={login}, email={email}, address={address}, comment={comment})");

            // Only for administrator from the first customer (Syncytium)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user) || user.CustomerId != 1)
            {
                return(HttpNotFound());
            }

            // check the value by itself

            Errors errors = new Errors();

            // no name set

            if (string.IsNullOrWhiteSpace(name))
            {
                errors.AddField("Name", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_NAME}" });
            }
            name = name.Trim();

            // no login set

            if (string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_LOGIN}" });
            }
            login = login.Trim();

            // no email set

            if (string.IsNullOrWhiteSpace(email))
            {
                errors.AddField("Email", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_EMAIL}" });
            }
            email = email.Trim();

            // check if the name already exists

            if (_userManager.Database.Customer.Where(c => c.Name.Equals(name)).Any())
            {
                errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_NAME}" });
            }

            // check if the login already exists

            bool loginExist = false;

            foreach (UserRecord record in _userManager.Database.User.Where(u => u.Login.Equals(login)).ToList())
            {
                // User deleted ?

                InformationRecord information = _userManager.Database._Information.FirstOrDefault(info => info.Id == record.Id && info.Table.Equals("User"));
                if (information == null || information.DeleteTick == null)
                {
                    loginExist = true;
                    break;
                }
            }

            if (loginExist)
            {
                errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_LOGIN}" });
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            if (errors.HasError)
            {
                // update ModelState on depends on errors

                SetModelState(ModelState, ressources, errors);
                return(View(new CustomerViewModel(ressources, user)));
            }

            // Create a new customer

            Info($"Creating of a new customer ('{name}', '{login}', '{email}', '{address}', '{comment}') ...");

            CustomerRecord newCustomer = new CustomerRecord()
            {
                Name    = name,
                Login   = login,
                Email   = email,
                Address = address,
                Comment = comment
            };

            _userManager.Database.Customer.Add(newCustomer);
            _userManager.Database.SaveChanges();

            Info($"Customer created {newCustomer}");

            // Add the parameter "Language.Tick.<customerId>" into the parameter table

            _userManager.Database._Parameter.Add(new ParameterRecord()
            {
                Key = $"Language.Tick.{newCustomer.Id}", Value = "0"
            });

            // Duplicate multilanguage dictionary (from the customer 1 to the new one)

            Info($"Duplicating multilanguage labels ...");

            int nbLabels = 0;

            foreach (LanguageRecord languageRecord in _userManager.Database.Language.Where(l => l.CustomerId == 1).ToList())
            {
                LanguageRecord newLanguageRecord = LanguageRecord.Copy(languageRecord) as LanguageRecord;
                newLanguageRecord.CustomerId = newCustomer.Id;
                _userManager.Database.Language.Add(newLanguageRecord);
                nbLabels++;
            }

            Info($"{nbLabels} labels duplicated");

            // Create the administrator for this new customer

            UserRecord newUser = new UserRecord()
            {
                Login        = login,
                Registration = name,
                Name         = name,
                Email        = email,
                Language     = user.Language,
                CustomerId   = newCustomer.Id
            };

            _userManager.Database.User.Add(newUser);
            _userManager.Database.SaveChanges();
            Info($"Creating a new user {newUser} ...");

            ModuleRecord newModule = new ModuleRecord()
            {
                Name       = "Administration",
                Module     = ModuleRecord.EModule.Administration,
                Profile    = UserProfile.EUserProfile.Administrator,
                Enable     = true,
                CustomerId = newCustomer.Id
            };

            _userManager.Database.Module.Add(newModule);
            _userManager.Database.SaveChanges();
            Info($"Module({newModule.Id}) created");

            UserModuleRecord newUserModule = new UserModuleRecord()
            {
                UserId     = newUser.Id,
                ModuleId   = newModule.Id,
                Default    = true,
                CustomerId = newCustomer.Id
            };

            _userManager.Database.UserModule.Add(newUserModule);
            _userManager.Database.SaveChanges();
            Info($"UserModule({newUserModule.Id}) created");

            // send a mail for the new user

            Info($"Sending an email to create the password ...");

            using (UserController controller = new UserController(_userManager))
                controller.SendNewPassword(newUser.Login);

            Info($"Customer created ...");

            return(RedirectToAction("Index"));
        }
예제 #11
0
        /// <summary>
        /// Check if the value is a decimal within expected digits
        /// </summary>
        /// <param name="column"></param>
        /// <param name="value"></param>
        /// <param name="errors"></param>
        /// <returns>true if the check is ok</returns>
        public override bool Check(DSColumn column, object value, Errors errors)
        {
            Decimal valueToCheck = 0;
            bool    validity     = base.Check(column, value, errors);

            if (value == null)
            {
                return(validity);
            }

            if (_maxValue == 0 && Digit > Precision)
            {
                _maxValue = 10;
                for (int i = Precision + 1; i < Digit; i++)
                {
                    _maxValue *= 10;
                }
                _minValue = -_maxValue;
            }

            if (value as string != null)
            {
                if (!Decimal.TryParse(value as string, out valueToCheck))
                {
                    errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", $"{Digit}", $"{Precision}", $"{value}" });
                    return(false);
                }
            }
            else if (value.GetType() == typeof(double) ||
                     value.GetType() == typeof(decimal) ||
                     value.GetType() == typeof(int) ||
                     value.GetType() == typeof(float))
            {
                valueToCheck = Convert.ToDecimal(value);
            }
            else if (value.GetType() == typeof(bool))
            {
                valueToCheck = (bool)value ? 1 : 0;
            }
            else
            {
                errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", $"{Digit}", $"{Precision}", $"{value}" });
                validity = false;
            }

            if (validity)
            {
                Decimal valueRounded = Math.Round(valueToCheck, Precision);

                if (valueRounded != valueToCheck)
                {
                    errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", $"{Digit}", $"{Precision}", $"{value}" });
                    return(false);
                }

                if (valueToCheck >= _maxValue || valueToCheck <= _minValue)
                {
                    errors.AddField(column.Property.Name, Error, new[] { $"{{{column.Field}}}", $"{Digit}", $"{Precision}", $"{value}" });
                    return(false);
                }
            }

            return(validity);
        }