public override void OnAdded(SPAddFieldOptions op) { using (new EnterExitLogger("CCSCascadedLookupField:OnAdded function")) { base.OnAdded(op); Update(); if (!string.IsNullOrEmpty(AdditionalFields)) { string[] AdditionalFieldsArray = AdditionalFields.Split(new string[] { ";#" }, StringSplitOptions.None); if (AdditionalFieldsArray.Length > 1) { for (int i = 0; i < AdditionalFieldsArray.Length - 1; i += 2) { if (!this.ParentList.Fields.ContainsField(this.Title + " : " + AdditionalFieldsArray[i])) { //create a new field string depLookUp = this.ParentList.Fields.AddDependentLookup(this.Title + " : " + AdditionalFieldsArray[i], this.Id); SPFieldLookup fieldDepLookup = (SPFieldLookup)this.ParentList.Fields.GetFieldByInternalName(depLookUp); if (fieldDepLookup != null) { fieldDepLookup.LookupWebId = this.LookupWebId; fieldDepLookup.LookupField = AdditionalFieldsArray[i + 1]; fieldDepLookup.Update(); } } } } } } }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var additionalFields = AdditionalFields.Split(','); var propValues = new List <object> { value }; foreach (var additionalField in additionalFields) { var prop = validationContext.ObjectType.GetProperty(additionalField); if (prop != null) { var propValue = prop.GetValue(validationContext.ObjectInstance, null); propValues.Add(propValue); } //else //{ // propValues.Add(null); //} } var controllerType = Assembly.GetExecutingAssembly().GetTypes() .FirstOrDefault(d => d.Name.ToLower() == (_controller + "Controller").ToLower()); if (controllerType == null) { return(null); } var instance = Activator.CreateInstance(controllerType); var method = controllerType.GetMethod(_action); if (method == null) { return(null); } var response = method.Invoke(instance, propValues.ToArray()); if (!(response is JsonResult)) { return(null); } var isAvailable = false; var json = response as JsonResult; bool.TryParse(json.Data.ToString(), out isAvailable); return(isAvailable ? null : new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); }
/// <summary> /// Overridden IsValid function /// </summary> /// <param name="value"></param> /// <param name="validationContext"></param> /// <returns></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string connection = OtherConfig.CosSSMSConnString; DbContextOptions <CosDbContext> dbContextOption = new DbContextOptions <CosDbContext>(); DbContextOptionsBuilder <CosDbContext> dbContextOptionBuilder = new DbContextOptionsBuilder <CosDbContext>(dbContextOption); CosDbContext dbContext = new CosDbContext(dbContextOptionBuilder.UseSqlServer(connection).Options); // Find the controller passed in constructor var controller = GetControllerList().FirstOrDefault(x => x.Name == string.Format("{0}Controller", this.RouteData["controller"])); if (controller == null) { // Default behavior of IsValid when no controller is found. return(ValidationResult.Success); } List <Type> proTypeList = new List <Type>() { value.GetType() }; List <object> proList = new List <object>() { value }; if (!string.IsNullOrWhiteSpace(AdditionalFields)) { var fields = AdditionalFields.Split(',', StringSplitOptions.RemoveEmptyEntries); proTypeList.AddRange(validationContext.ObjectType.GetProperties().Where(info => fields.Any(s => info.Name.Contains(s))).Select(info => info.PropertyType)); proList.AddRange(validationContext.ObjectType.GetProperties().Where(info => fields.Any(s => info.Name.Contains(s))).Select(info => info.GetValue(validationContext.ObjectInstance))); } // Find the Method passed in constructor var mi = controller.GetMethod(this.RouteData["action"].ToString(), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, proTypeList.ToArray(), null); if (mi == null) { // Default behavior of IsValid when action not found return(ValidationResult.Success); } // Create instance of the controller to be able to call non static validation method var instance = Activator.CreateInstance(controller, dbContext); // invoke the method on the controller with value and "AdditionalFields" JsonResult result = mi.Invoke(instance, proList.ToArray()) is Task <object> task ? (JsonResult)task.Result : (JsonResult)mi.Invoke(instance, proList.ToArray()); // Return success or the error message string from CustomRemoteAttribute if (!(result.Value is string errorMessaqe)) { bool isValid; try { isValid = (bool)result.Value; } catch (Exception) { isValid = false; } return(isValid ? ValidationResult.Success : new ValidationResult(base.ErrorMessageString)); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var propValues = new List <object> { value }; if (!string.IsNullOrWhiteSpace(AdditionalFields)) { var additionalFields = AdditionalFields.Split(','); propValues.AddRange(additionalFields .Select(additionalField => validationContext.ObjectType.GetProperty(additionalField)) .Where(prop => prop != null) .Select(prop => prop.GetValue(validationContext.ObjectInstance, null))); } else if (propValues.Count == 1 && propValues.First() == null) { return(new ValidationResult("[RemoteClientServerAttribute] Nie można walidować właściwości o wartości null")); } // Pobierz kontroler używając Reflection var controller = Assembly.GetExecutingAssembly().GetTypes() .FirstOrDefault(type => string.Equals(type.Name, $"{RouteData["controller"].ToString()}Controller", StringComparison.CurrentCultureIgnoreCase)); // Pobierz metodę akcji zawierającą logikę walidacji var action = controller?.GetMethods() .FirstOrDefault(method => string.Equals(method.Name, RouteData["action"].ToString(), StringComparison.CurrentCultureIgnoreCase) && method.GetParameters().Select(p => p?.ParameterType).SequenceEqual(propValues?.Select(p => p?.GetType()))); if (action == null) { return(new ValidationResult("[RemoteClientServerAttribute] Wskazana metoda walidacji nie istnieje")); } // Utwórz instancję klasy kontrolera var instance = Activator.CreateInstance(controller); // Wywołaj metodę akcji posiadającą logikę walidacji var response = action.Invoke(instance, propValues.ToArray()); var jsonString = response as string; var jsonResult = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(jsonString); var result = jsonResult["Result"]; var message = jsonResult["Message"] ?? ""; if (result == null) { throw new Exception("[RemoteClientServerAttribute] Wynik metody zwrócił null"); } switch ((ActionStatus)result) { case ActionStatus.Success: { return(ValidationResult.Success); } case ActionStatus.Failure: { return(new ValidationResult(ErrorMessage)); // zwróć wiadomość użytkownika } case ActionStatus.DatabaseError: { return(new ValidationResult(message)); // Zwróć wiadomość serwera } default: throw new ArgumentOutOfRangeException(); } }