/// <summary> /// Adds business services to the current service collection. /// </summary> /// <param name="configure">The configure callback.</param> /// <returns>Reference to the current ApiBuilder.</returns> /// <exception cref="InvalidOperationException">If this method /// was already called.</exception> /// <exception cref="ArgumentNullException">Configure is null. /// </exception> public ApiBuilder <TLoggerCategory, TDbContext> AddBusinesServices( Action <IConfiguration> configure) { if (IsInvoked(nameof(AddBusinesServices))) { throw new InvalidOperationException( ServiceResources.Get("ApiBuilder.MethodAlreadyCalled", nameof(AddBusinesServices)) ); } if (configure == null) { throw new ArgumentNullException( UtilResources.Get("ArgumentCanNotBeNull", nameof(configure)) ); } switch (ServiceType) { case ApiServiceType.ServiceHttp: case ApiServiceType.ServiceMock: _services.AddTransient <ApiServiceArgs <TLoggerCategory> >(); break; case ApiServiceType.ServiceEF: _services.AddTransient <ApiServiceArgsEF <TLoggerCategory, TDbContext> >(); break; } configure.Invoke(_config); _invokedMethods.Add(nameof(AddBusinesServices)); return(this); }
// GET: Language public ActionResult setLanguage() { UtilResources.ChangeLanguageTwo(); string url = this.Request.UrlReferrer.AbsolutePath; return(Redirect(url)); }
/// <summary> /// Adds fluent validation to the current service collection. /// </summary> /// <param name="configure">The configure callback.</param> /// <returns>Reference to the current ApiBuilder.</returns> /// <exception cref="InvalidOperationException">If this method /// was already called.</exception> /// <exception cref="ArgumentNullException">Configure is null. /// </exception> public ApiBuilder <TLoggerCategory, TDbContext> AddValidators( Action configure) { if (IsInvoked(nameof(AddValidators))) { throw new InvalidOperationException( ServiceResources.Get("ApiBuilder.MethodAlreadyCalled", nameof(AddValidators)) ); } if (configure == null) { throw new ArgumentNullException( UtilResources.Get("ArgumentCanNotBeNull", nameof(configure)) ); } _services.Configure <ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); configure.Invoke(); _invokedMethods.Add(nameof(AddValidators)); return(this); }
public ActionResult Create(ManagersCooperativesViewModels managerCoop) { if (ModelState.IsValid && validForm(managerCoop)) { // Si la coopérative existe, on ne l'ajoute pas en BD if (managerCoop.manager.IDCooperative == 0 || managerCoop.manager.IDCooperative == null) { db.Cooperative.Add(managerCoop.cooperative); db.SaveChanges(); managerCoop.manager.IDCooperative = managerCoop.cooperative.IDCooperative; } managerCoop.manager.ManagerPassword = UtilResources.EncryptPassword(Request.Form["password1"]); db.Manager.Add(managerCoop.manager); db.SaveChanges(); return(RedirectToAction("Index", "Home")); } if (!ModelState.IsValid) { ModelState.AddModelError("", UtilResources.GetLabel("Tous les champs doivent contenir une valeur")); } return(View(managerCoop)); }
/// <summary> /// Reads an enumeration from this configuration based on the /// enum description. /// </summary> /// <typeparam name="TEnum">Enum type.</typeparam> /// <param name="config">Reference to the current IConfiguration instance. /// </param> /// <param name="key">The key of the configuration section.</param> /// <returns>Enum value.</returns> /// <exception cref="ArgumentNullException">Config is null.</exception> /// <exception cref="ConfigException">Key not found or value is /// invalid.</exception> public static TEnum ReadEnum <TEnum>(this IConfiguration config, string key) where TEnum : struct, IConvertible { if (config == null) { throw new ArgumentNullException( UtilResources.Get("ArgumentCanNotBeNull", nameof(config))); } var value = config[key]; var type = EnumUtility.GetValueFromDescription <TEnum>(value); if (string.IsNullOrEmpty(value)) { throw new ConfigException( ServiceResources.Get("ConfigKeyNotFound", key)); } if (type.Equals(default(TEnum))) { throw new ConfigException( ServiceResources.Get("ConfigValueInvalid", key, value)); } return(type); }
public bool validForm(ManagersCooperativesViewModels managerCoop) { bool valid = true; //validation si les mots de passes sont pareils if (Request.Form["password1"] == "" || Request.Form["password2"] == "" || (Request.Form["password2"] != Request.Form["password1"])) { valid = false; ModelState.AddModelError("", UtilResources.GetLabel("Les mots de passe ne correspondent pas")); } //validation si la cooperative existe déjà dans la base de données if (db.Cooperative.Any(o => o.Name == managerCoop.cooperative.Name)) { //Met à jour les données de la coopérative Cooperative temp = db.Cooperative.Where(o => o.Name == managerCoop.cooperative.Name).First(); managerCoop.manager.IDCooperative = temp.IDCooperative; temp.NoStreet = managerCoop.cooperative.NoStreet; temp.Street = managerCoop.cooperative.Street; temp.PostalCode = managerCoop.cooperative.PostalCode; temp.City = managerCoop.cooperative.City; db.Entry(temp).State = EntityState.Modified; db.SaveChanges(); } //validation pour le courriel if (managerCoop.manager.Email != "" || managerCoop.manager.Email != null) { try { MailAddress mail = new MailAddress(managerCoop.manager.Email); } catch (FormatException) { ModelState.AddModelError("", UtilResources.GetLabel("L'adresse courriel n'est pas valide.")); valid = false; } } else { ModelState.AddModelError("", UtilResources.GetLabel("L'adresse courriel n'est pas valide.")); valid = false; } // On regarde si l'email est déjà en BD if (db.Manager.Any(o => o.Email == managerCoop.manager.Email)) { valid = false; ModelState.AddModelError("", UtilResources.GetLabel("L'adresse courriel est déjà utilisé")); } return(valid); }
public void NonNullFactoryGet() { var currentFactory = UtilResources.Factory; UtilResources.Initialize(new StringLocalizerFactory()); var name = "The database was deleted!"; var resource = UtilResources.Get(name); Assert.AreEqual(name, resource); UtilResources.Initialize(currentFactory); }
public void NonNullFactoryGetWithArgs() { var currentFactory = UtilResources.Factory; UtilResources.Initialize(new StringLocalizerFactory()); var name = "The {0} database couldn´t be deleted!"; var args = "ChuckNorrisFacts"; var resource = UtilResources.Get(name, args); Assert.AreEqual("The ChuckNorrisFacts database couldn´t be deleted!", resource); UtilResources.Initialize(currentFactory); }
public ActionResult Create([Bind(Include = "IDStudent,FirstName,LastName,Email,PhoneNumber,StudentPassword")] Student student) { if (ModelState.IsValid && validForm()) { student.StudentPassword = UtilResources.EncryptPassword(Request.Form["password1"]); db.Student.Add(student); db.SaveChanges(); return(RedirectToAction("Index", "Home")); } if (!ModelState.IsValid) { ModelState.AddModelError("", UtilResources.GetLabel("Tous les champs doivent contenir une valeur")); } return(View(student)); }
/// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="args">Encapsulates the properties to initialize a new /// ApiServiceArgs<TLoggerCategory>.</param> /// <exception cref="ArgumentNullException">Args is null.</exception> public ApiService(ApiServiceArgs <TLoggerCategory> args) { if (args == null) { throw new ArgumentNullException( UtilResources.Get("ArgumentCanNotBeNull", nameof(args))); } _stopWatch = new Stopwatch(); _httpContextAccessor = args.HttpContextAccessor; ServiceProvider = args.ServiceProvider; Config = args.Config; Logger = args.Logger; Mapper = args.Mapper; UtilResources.Initialize(args.StringLocalizerFactory); _stringLocalizer = UtilResources.Factory.Create(typeof(TResources)); }
public static void AddMasterData <TLoggerCategory>(this IServiceCollection services, IConfiguration config) { var serviceType = config.GetServiceType(); switch (serviceType) { case ApiServiceType.ServiceEF: services.AddTransient <IMasterDataService, MasterDataServiceEF <TLoggerCategory> >(); break; case ApiServiceType.ServiceMock: services.AddTransient <IMasterDataService, MasterDataServiceMock <TLoggerCategory> >(); break; default: throw new InjectException( UtilResources.Get("Common.InjectException", nameof(IMasterDataService)) ); } }
/// <summary> /// Reads an object from this configuration by matching property names /// against configuration keys recursively. /// </summary> /// <typeparam name="TObject">The type of the object to be created.</typeparam> /// <param name="config">Reference to the current IConfiguration instance. /// </param> /// <param name="key">The key of the configuration section.</param> /// <returns>Instance of type T.</returns> /// <exception cref="ArgumentNullException">Config is null.</exception> /// <exception cref="ConfigException">Key not found.</exception> public static TObject ReadObject <TObject>(this IConfiguration config, string key) { if (config == null) { throw new ArgumentNullException( UtilResources.Get("ArgumentCanNotBeNull", nameof(config))); } var configSection = config.GetSection(key); if (!configSection.Exists()) { throw new ConfigException( ServiceResources.Get("ConfigKeyNotFound", key) ); } var instance = (TObject)Activator.CreateInstance(typeof(TObject)); configSection.Bind(instance); return(instance); }
/// <summary> /// Gets the string resource with the given name and formatted with /// the supplied arguments. /// </summary> /// <param name="name">The name of the string resource.</param> /// <param name="arguments">The values to format the string with.</param> /// <returns>The formatted string resource.</returns> public static string Get(string name, params object[] arguments) => Localizer?[name, arguments].Value ?? UtilResources.Get(name, arguments);
/// <summary> /// Gets the string resource with the given name. /// </summary> /// <param name="name">The name of the string resource.</param> /// <returns>The string resource.</returns> public static string Get(string name) => Localizer?[name].Value ?? UtilResources.Get(name);
// Valide si les informations entrés par l'utilisateur sont corrects public bool validForm() { bool valid = true; //validation si les mots de passes sont pareils if (Request.Form["password1"] == null || Request.Form["password2"] == null || (Request.Form["password2"] != Request.Form["password1"])) { valid = false; ModelState.AddModelError("", UtilResources.GetLabel("Les mots de passe ne correspondent pas")); } // Numero Telephone validation // L'utilisateur à le choix de ne pas écrire son # de téléphone if (Request.Form["PhoneNumber"] != "") { // À l'aide des Regular Expression, on regarde si le numéro de téléphone est du bon format. string strIn = Request.Form["PhoneNumber"]; string re1 = @"^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$"; // RegEx du numero de telephone Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline); Match m = r.Match(strIn); if (m.Success) { String int1 = m.Groups[1].ToString(); Console.Write("(" + int1.ToString() + ")" + "\n"); // On doit également vérifier si le numéro n'est pas déjà dans la base de donnée if (db.Student.Any(o => o.PhoneNumber == strIn)) { valid = false; ModelState.AddModelError("", UtilResources.GetLabel("Ce numéro de téléphone est déjà utilisé")); } } else { valid = false; ModelState.AddModelError("", UtilResources.GetLabel("Numéro de téléphone doit être sous le format: xxx-xxx-xxxx")); } } // Email validation string strEmail = Request.Form["Email"]; if (strEmail != "" || strEmail != null) { try { MailAddress mail = new MailAddress(strEmail); } catch (FormatException) { ModelState.AddModelError("", UtilResources.GetLabel("L'adresse courriel n'est pas valide.")); valid = false; } } else { ModelState.AddModelError("", UtilResources.GetLabel("L'adresse courriel n'est pas valide.")); valid = false; } // On regarde si l'email est déjà en BD if (db.Student.Any(o => o.Email == strEmail)) { valid = false; ModelState.AddModelError("", UtilResources.GetLabel("L'adresse courriel est déjà utilisé")); } return(valid); }
/// <summary> /// Paginates this query according to request params. /// </summary> /// <typeparam name="TItem">The entity type in the query collection.</typeparam> /// <param name="query">Object against we are querying.</param> /// <param name="request">Object with the request arguments.</param> /// <returns>The task object representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException">Request is null.</exception> public static async Task <PaginationResult <TItem> > PaginateAsync <TItem>( this IQueryable <TItem> query, PaginationRequest request) { if (request == null) { throw new ArgumentNullException( UtilResources.Get("ArgumentCanNotBeNull", nameof(request))); } int count; try { count = await query.CountAsync(); } catch (InvalidOperationException) { count = query.Count(); } if (!string.IsNullOrEmpty(request.SortKey)) { query = request.IsAscending ? query.OrderBy(request.SortKey) : query.OrderByDescending(request.SortKey); } query = query .Skip((request.PageNumber - 1) * request.PageSize) .Take(request.PageSize); List <TItem> items; try { items = await query.ToListAsync(); } catch (InvalidOperationException) { items = query.ToList(); } var sorDirection = request.IsAscending ? SortDirectionType.Asc.GetDescription() : SortDirectionType.Desc.GetDescription(); var pageCount = (int)Math.Ceiling(count / (double)request.PageSize); var result = new PaginationResult <TItem> { PageNumber = request.PageNumber, PageSize = request.PageSize, SortKey = request.SortKey, SortDirection = sorDirection, Items = items, RecordCount = count, PageCount = pageCount }; return(result); }