Open farzinmonsef opened 1 year ago
@echo OFF @echo Date is %Date% SET DayOfWeek=%Date:~0,3% SET Day=%Date:~7,2% SET Month=%Date:~4,2% SET Year=%Date:~10,4% SET Today=%Date:~10,4%-%Date:~4,2%-%Date:~7,2% @echo Year is %Year%, Month is %Month%, Day is %Day%, DayOfWeek is %DayOfWeek% @echo Today is %Today% rem @echo.
c: cd \work
del /F /Q "c:\work# Bak\Factor%Today%.zip" "C:\Program Files\WinRAR\winrar.exe" a -afzip -r "c:\work# Bak\Factor%Today%" "C:\Work\Factor*.*"
// #region Custom Validation Rules /////////////////////////////////////////////////////////////////////////////////////////////// (function ($, kendo) { $.extend(true, kendo.ui.validator, { rules: { requiredif: function (input) { var tmp = input[0].attributes["data-val-requiredif"]; if (typeof tmp != 'undefined') { var requiredifExists = input[0].attributes["data-val-requiredif"].value; var requirediffield = input[0].attributes["data-val-requiredif-field"].value; var requiredifvalues = input[0].attributes["data-val-requiredif-values"].value; var v = $("input[name=" + requirediffield + "]")[0].value var requiredifvaluesArray = requiredifvalues.split('|'); var match = false; for (var i = 0; i < requiredifvaluesArray.length; i++) { if (requiredifvaluesArray[i] == v) { match = true; break; } } if (match) { if ((input[0].value == '') || (input[0].value == null)) { return false; } } } return true; } }, messages: { requiredif: function (input) { return input[0].attributes["data-val-requiredif"].value; } } }); })(jQuery, kendo); // #endregion //////////////////////////////////////////////////////////////////////////////////////////////////
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc;
namespace FactorData.Models {
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
public string Field { get; set; }
public string Values { get; set; }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "requiredif"
};
rule.ValidationParameters["field"] = Field;
rule.ValidationParameters["values"] = Values;
yield return rule;
}
private const string DefaultErrorMessageFormatString = "The {0} field is required.";
private bool IsValueRequired(string checkValue, Object currentValue)
{
if (checkValue.Equals("!null", StringComparison.InvariantCultureIgnoreCase))
{
return currentValue != null;
}
return checkValue.Equals(currentValue.ToString());
}
protected override ValidationResult IsValid(Object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
System.Type type = instance.GetType();
bool valueRequired = false;
var ValuesArray = Values.Split('|').ToList();
Object propertyValue = type.GetProperty(Field).GetValue(instance, null);
for (int i = 0; i < ValuesArray.Count; i++)
{
valueRequired = IsValueRequired(ValuesArray[i], propertyValue);
if (valueRequired) break;
}
if (valueRequired)
{
return !string.IsNullOrEmpty(Convert.ToString(value))
? ValidationResult.Success
: new ValidationResult(ErrorMessage != "" ? ErrorMessage
: string.Format(DefaultErrorMessageFormatString, context.DisplayName));
}
return ValidationResult.Success;
}
}
}
HierarchicalRequiredIf This example shows how to create RequiredIf attribute of some ViewModel property, based on property of the parent.
Solution applies to .NET Core Razor Pages project, but it can be easily addapted to other types of projects.
Main part of the solution is to connect Parent and Child model.
Child model would have ParentModel property public ContainerViewModel ParentModel { get; set; }
2.This property is set on Parent's getter of child items:
public IList
foreach (var child in this.items) {
if (child.ParentModel == null) {
child.ParentModel = this;
}
}
}
return this.items;
}
set {
this.items = value;
}
}
After this, attribute is applied on child ViewModel property:
[RequiredIfHierarchical(parentProperty: nameof(ContainerViewModel.ItemsMustHaveValues), ignoreValues:new string [] { "False", "" }, ErrorMessage = "Required based on value of parent (ItemsMustHaveValues)")] public int? Value { get; set; }
Code for server side validation is IsValid method of custom attribute RequiredIfHierarchical:
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (value == null) {
var targetObject = validationContext.ObjectInstance;
var parentProperty = targetObject.GetType().GetProperty("ParentModel");
var parentModel = parentProperty.GetValue(targetObject, null);
var otherProperty = parentModel.GetType().GetProperty(OtherProperty);
var otherPropertyValue = otherProperty.GetValue(parentModel, null)?.ToString();
if (IgnoreValues.Any(x => x == otherPropertyValue)) return ValidationResult.Success;
if (!string.IsNullOrWhiteSpace(otherPropertyValue)) {
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
Client side validation can be applied with jquery unobtrusive validation method:
$.validator.addMethod("requiredifhierarchical", function (value, element, params) {
var modelData = element.name.split('.');
modelData = modelData.reverse();
var parentModelName = modelData[2];
var elementOfParentModel = $('#' + parentModelName + "_" + params);
var ignoreElements;
var ignoreEl = $(element).data("val-requiredifhierarchical-ignorevalues");
if (ignoreEl.indexOf(',') !== -1) {
ignoreElements = ignoreEl.split(',');
} else {
ignoreElements = [ignoreEl];
}
var parentValue = elementOfParentModel.val();
if (elementOfParentModel.attr('type') == 'checkbox') {
parentValue = elementOfParentModel.is(":checked");
}
for (i = 0; i < ignoreElements.length; i++) {
if (parentValue == ignoreElements[i]) return true;
}
if (parentValue != '') {
return value != '';
}
return true;
});
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Usage in MeataData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . [UIHint("NumberFormated")] [RequiredIf(Field = "TransType", Values = "5|6|7", ErrorMessage = "Cancel and Retire is required for this Trans Type")] [Display(Name = "Cancel and Retire")] public Nullable CancelandRetire { get; set; } . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . In View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (function ($, kendo) { $.extend(true, kendo.ui.validator, { rules: { requiredif: function (input) { var tmp = input[0].attributes["data-val-requiredif"]; if (typeof tmp != 'undefined') { var requiredifExists = input[0].attributes["data-val-requiredif"].value; var requirediffield = input[0].attributes["data-val-requiredif-field"].value; var requiredifvalues = input[0].attributes["data-val-requiredif-values"].value; var v = $("input[name=" + requirediffield + "]")[0].value var requiredifvaluesArray = requiredifvalues.split('|'); var match = false; for (var i = 0; i < requiredifvaluesArray.length; i++) { if (requiredifvaluesArray[i] == v) { match = true; break; } } if (match) { if ((input[0].value == '') || (input[0].value == null)) { return false; } } } return true; } }, messages: { requiredif: function (input) { return input[0].attributes["data-val-requiredif"].value; } } }); })(jQuery, kendo);
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . RequiredIfAttribute.cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc;
namespace Entitites { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { public string Field { get; set; } public string Values { get; set; }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "requiredif"
};
rule.ValidationParameters["field"] = Field;
rule.ValidationParameters["values"] = Values;
yield return rule;
}
private const string DefaultErrorMessageFormatString = "The {0} field is required.";
private bool IsValueRequired(string checkValue, Object currentValue)
{
if (checkValue.Equals("!null", StringComparison.InvariantCultureIgnoreCase))
{
return currentValue != null;
}
return checkValue.Equals(currentValue.ToString());
}
protected override ValidationResult IsValid(Object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
System.Type type = instance.GetType();
bool valueRequired = false;
var ValuesArray = Values.Split('|').ToList();
Object propertyValue = type.GetProperty(Field).GetValue(instance, null);
for (int i = 0; i < ValuesArray.Count; i++) {
valueRequired = IsValueRequired(ValuesArray[i], propertyValue);
if (valueRequired) break;
}
if (valueRequired)
{
return !string.IsNullOrEmpty(Convert.ToString(value))
? ValidationResult.Success
: new ValidationResult(ErrorMessage != "" ? ErrorMessage
: string.Format(DefaultErrorMessageFormatString, context.DisplayName));
}
return ValidationResult.Success;
}
} }
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
using Microsoft.Ajax.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web;
namespace SouthernCompany.Gas.CSP.Web.CSP { public static class Helper { public static object getFieldValueByNAme(string FldName, Type fieldsType,object fieldsInst) { FieldInfo[] fields = fieldsType.GetFields(BindingFlags.Public | BindingFlags.Instance); //debug.WriteLine("Displaying the values of the fields of {0}:", fieldsType); for (int i = 0; i < fields.Length; i++) { //debug.WriteLine(" {0}:\t'{1}'", fields[i].Name, fields[i].GetValue(fieldsInst)); if (FldName.ToLower() == fields[i].Name.ToLower()) { return (object)fields[i].GetValue(fieldsInst); } } return null; }
}
}
//checking server-side validation if (!ModelState.IsValid) { for (int i = 0; i < ModelState.Values.Count; i++) { if (ModelState.Values.ElementAt(i).Errors.Count > 0) { Debug.WriteLine("Field= " + ModelState.Keys.ElementAt(i));// +" ,Value= "+ startServiceFormData); Debug.WriteLine("ErrorMessage= " + ModelState.Values.ElementAt(i).Errors.ElementAt(0).ErrorMessage); Debug.WriteLine("Exception= " + ModelState.Values.ElementAt(i).Errors.ElementAt(0).Exception); object temp = Helper.getFieldValueByNAme(ModelState.Keys.ElementAt(i), typeof(StartServiceViewModel), startServiceFormData); Debug.WriteLine(ModelState.Keys.ElementAt(i) + "= " + (temp == null? "null": Convert.ToString(temp)));
}
}
}
MVC general EditorTemplates