コード例 #1
0
ファイル: NotNullValidator.cs プロジェクト: davinx/himedi
 protected internal override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if ((null == objectToValidate) == !base.Negated)
     {
         base.LogValidationResult(validationResults, this.GetMessage(objectToValidate, key), currentTarget, key);
     }
 }
		/// <summary>
		/// Does the validate.
		/// </summary>
		/// <param name="objectToValidate">The object to validate.</param>
		/// <param name="currentTarget">The current target.</param>
		/// <param name="key">The key.</param>
		/// <param name="validationResults">The validation results.</param>
		protected override void DoValidate(ModelBusReference objectToValidate, object currentTarget, string key, ValidationResults validationResults)
		{
			// store default message (in case the error comes from a DC element) and set our new message
			dcModelMessageTemplate = this.MessageTemplate;
			this.MessageTemplate = currentMessageTemplate;			
			
			// Validate cross model references
            base.DoValidate(objectToValidate, currentTarget, key, validationResults);

			if (!validationResults.IsValid)
			{
				return;
			}

            using (ModelBusReferenceResolver resolver = new ModelBusReferenceResolver())
            {
                ModelElement referencedElement = resolver.Resolve(objectToValidate);

                if (referencedElement != null)
                {
                    DataContractModel dcm = referencedElement.Store.ElementDirectory.FindElements<DataContractModel>()[0];
                    if (dcm.ImplementationTechnology == null ||
                        String.IsNullOrWhiteSpace(dcm.ProjectMappingTable) ||
                        !dcm.ImplementationTechnology.Name.Equals(GetItName(currentTarget),StringComparison.OrdinalIgnoreCase))
                    {
                        validationResults.AddResult(
                            new ValidationResult(String.Format(CultureInfo.CurrentUICulture, this.dcModelMessageTemplate, ValidatorUtility.GetTargetName(currentTarget)), currentTarget, key, String.Empty, this));
                    }
                }
            }
		}
コード例 #3
0
 public void DoValidateSubmit(ValidationResults results)
 {
     if (this.Modes.Count == 0)
         results.AddResult(new ValidationResult("At least one ground transportation mode is required.",
             typeof(Ground),
             "", "", null));
 }
 public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if ((string)objectToValidate != "test value")
     {
         LogValidationResult(validationResults, "Invalid value", currentTarget, key);
     }
 }
コード例 #5
0
 /// <summary>
 /// Implements the validation logic for the receiver.
 /// </summary>
 /// <param name="objectToValidate">The object to validate.</param>
 /// <param name="currentTarget">The object on the behalf of which the validation is performed.</param>
 /// <param name="key">The key that identifies the source of <paramref name="objectToValidate"/>.</param>
 /// <param name="validationResults">The validation results to which the outcome of the validation should be stored.</param>
 public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if (objectToValidate != null)
     {
         this.wrappedValidator.DoValidate(objectToValidate, currentTarget, key, validationResults);
     }
 }
		public void DoValidateCollectionItemFailsForDuplicateNamedElements()
		{
			Store store = new Store(typeof(CoreDesignSurfaceDomainModel), typeof(ServiceContractDslDomainModel));
			ServiceContractModel model;

			using (Transaction transaction = store.TransactionManager.BeginTransaction())
			{
				string name = "Duplicate Name";
				model = store.ElementFactory.CreateElement(ServiceContractModel.DomainClassId) as ServiceContractModel;

				Message contract = store.ElementFactory.CreateElement(Message.DomainClassId) as Message;
				contract.Name = name;

				MessagePart part = store.ElementFactory.CreateElement(PrimitiveMessagePart.DomainClassId) as PrimitiveMessagePart;
				part.Name = name;

				contract.MessageParts.Add(part);

				TestableMessagePartElementCollectionValidator target = new TestableMessagePartElementCollectionValidator();

				ValidationResults results = new ValidationResults();
				target.TestDoValidateCollectionItem(part, contract, String.Empty, results);

				Assert.IsFalse(results.IsValid);

				transaction.Commit();
			}
		}
		public void DoValidateCollectionItemSucceedsForUniqueNamedElements()
		{
			Store store = new Store(typeof(CoreDesignSurfaceDomainModel), typeof(ServiceContractDslDomainModel));
			ServiceContractModel model;

			using (Transaction transaction = store.TransactionManager.BeginTransaction())
			{
				model = store.ElementFactory.CreateElement(ServiceContractModel.DomainClassId) as ServiceContractModel;

				ServiceContract contract = store.ElementFactory.CreateElement(ServiceContract.DomainClassId) as ServiceContract;
				contract.Name = "Contract Name";

				Operation part = store.ElementFactory.CreateElement(Operation.DomainClassId) as Operation;
				part.Name = "Part Name";

				contract.Operations.Add(part);

				TestableOperationElementCollectionValidator target = new TestableOperationElementCollectionValidator();

				ValidationResults results = new ValidationResults();
				target.TestDoValidateCollectionItem(part, contract, String.Empty, results);

				Assert.IsTrue(results.IsValid);

				transaction.Commit();
			}
		}
コード例 #8
0
 protected internal override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if (objectToValidate != null)
     {
         IEnumerable enumerable = objectToValidate as IEnumerable;
         if (enumerable != null)
         {
             foreach (object obj2 in enumerable)
             {
                 if (obj2 != null)
                 {
                     if (this.targetType.IsAssignableFrom(obj2.GetType()))
                     {
                         this.targetTypeValidator.DoValidate(obj2, obj2, null, validationResults);
                     }
                     else
                     {
                         base.LogValidationResult(validationResults, Resources.ObjectCollectionValidatorIncompatibleElementInTargetCollection, obj2, null);
                     }
                 }
             }
         }
         else
         {
             base.LogValidationResult(validationResults, Resources.ObjectCollectionValidatorTargetNotCollection, currentTarget, key);
         }
     }
 }
コード例 #9
0
        /// <summary>
        /// Applies the validation logic represented by the receiver on an object, 
        /// adding the validation results to <paramref name="validationResults"/>.
        /// </summary>
        /// <param name="target">The object to validate.</param>
        /// <param name="validationResults">The validation results to which the outcome of the validation should be stored.</param>
        public void Validate(object target, ValidationResults validationResults)
        {
            if (null == validationResults)
                throw new ArgumentNullException("validationResults");

            DoValidate(target, target, null, validationResults);
        }
コード例 #10
0
        public void Validate(ValidationResults results)
        {
            string msg = string.Empty;

            if (!DateDue.HasValue)
            {
                if (OnOrder > 0)
                {
                    msg = "Must provide a delivery due date for stock on back order.";
                    results.AddResult(new ValidationResult(msg, this, "ProductSelfValidation", "", null));
                }
            }
            else
            {
                if (OnOrder == 0)
                {
                    msg = "Can specify delivery due date only when stock is on back order.";
                    results.AddResult(new ValidationResult(msg, this, "ProductSelfValidation", "", null));
                }
            }

            if (InStock + OnOrder > 100)
            {
                msg = "Total inventory (in stock and on order) cannot exceed 100 items.";
                results.AddResult(new ValidationResult(msg, this, "ProductSelfValidation", "", null));
            }
        }
コード例 #11
0
 /// <summary>
 /// Validates by invoking the self validation method configured for the validator.
 /// </summary>
 /// <param name="objectToValidate">The object to validate.</param>
 /// <param name="currentTarget">The object on the behalf of which the validation is performed.</param>
 /// <param name="key">The key that identifies the source of <paramref name="objectToValidate"/>.</param>
 /// <param name="validationResults">The validation results to which the outcome of the validation should be stored.</param>
 /// <remarks>
 /// A validation failure will be logged by the validator when the following conditions are met without
 /// invoking the self validation method:
 /// <list type="bullet">
 /// <item><term><paramref name="objectToValidate"/> is <see langword="null"/>.</term></item>
 /// <item><term><paramref name="objectToValidate"/> is an instance of a type not compatible with the declaring type for the 
 /// self validation method.</term></item>
 /// </list>
 /// <para/>
 /// A validation failure will also be logged if the validation method throws an exception.
 /// </remarks>
 public override void DoValidate(object objectToValidate,
     object currentTarget,
     string key,
     ValidationResults validationResults)
 {
     if (null == objectToValidate)
     {
         this.LogValidationResult(validationResults, Resources.SelfValidationValidatorMessage, currentTarget, key);
     }
     else if (!this.methodInfo.DeclaringType.IsAssignableFrom(objectToValidate.GetType()))
     {
         this.LogValidationResult(validationResults, Resources.SelfValidationValidatorMessage, currentTarget, key);
     }
     else
     {
         try
         {
             this.methodInfo.Invoke(objectToValidate, new object[] { validationResults });
         }
         catch (Exception)
         {
             this.LogValidationResult(validationResults, Resources.SelfValidationMethodThrownMessage, currentTarget, key);
         }
     }
 }
コード例 #12
0
		protected override void DoValidate(object objectToValidate, object currentObject, string key, ValidationResults validateResults)
		{
			string typeString = (string)objectToValidate;
			string messageTemplate = string.IsNullOrEmpty(this.MessageTemplate) ? "{0}包含无效或重复的的管理范围类别字符串:{1}" : this.MessageTemplate;
			string[] parts = typeString.Split(AUCommon.Spliter, StringSplitOptions.RemoveEmptyEntries);

			// 准备有效项的集合
			HashSet<string> effected = new HashSet<string>();
			HashSet<string> repeated = new HashSet<string>();
			foreach (var item in SchemaInfo.FilterByCategory("AUScopeItems"))
				effected.Add(item.Name);

			// 检查有效项
			foreach (var item in parts)
			{
				if (effected.Contains(item) == false)
				{
					this.RecordValidationResult(validateResults, string.Format(messageTemplate, AUCommon.DisplayNameFor((SchemaObjectBase)currentObject), item), currentObject, key);
					break;
				}

				if (repeated.Contains(item))
				{
					this.RecordValidationResult(validateResults, string.Format(messageTemplate, AUCommon.DisplayNameFor((SchemaObjectBase)currentObject), item), currentObject, key);
					break;
				}
				else
				{
					repeated.Add(item);
				}
			}
		}
コード例 #13
0
ファイル: OrCompositeValidator.cs プロジェクト: reckcn/CSharp
		/// <summary>
		/// Implements the validation logic for the receiver, invoking validation on the composed validators.
		/// </summary>
		/// <param name="objectToValidate">The object to validate.</param>
		/// <param name="currentTarget">The object on the behalf of which the validation is performed.</param>
		/// <param name="key">The key that identifies the source of <paramref name="objectToValidate"/>.</param>
		/// <param name="validationResults">The validation results to which the outcome of the validation should be stored.</param>
		/// <remarks>
		/// The results the generated by the composed validators are logged to <paramref name="validationResults"/>
		/// only if all the validators generate results.
		/// </remarks>
		public override void DoValidate(object objectToValidate,
			object currentTarget,
			string key,
			ValidationResults validationResults)
		{
			List<ValidationResult> childrenValidationResults = new List<ValidationResult>();

			foreach (Validator validator in this.validators)
			{
				ValidationResults childValidationResults = new ValidationResults();
				validator.DoValidate(objectToValidate, currentTarget, key, childValidationResults);
				if (childValidationResults.IsValid)
				{
					// no need to query the rest of the validators
					return;
				}

				childrenValidationResults.AddRange(childValidationResults);
			}

			LogValidationResult(validationResults,
				GetMessage(objectToValidate, key),
				currentTarget, 
				key,
				childrenValidationResults);
		}
コード例 #14
0
        /// <summary>
        /// Un curs poate fi ales cel mult o data de catre un student.
        /// </summary>
        /// <param name="student"></param>
        /// <param name="results"></param>
        internal void ValidateCourseCanOnlyBeChoosenASingleTime(Student student, ValidationResults results)
        {
            if (student.Courses.Where(c => c.CourseId != 0).GroupBy(c => c.CourseId).Any(g => g.Count() > 1))
            {
                results.AddResult(new ValidationResult
                    (
                    "The there are duplicate courses (same id) in the list of courses chosen by the student", results, "ValidationMethod", "error", null)
                    );
                return;
            }

            if (student.Courses.Where(c => c.CourseId != 0).GroupBy(c => new { c.Name, c.Description }).Any(g => g.Count() > 1))
            {
                results.AddResult(new ValidationResult
                   (
                   "The there are duplicate courses (same name & description) in the list of courses chosen by the student", results, "ValidationMethod", "error", null)
                   );
                return;
            }

            if (student.Courses.Where(c => c.CourseId != 0).GroupBy(c => c.Name).Any(g => g.Count() > 1))
            {
                 results.AddResult(new ValidationResult
                    (
                    "The there are duplicate courses in the list of courses (same name) chosen by the student", results, "ValidationMethod", "error", null)
                    );
            }
        }
コード例 #15
0
        public void ControlValidationMappingsFailureTest()
        {
            IBugzillaPageView viewMock = MockRepository.StrictMock<IBugzillaPageView>();

            Expect.Call(viewMock.Model).PropertyBehavior();
            viewMock.ValidationRequested += null;
            LastCall.IgnoreArguments();
            viewMock.ControlValidationTriggered += null;
            LastCall.IgnoreArguments();
            IEventRaiser raiser = LastCall.GetEventRaiser();
            Expect.Call(FacadeMock.GetSourceList()).Return(new string[0]);
            Expect.Call(viewMock.SourceList).PropertyBehavior().Return(new string[0]);
            Expect.Call(FacadeMock.GetProjectWrapperList()).Return(null);
            Expect.Call(viewMock.VersionOneProjects).PropertyBehavior();
            Expect.Call(FacadeMock.GetVersionOnePriorities()).Return(null);
            Expect.Call(viewMock.VersionOnePriorities).PropertyBehavior();
            viewMock.DataBind();
            ValidationResults results = new ValidationResults();
            ValidationResult generalResult = new ValidationResult(string.Empty, new BugzillaProjectMapping(), null, null, null);
            results.AddResult(generalResult);
            Expect.Call(FacadeMock.ValidateEntity(viewMock.Model)).IgnoreArguments().Return(results);
            viewMock.SetGeneralTabValid(true);
            viewMock.SetMappingTabValid(false);

            MockRepository.ReplayAll();

            BugzillaController controller = CreateController();
            controller.RegisterView(viewMock);
            controller.PrepareView();
            raiser.Raise(viewMock, EventArgs.Empty);

            MockRepository.VerifyAll();
        }
コード例 #16
0
        protected override void DoValidate(object objectToValidate, object currentObject, string key, ValidationResults validateResults)
		{
            if (objectToValidate == null || OguBase.IsNullOrEmpty((IOguObject)objectToValidate))
            {
                RecordValidationResult(validateResults, this.MessageTemplate, currentObject, key);
            }
		}
コード例 #17
0
        public void CanValidateGravatar()
        {
            var results = new ValidationResults();
            var widget = new Gravatar();

            // Confirm errors.
            widget.FullName = "123456789012345678901234567890123456789012345678901234567890";
            widget.Rating = "too_long";

            bool success = widget.Validate(results);
            Assert.IsFalse(success);
            Assert.AreEqual(results.Count, 6);

            // Confirm correct
            widget.Header = "about";
            widget.Zone = "right";
            widget.FullName = "kishore reddy";
            widget.Rating = "r";
            widget.Email = "*****@*****.**";
            widget.Size = 80;

            results.Clear();
            success = widget.Validate(results);
            Assert.IsTrue(success);
            Assert.AreEqual(results.Count, 0);
        }
コード例 #18
0
		/// <summary>
		/// Validates the state of this control.
		/// </summary>
		/// <param name="context">The <see cref="IMansionWebContext"/>.</param>
		/// <param name="form">The <see cref="Form"/> to which this control belongs.</param>
		/// <param name="results">The <see cref="ValidationResults"/> in which the validation results are stored.</param>
		protected override void DoValidate(IMansionWebContext context, Form form, ValidationResults results)
		{
			// loop over all the controls
			foreach (var control in FormControls)
				control.Validate(context, form, results);
			base.DoValidate(context, form, results);
		}
コード例 #19
0
		public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{
			Dictionary<Type, Validator> validators = new Dictionary<Type, Validator>();
			Int32 i = 0;
			ValidationResults results = new ValidationResults();
			IMethodReturn result = null;

			foreach (Type type in input.MethodBase.GetParameters().Select(p => p.ParameterType))
			{
				if (validators.ContainsKey(type) == false)
				{
					validators[type] = ValidationFactory.CreateValidator(type, this.Ruleset);
				}

				Validator validator = validators[type];
				validator.Validate(input.Arguments[i], results);

				++i;
			}

			if (results.IsValid == false)
			{
				result = input.CreateExceptionMethodReturn(new Exception(String.Join(Environment.NewLine, results.Select(r => r.Message).ToArray())));
			}
			else
			{
				result = getNext()(input, getNext);
			}

			return (result);
		}
コード例 #20
0
        /// <summary>
        /// Converts <paramref name="results"/> to a list of anonymous objects.
        /// </summary>
        /// <param name="results">The validation results to convert.</param>
        /// <param name="controlList">The control metadata list.</param>
        /// <param name="firstError">When the method returns, will contain the earliest control that has an error.</param>
        /// <returns>A new list of anonymous objects.</returns>
        public static Dictionary<string, List<string>> ConvertValidationResultsToErrorMessages(ValidationResults results, ControlList controlList, out Control firstError)
        {
            int minPos = int.MaxValue;
            firstError = null;

            Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
            foreach (ValidationResult result in results)
            {
                string errorKey = Regex.Replace(result.Key, "[" + Regex.Escape(".[") + "\\]]+", "-");
                if (!errors.ContainsKey(errorKey))
                {
                    errors.Add(errorKey, new List<string>());
                }

                errors[errorKey].Add(result.Message);
                string controlName = Regex.Match(errorKey, "[a-z0-9_]+$", RegexOptions.IgnoreCase).Value;
                Control control = controlList.FindRecursive(controlName);
                if (control == null)
                {
                    controlName = Regex.Match(errorKey, "[a-z0-9_]+(?=-" + controlName + "$)", RegexOptions.IgnoreCase).Value;
                    control = controlList.FindRecursive(controlName);
                }

                if (control.Position < minPos)
                {
                    minPos = control.Position;
                    firstError = control;
                }
            }

            return errors;
        }
        /// <summary>
        /// Does the validate.
        /// </summary>
        /// <param name="objectToValidate">The object to validate.</param>
        /// <param name="currentTarget">The current target.</param>
        /// <param name="key">The key.</param>
        /// <param name="validationResults">The validation results.</param>
        protected override void DoValidate(ModelBusReference objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            this.MessageTemplate = currentMessageTemplate;

            base.DoValidate(objectToValidate, currentTarget, key, validationResults);

            if (!validationResults.IsValid)
            {
                return;
            }

            ServiceReference serviceReference = currentTarget as ServiceReference;

            if (serviceReference == null)
            {
                return;
            }

            using (ModelBusReferenceResolver resolver = new ModelBusReferenceResolver())
            {
                ModelElement referencedElement = resolver.Resolve(objectToValidate);
                if (referencedElement != null)
                {
                    ServiceContractModel dcm = referencedElement.Store.ElementDirectory.FindElements<ServiceContractModel>()[0];
                    if (dcm.ImplementationTechnology == null ||
                        String.IsNullOrWhiteSpace(dcm.ProjectMappingTable) ||
                        !dcm.ImplementationTechnology.Name.Equals(GetItName(currentTarget), StringComparison.OrdinalIgnoreCase))
                    {
                        validationResults.AddResult(
                            new ValidationResult(String.Format(CultureInfo.CurrentUICulture, this.MessageTemplate, ValidatorUtility.GetTargetName(currentTarget)), currentTarget, key, String.Empty, this));
                    }
                }
            }
        }
コード例 #22
0
        protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            if(objectToValidate == null)
            {
                // Skipping valudation if optional decimal is a null
                return;
            }

            var number = (decimal)objectToValidate;

            List<DecimalPrecisionValidatorAttribute> attributes = currentTarget.GetType().GetProperty(key).GetCustomAttributesRecursively<DecimalPrecisionValidatorAttribute>().ToList();
            var validatiorAttribute = attributes[0];

            if (number != Decimal.Round(number, validatiorAttribute.Scale))
            {

                LogValidationResult(validationResults, GetString("Validation.Decimal.SymbolsAfterPointAllowed").FormatWith(validatiorAttribute.Scale), currentTarget, key);
                return;
            }

            string str = number.ToString(CultureInfo.InvariantCulture);
            int separatorIndex = str.IndexOf('.');
            if(separatorIndex > 0)
            {
                str = str.Substring(0, separatorIndex);
            }

            if (str.StartsWith("-")) str = str.Substring(1);

            int allowedDigitsBeforeSeparator = validatiorAttribute.Precision - validatiorAttribute.Scale;
            if (str.Length > allowedDigitsBeforeSeparator)
            {
                LogValidationResult(validationResults, GetString("Validation.Decimal.SymbolsBeforePointAllowed").FormatWith(allowedDigitsBeforeSeparator), currentTarget, key);
            }
        }
コード例 #23
0
        public void EntityValidation(ValidationResults results)
        {
            //--- Required
            if (menu_id == null)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Menu"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            if (bill_of_material_head_id == null)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Bill of Material Head"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
            if (quantity == null)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Quantity"), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }

            //---
            if (quantity <= 0)
            {
                ValidationResult result = new ValidationResult(string.Format(ErrorMessage.CompareValueMore, "Quantity", 0), this, string.Empty, string.Empty, null);
                results.AddResult(result);
            }
        }
コード例 #24
0
        public void ValidatorWillThrowIfProvidedNulValidationResults()
        {
            Validator validator = new MockValidator(true, "template");
            ValidationResults validationResults = new ValidationResults();

            validator.Validate(this, null);
        }
コード例 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArgumentValidationException"/> class, storing the validation
        /// results and the name of the parameter that failed.
        /// </summary>
        /// <param name="validationResults">The <see cref="ValidationResults"/> returned from the Validation Application Block.</param>
        /// <param name="paramName">The parameter that failed validation.</param>
        public ArgumentValidationException(ValidationResults validationResults, string paramName)
            : base(Resources.ValidationFailedMessage, paramName)
        {
            this.validationResults = validationResults;

            SerializeObjectState += (s, e) => e.AddSerializedState(new ValidationResultsSerializationData(this.validationResults));
        }
コード例 #26
0
 public void EntityValidation(ValidationResults results)
 {
     //--- Required
     if (bill_of_material_head_id == null)
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Bill Of Material Head"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (IsCheckedMaterial && material_id == null)
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Material"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     else if (!IsCheckedMaterial && bill_of_material_head_id_sub == null)
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "BOM"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (amount == null)
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Amount"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (lost_factor == null)
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Lost Factor"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
 }
コード例 #27
0
 protected internal override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     foreach (Validator validator in this.validators)
     {
         validator.DoValidate(objectToValidate, currentTarget, key, validationResults);
     }
 }
コード例 #28
0
        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            // Get the token for this authentication process (rendered in a hidden input field, see the view)
            var token = (string)ViewState["Token"];

            // Get an instance of the Authentication class
            var auth = Util.GetRestPkiClient().GetAuthentication();

            // Call the CompleteWithWebPki() method with the token, which finalizes the authentication process. The call yields a
            // ValidationResults which denotes whether the authentication was successful or not.
            var validationResults = auth.CompleteWithWebPki(token);

            // Check the authentication result
            if (!validationResults.IsValid) {
                // If the authentication was not successful, we render a page showing what went wrong
                this.ValidationResults = validationResults;
                Server.Transfer("AuthenticationFail.aspx");
                return;
            }

            // At this point, you have assurance that the certificate is valid according to the TrustArbitrator you
            // selected when starting the authentication and that the user is indeed the certificate's subject. Now,
            // you'd typically query your database for a user that matches one of the certificate's fields, such as
            // userCert.EmailAddress or userCert.PkiBrazil.CPF (the actual field to be used as key depends on your
            // application's business logic) and set the user ID on the auth cookie. For demonstration purposes,
            // we'll just render a page showing some of the user's certificate information.
            this.Certificate = auth.GetCertificate();
            Server.Transfer("AuthenticationSuccess.aspx");
        }
コード例 #29
0
ファイル: Employee.cs プロジェクト: hpbaotho/pos-project-th
 public void EntityValidation(ValidationResults results)
 {
     //--- Required
     if (string.IsNullOrEmpty(employee_no))
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Employee No"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (string.IsNullOrEmpty(first_name))
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "First Name"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (string.IsNullOrEmpty(last_name))
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Last Name"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (string.IsNullOrEmpty(user_name))
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "User Name"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
     if (string.IsNullOrEmpty(user_password))
     {
         ValidationResult result = new ValidationResult(string.Format(ErrorMessage.IsRequired, "Password"), this, string.Empty, string.Empty, null);
         results.AddResult(result);
     }
 }
コード例 #30
0
 public void Validate(ValidationResults results)
 {
     var examMetadata = new ExamMetadata();
     examMetadata.ExamValidateDate(this, ExaminationDate, results);
     examMetadata.ValidateAllowedPasses(this, results);
     examMetadata.ValidateGradeCourse(this, results);
 }
コード例 #31
0
        private void btnNext_Click(object sender, EventArgs e)
        {
            int    num;
            int    num2;
            string str = string.Empty;

            if (ValidateValues(out num, out num2))
            {
                if (!addpromoteSales.IsValid)
                {
                    ShowMsg(addpromoteSales.CurrentErrors, false);
                }
                else
                {
                    PurchaseGiftInfo target = new PurchaseGiftInfo();
                    target.Name           = addpromoteSales.Item.Name;
                    target.Description    = addpromoteSales.Item.Description;
                    target.MemberGradeIds = chklMemberGrade.SelectedValue;
                    target.BuyQuantity    = num;
                    target.GiveQuantity   = num2;

                    Session["PurchaseGiftInfo"] = target;
                    if (target.GiveQuantity > target.BuyQuantity)
                    {
                        str = Formatter.FormatErrorMessage("赠送数量不能大于购买数量");
                    }
                    if (chklMemberGrade.SelectedValue.Count <= 0)
                    {
                        str = str + Formatter.FormatErrorMessage("适合的客户必须选择一个");
                    }
                    ValidationResults results = Hishop.Components.Validation.Validation.Validate <PurchaseGiftInfo>(target, new string[] { "ValPromotion" });
                    if (!results.IsValid)
                    {
                        foreach (ValidationResult result in (IEnumerable <ValidationResult>)results)
                        {
                            str = str + Formatter.FormatErrorMessage(result.Message);
                        }
                    }
                    if (!string.IsNullOrEmpty(str))
                    {
                        ShowMsg(str, false);
                    }
                    else
                    {
                        switch (SubsitePromoteHelper.AddPromotion(target))
                        {
                        case PromotionActionStatus.Success:
                        {
                            int activeIdByPromotionName = SubsitePromoteHelper.GetActiveIdByPromotionName(target.Name);
                            base.Response.Redirect(Globals.ApplicationPath + "/Shopadmin/promotion/MyPromotionProducts.aspx?ActiveId=" + activeIdByPromotionName, true);
                            return;
                        }

                        case PromotionActionStatus.DuplicateName:
                            ShowMsg("已存在此名称的促销活动", false);
                            return;

                        case PromotionActionStatus.SameCondition:
                            ShowMsg("已经存在相同满足条件的优惠活动", false);
                            return;
                        }
                        ShowMsg("添加促销活动--买几送几错误", false);
                    }
                }
            }
        }
コード例 #32
0
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            bool flag  = false;
            bool flag2 = objectToValidate == null;

            if (!flag2)
            {
                flag = !Enum.IsDefined(this.enumType, objectToValidate);
            }
            if (flag2 || (flag != base.Negated))
            {
                base.LogValidationResult(validationResults, this.GetMessage(objectToValidate, key), currentTarget, key);
            }
        }
コード例 #33
0
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            bool flag  = false;
            bool flag2 = objectToValidate == null;

            if (!flag2)
            {
                if (string.Empty.Equals(objectToValidate) && this.IsTheTargetTypeAValueTypeDifferentFromString())
                {
                    flag = true;
                }
                else
                {
                    try
                    {
                        if (TypeDescriptor.GetConverter(this.targetType).ConvertFromString(null, CultureInfo.CurrentCulture, objectToValidate) == null)
                        {
                            flag = true;
                        }
                    }
                    catch (Exception)
                    {
                        flag = true;
                    }
                }
            }
            if (flag2 || (flag != base.Negated))
            {
                base.LogValidationResult(validationResults, this.GetMessage(objectToValidate, key), currentTarget, key);
            }
        }
コード例 #34
0
 protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if (objectToValidate != null)
     {
         if (this.rangeChecker.IsInRange(objectToValidate.Length) == base.Negated)
         {
             base.LogValidationResult(validationResults, this.GetMessage(objectToValidate, key), currentTarget, key);
         }
     }
     else
     {
         base.LogValidationResult(validationResults, this.GetMessage(objectToValidate, key), currentTarget, key);
     }
 }
コード例 #35
0
ファイル: SettingsView.cs プロジェクト: theolivenbaum/vrs
 public void ShowValidationResults(ValidationResults results)
 {
     _ValidationHelper.ApplyValidationResults(results, _ViewModel);
     _FailedValidation = results.HasErrors;
 }
コード例 #36
0
 protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if (!File.Exists(objectToValidate) && !Directory.Exists(objectToValidate))
     {
         this.LogValidationResult(validationResults, this.MessageTemplate, currentTarget, key);
     }
 }
コード例 #37
0
        /// <summary>
        /// 添加按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddVouchers_Click(object sender, System.EventArgs e)
        {
            string  text     = string.Empty;
            string  arg_0B_0 = string.Empty;
            decimal?amount;
            decimal discountValue;

            if (!this.ValidateValues(out amount, out discountValue))
            {
                return;
            }
            if (!this.calendarStartDate.SelectedDate.HasValue)
            {
                this.ShowMsg("请选择开始日期!", false);
                return;
            }
            if (!this.calendarEndDate.SelectedDate.HasValue)
            {
                this.ShowMsg("请选择结束日期!", false);
                return;
            }
            if (this.calendarStartDate.SelectedDate.Value.CompareTo(this.calendarEndDate.SelectedDate.Value) >= 0)
            {
                this.ShowMsg("开始日期不能晚于结束日期!", false);
                return;
            }

            string strValidity = this.txtValidity.Text;

            if (!Regex.IsMatch(strValidity, @"^[1-9][0-9]*$"))
            {
                this.ShowMsg(" 有效期只能是数字,必须大于等于O!", false);
                return;
            }

            string strOverMoney = txtOverMoney.Text;

            if (this.rdoOverMoney.Checked && !Regex.IsMatch(strOverMoney, @"^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$"))
            {
                this.ShowMsg(" 满足金额必须为正数,且最多只能有两位小数", false);
                return;
            }


            VoucherInfo voucherInfo = new VoucherInfo();

            voucherInfo.Name          = this.txtVoucherName.Text;
            voucherInfo.ClosingTime   = this.calendarEndDate.SelectedDate.Value.AddDays(1).AddSeconds(-1);
            voucherInfo.StartTime     = this.calendarStartDate.SelectedDate.Value;
            voucherInfo.Amount        = amount;
            voucherInfo.DiscountValue = discountValue;

            #region 发送方式
            int    SendType     = 0;
            string stroverMoney = string.Empty;
            if (this.rdoManually.Checked)
            {
                SendType = int.Parse(this.rdoManually.Value);
            }

            else if (this.rdoOverMoney.Checked)
            {
                SendType     = int.Parse(this.rdoOverMoney.Value);
                stroverMoney = txtOverMoney.Text.ToString();
            }

            else if (this.rdoRegist.Checked)
            {
                SendType = int.Parse(this.rdoRegist.Value);
            }

            else if (this.rdoLq.Checked)
            {
                SendType = int.Parse(this.rdoLq.Value);
            }


            #endregion

            voucherInfo.SendType     = SendType;
            voucherInfo.SendTypeItem = stroverMoney;
            voucherInfo.Validity     = int.Parse(this.txtValidity.Text);

            #region 字段限制验证,通过数据注解验证的方式
            ValidationResults validationResults = Validation.Validate <VoucherInfo>(voucherInfo, new string[]
            {
                "Voucher"
            });
            if (!validationResults.IsValid)
            {
                using (System.Collections.Generic.IEnumerator <ValidationResult> enumerator = ((System.Collections.Generic.IEnumerable <ValidationResult>)validationResults).GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        ValidationResult current = enumerator.Current;
                        text += Formatter.FormatErrorMessage(current.Message);
                        this.ShowMsg(text, false);
                        return;
                    }
                }
            }
            #endregion

            string empty = string.Empty;
            if (this.voucherId == 0)  //创建现金券
            {
                VoucherActionStatus voucherActionStatus = VoucherHelper.CreateVoucher(voucherInfo, 0, out empty, 1);
                if (voucherActionStatus == VoucherActionStatus.UnknowError)
                {
                    this.ShowMsg("未知错误", false);
                }
                else
                {
                    if (voucherActionStatus == VoucherActionStatus.DuplicateName)
                    {
                        this.ShowMsg("已经存在相同的现金券名称", false);
                        return;
                    }
                    if (voucherActionStatus == VoucherActionStatus.CreateClaimCodeError)
                    {
                        this.ShowMsg("生成现金券号码错误", false);
                        return;
                    }
                    this.ShowMsg("添加现金券成功", true);
                    this.RestCoupon();
                    return;
                }
            }

            else  //修改现金券
            {
                voucherInfo.VoucherId = this.voucherId;
                VoucherActionStatus voucherActionStatus = VoucherHelper.UpdateVoucher(voucherInfo);
                if (voucherActionStatus == VoucherActionStatus.Success)
                {
                    this.RestCoupon();
                    this.ShowMsg("成功修改了现金券信息", true);
                }
                else
                {
                    if (voucherActionStatus == VoucherActionStatus.DuplicateName)
                    {
                        this.ShowMsg("修改现金券信息错误,已经具有此现金券名称", false);
                        return;
                    }
                    this.ShowMsg("未知错误", false);
                    this.RestCoupon();
                    return;
                }
            }
        }
コード例 #38
0
 public NeuraliumDigestValidationResult(ValidationResults result) : base(result)
 {
 }
コード例 #39
0
 public NeuraliumDigestValidationResult(ValidationResults result, NeuraliumDigestValidationErrorCode errorCode) : base(result, errorCode)
 {
 }
コード例 #40
0
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            if (string.IsNullOrEmpty(objectToValidate))
            {
                return;
            }

            ModelElement mel = currentTarget as ModelElement;

            if (mel == null ||
                (!(mel is XsdMessage) && !(mel is XsdElementFault)))
            {
                return;
            }

            XmlSchemaElementMoniker elementUri = new XmlSchemaElementMoniker(objectToValidate);

            // It's a primite type
            if (string.IsNullOrEmpty(elementUri.ElementName))
            {
                return;
            }

            string fileName = Path.GetFileName(elementUri.XmlSchemaPath);
            string fullPath = GetXsdFullPath(mel, elementUri.XmlSchemaPath);


            string melName = string.Empty;

            DomainClassInfo.TryGetName(mel, out melName);

            if (string.IsNullOrEmpty(fullPath))
            {
                this.LogValidationResult(validationResults, string.Format(CultureInfo.CurrentUICulture, this.invalidFilePathMessage, melName, fileName, schemaDirectory), currentTarget, key);
                return;
            }

            XmlSchemaTypeGenerator generator = new XmlSchemaTypeGenerator(IsXmlSerializer(mel));

            CodeCompileUnit unit = null;

            try
            {
                unit = generator.GenerateCodeCompileUnit(fullPath);
            }
            catch (InvalidDataContractException exception)
            {
                this.LogValidationResult(validationResults, exception.Message, currentTarget, key);
                return;
            }
            catch (InvalidSerializerException serializationException)
            {
                if (!IsXmlSerializer(mel))
                {
                    this.LogValidationResult(validationResults,
                                             string.Format(CultureInfo.CurrentUICulture,
                                                           this.notCompliantWithDataContractSerializerMessage + ". " + serializationException.Message,
                                                           fileName), currentTarget, key);
                    return;
                }
            }

            foreach (CodeNamespace ns in unit.Namespaces)
            {
                foreach (CodeTypeDeclaration codeType in ns.Types)
                {
                    if (codeType.Name.Equals(elementUri.ElementName, StringComparison.Ordinal))
                    {
                        return;
                    }
                }
            }

            this.LogValidationResult(validationResults, string.Format(CultureInfo.CurrentUICulture, this.MessageTemplate, melName, elementUri.ElementName, fileName), currentTarget, key);
        }
コード例 #41
0
        protected override void DoValidate(T objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            bool flag  = false;
            bool flag2 = objectToValidate == null;

            flag = !flag2 && !this.rangeChecker.IsInRange(objectToValidate);
            if (flag2 || (flag != base.Negated))
            {
                base.LogValidationResult(validationResults, this.GetMessage(objectToValidate, key), currentTarget, key);
            }
        }
コード例 #42
0
 public NeuraliumDigestValidationResult(ValidationResults result, List <NeuraliumDigestValidationErrorCode> errorCodes) : base(result, errorCodes?.Cast <EventValidationErrorCode>().ToList())
 {
 }
コード例 #43
0
        private IEnumerable <ValidationResult> FormatValidationResults(IEnumerable <ValidationResult> source, ValidationResults destination)
        {
            var hasResults = false;

            foreach (var result in source)
            {
                hasResults = true;
                destination.AddResult(new ValidationResult(
                                          result.Message,
                                          result.Target,
                                          String.Format(CultureInfo.InvariantCulture, KeyFormat, result.Key),
                                          result.Tag,
                                          result.Validator,
                                          FormatValidationResults(result.NestedValidationResults, new ValidationResults())));
            }

            return(hasResults ? destination : source);
        }
コード例 #44
0
 public NeuraliumDigestValidationResult(ValidationResults result, List <DigestValidationErrorCode> errorCodes) : base(result, errorCodes)
 {
 }
コード例 #45
0
        private void ValidateInterfacesStrategy(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            foreach (var validator in m_validators)
            {
                validator.Validate(objectToValidate, validationResults);
            }

            base.DoValidate(objectToValidate, currentTarget, key, validationResults);
        }
コード例 #46
0
 public void TestDoValidate(bool objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     this.DoValidate(objectToValidate, currentTarget, key, validationResults);
 }
コード例 #47
0
        /// <summary>
        /// Implements the validation logic for the receiver.
        /// </summary>
        /// <param name="objectToValidate">The object to validate.</param>
        /// <param name="currentTarget">The object on the behalf of which the validation is performed.</param>
        /// <param name="key">The key that identifies the source of <paramref name="objectToValidate"/>.</param>
        /// <param name="validationResults">The validation results to which the outcome of the validation should be stored.</param>
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            bool logError = false;
            bool isObjectToValidateNull = objectToValidate == null;

            if (!isObjectToValidateNull)
            {
                logError = !Enum.IsDefined(enumType, objectToValidate);
            }

            if (isObjectToValidateNull || (logError != Negated))
            {
                this.LogValidationResult(validationResults,
                                         GetMessage(objectToValidate, key),
                                         currentTarget,
                                         key);
            }
        }
コード例 #48
0
        private void FormatKeyStrategy(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            var nestedValidationResults = new ValidationResults();

            ValidateInterfacesStrategy(objectToValidate, currentTarget, key, nestedValidationResults);
            FormatValidationResults(nestedValidationResults, validationResults);
        }
コード例 #49
0
 /// <summary>
 /// Creates a new <see cref="ArgumentValidationException"/>, storing the validation
 /// results and the name of the parameter that failed.
 /// </summary>
 /// <param name="validationResults"><see cref="ValidationResults"/> returned from the Validation Application Block.</param>
 /// <param name="paramName">Parameter that failed validation.</param>
 public ArgumentValidationException(ValidationResults validationResults, string paramName)
     : base(Resources.ValidationFailedMessage, paramName)
 {
     this.validationResults = validationResults;
 }
コード例 #50
0
        public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            if (objectToValidate == null)
            {
                return;
            }

            m_strategy(objectToValidate, currentTarget, key, validationResults);
        }
コード例 #51
0
 protected internal override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     if (objectToValidate != null)
     {
         if (this.targetType.IsAssignableFrom(objectToValidate.GetType()))
         {
             this.targetTypeValidator.DoValidate(objectToValidate, objectToValidate, null, validationResults);
         }
         else
         {
             base.LogValidationResult(validationResults, Resources.ObjectValidatorInvalidTargetType, currentTarget, key);
         }
     }
 }
コード例 #52
0
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            ILanguageDependentPageModel pageModel = currentTarget as ILanguageDependentPageModel;

            if (pageModel != null)
            {
                _language = pageModel.Language;
            }
            CodeDomProvider provider = CodeDomProvider.CreateProvider(_language);

            if (objectToValidate.StartsWith("@", StringComparison.InvariantCulture) || !provider.IsValidIdentifier(objectToValidate))
            {
                string message = string.Format(CultureInfo.CurrentCulture, this.MessageTemplate, objectToValidate);
                this.LogValidationResult(validationResults, message, currentTarget, key);
            }
        }
コード例 #53
0
        /// <summary>
        /// Execute conditional validation.
        /// If this method is called via WinForms integration layer, <paramref name="currentTarget"/> is ValidatedControlItem instance.
        /// When we explicitly validate entities using EL Validation facade, <paramref name="currentTarget"/> contains entity instance.
        /// </summary>
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            var modelResolved = currentTarget;

            if (currentTarget is ValidatedControlItem)
            {
                var validatedItem = (ValidatedControlItem)currentTarget;
                modelResolved = validatedItem.Control.DataBindings[0].DataSource;
            }

            var propertyInfo  = modelResolved.GetType().GetProperty(conditionalPropertyName, typeof(bool));
            var propertyValue = (bool)propertyInfo.GetValue(modelResolved, null);

            if (propertyValue == skipOnFalse)
            {
                base.DoValidate(objectToValidate, currentTarget, key, validationResults);
            }
        }
コード例 #54
0
 /// <summary>
 /// Initializes a new instance of the <Typ>SafeToDisplayException</Typ> class,
 /// including further information in a <r>ValidationResults</r> object.
 /// </summary>
 /// <param name="validationResults">Validation results associated with this exception,
 ///     or <n>null</n> if none.</param>
 /// <param name="message">The message that describes the error.</param>
 public SafeToDisplayException(ValidationResults validationResults, string message)
     : base(message)
 {
     m_validationResults = validationResults;
 }
コード例 #55
0
        CategoryInfo GetCategory()
        {
            CategoryInfo target = new CategoryInfo();

            target.Name                  = txtCategoryName.Text.Trim();
            target.ParentCategoryId      = dropCategories.SelectedValue;
            target.AssociatedProductType = dropProductTypes.SelectedValue;

            if (!string.IsNullOrEmpty(txtRewriteName.Text.Trim()))
            {
                target.RewriteName = txtRewriteName.Text.Trim();
            }
            else
            {
                target.RewriteName = null;
            }

            target.MetaTitle       = txtPageKeyTitle.Text.Trim();
            target.MetaKeywords    = txtPageKeyWords.Text.Trim();
            target.MetaDescription = txtPageDesc.Text.Trim();
            target.Notes1          = fckNotes1.Text;
            target.Notes2          = fckNotes2.Text;
            target.Notes3          = fckNotes3.Text;
            target.DisplaySequence = 1;

            if (target.ParentCategoryId.HasValue)
            {
                CategoryInfo category = SubsiteCatalogHelper.GetCategory(target.ParentCategoryId.Value);
                if ((category == null) || (category.Depth >= 5))
                {
                    ShowMsg(string.Format("您选择的上级分类有误,店铺分类最多只支持{0}级分类", 5), false);
                    return(null);
                }
                if (!string.IsNullOrEmpty(target.Notes1))
                {
                    target.Notes1 = category.Notes1;
                }
                if (!string.IsNullOrEmpty(target.Notes2))
                {
                    target.Notes2 = category.Notes2;
                }
                if (!string.IsNullOrEmpty(target.Notes3))
                {
                    target.Notes3 = category.Notes3;
                }
                if (!string.IsNullOrEmpty(target.RewriteName))
                {
                    target.RewriteName = category.RewriteName;
                }
            }
            ValidationResults results = Validation.Validate <CategoryInfo>(target, new string[] { "ValCategory" });
            string            msg     = string.Empty;

            if (results.IsValid)
            {
                return(target);
            }
            foreach (ValidationResult result in (IEnumerable <ValidationResult>)results)
            {
                msg = msg + Formatter.FormatErrorMessage(result.Message);
            }
            ShowMsg(msg, false);
            return(null);
        }
コード例 #56
0
        private void saveCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            IUser user          = this.GetBinding <IUser>(BindingNames.User);
            var   userFormLogin = GetBinding <IUserFormLogin>(BindingNames.UserFormLogin);

            var userFormLoginFromDatabase = user.GetUserFormLogin();

            bool userValidated = true;

            ValidationResults validationResults = ValidationFacade.Validate(user);

            foreach (ValidationResult result in validationResults)
            {
                this.ShowFieldMessage($"{BindingNames.User}.{result.Key}", result.Message);
                userValidated = false;
            }


            List <CultureInfo> newActiveLocales     = ActiveLocalesFormsHelper.GetSelectedLocalesTypes(this.Bindings).ToList();
            List <CultureInfo> currentActiveLocales = UserSettings.GetActiveLocaleCultureInfos(user.Username, false).ToList();

            string selectedActiveLocaleName = this.GetBinding <string>("ActiveLocaleName");

            CultureInfo selectedActiveLocale = CultureInfo.CreateSpecificCulture(selectedActiveLocaleName);

            string systemPerspectiveEntityToken = EntityTokenSerializer.Serialize(AttachingPoint.SystemPerspective.EntityToken);

            List <Guid>   newUserGroupIds            = UserGroupsFormsHelper.GetSelectedUserGroupIds(this.Bindings);
            List <string> newSerializedEnitityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList();


            if (string.Compare(user.Username, UserSettings.Username, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                // Current user shouldn't be able to lock itself
                if (userFormLogin.IsLocked)
                {
                    this.ShowMessage(DialogType.Message,
                                     Texts.EditUserWorkflow_EditErrorTitle,
                                     Texts.EditUserWorkflow_LockingOwnUserAccount);

                    userValidated = false;
                }

                // Current user shouldn't be able to remove its own access to "System" perspective
                var groupsWithAccessToSystemPerspective = new HashSet <Guid>(GetGroupsThatHasAccessToPerspective(systemPerspectiveEntityToken));

                if (!newSerializedEnitityTokens.Contains(systemPerspectiveEntityToken) &&
                    !newUserGroupIds.Any(groupsWithAccessToSystemPerspective.Contains))
                {
                    this.ShowMessage(DialogType.Message,
                                     Texts.EditUserWorkflow_EditErrorTitle,
                                     Texts.EditUserWorkflow_EditOwnAccessToSystemPerspective);

                    userValidated = false;
                }
            }

            string newPassword = this.GetBinding <string>(BindingNames.NewPassword);

            if (newPassword == NotPassword || UserFormLoginManager.ValidatePassword(userFormLoginFromDatabase, newPassword))
            {
                newPassword = null;
            }
            else
            {
                IList <string> validationMessages;
                if (!PasswordPolicyFacade.ValidatePassword(user, newPassword, out validationMessages))
                {
                    foreach (var message in validationMessages)
                    {
                        this.ShowFieldMessage(BindingNames.NewPassword, message);
                    }

                    userValidated = false;
                }
            }

            if (!userValidated)
            {
                return;
            }

            if (!userFormLogin.IsLocked)
            {
                userFormLogin.LockoutReason = (int)UserLockoutReason.Undefined;
            }
            else
            {
                bool wasLockedBefore = userFormLoginFromDatabase.IsLocked;

                if (!wasLockedBefore)
                {
                    userFormLoginFromDatabase.LockoutReason = (int)UserLockoutReason.LockedByAdministrator;
                }
            }

            UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken);

            bool reloadUsersConsoles = false;

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                DataFacade.Update(user);

                userFormLoginFromDatabase.Folder   = userFormLogin.Folder;
                userFormLoginFromDatabase.IsLocked = userFormLogin.IsLocked;
                DataFacade.Update(userFormLoginFromDatabase);

                if (newPassword != null)
                {
                    UserFormLoginManager.SetPassword(userFormLoginFromDatabase, newPassword);
                }

                string cultureName             = this.GetBinding <string>("CultureName");
                string c1ConsoleUiLanguageName = this.GetBinding <string>("C1ConsoleUiLanguageName");

                UserSettings.SetUserCultureInfo(user.Username, CultureInfo.CreateSpecificCulture(cultureName));
                UserSettings.SetUserC1ConsoleUiLanguage(user.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName));

                List <string> existingSerializedEntityTokens = UserPerspectiveFacade.GetSerializedEntityTokens(user.Username).ToList();

                int intersectCount = existingSerializedEntityTokens.Intersect(newSerializedEnitityTokens).Count();
                if ((intersectCount != newSerializedEnitityTokens.Count) ||
                    (intersectCount != existingSerializedEntityTokens.Count))
                {
                    UserPerspectiveFacade.SetSerializedEntityTokens(user.Username, newSerializedEnitityTokens);

                    if (UserSettings.Username == user.Username)
                    {
                        reloadUsersConsoles = true;
                    }
                }

                if (DataLocalizationFacade.ActiveLocalizationCultures.Any())
                {
                    foreach (CultureInfo cultureInfo in newActiveLocales)
                    {
                        if (!currentActiveLocales.Contains(cultureInfo))
                        {
                            UserSettings.AddActiveLocaleCultureInfo(user.Username, cultureInfo);
                        }
                    }

                    foreach (CultureInfo cultureInfo in currentActiveLocales)
                    {
                        if (!newActiveLocales.Contains(cultureInfo))
                        {
                            UserSettings.RemoveActiveLocaleCultureInfo(user.Username, cultureInfo);
                        }
                    }

                    if (selectedActiveLocale != null)
                    {
                        if (!selectedActiveLocale.Equals(UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username)))
                        {
                            reloadUsersConsoles = true;
                        }

                        UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, selectedActiveLocale);
                    }
                    else if (UserSettings.GetActiveLocaleCultureInfos(user.Username).Any())
                    {
                        UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, UserSettings.GetActiveLocaleCultureInfos(user.Username).First());
                    }
                }


                List <IUserUserGroupRelation> oldRelations = DataFacade.GetData <IUserUserGroupRelation>(f => f.UserId == user.Id).ToList();

                IEnumerable <IUserUserGroupRelation> deleteRelations =
                    from r in oldRelations
                    where !newUserGroupIds.Contains(r.UserGroupId)
                    select r;

                DataFacade.Delete(deleteRelations);


                foreach (Guid newUserGroupId in newUserGroupIds)
                {
                    Guid groupId = newUserGroupId;
                    if (oldRelations.Any(f => f.UserGroupId == groupId))
                    {
                        continue;
                    }

                    var userUserGroupRelation = DataFacade.BuildNew <IUserUserGroupRelation>();
                    userUserGroupRelation.UserId      = user.Id;
                    userUserGroupRelation.UserGroupId = newUserGroupId;

                    DataFacade.AddNew(userUserGroupRelation);
                }

                LoggingService.LogEntry("UserManagement",
                                        $"C1 Console user '{user.Username}' updated by '{UserValidationFacade.GetUsername()}'.",
                                        LoggingService.Category.Audit,
                                        TraceEventType.Information);

                transactionScope.Complete();
            }

            if (UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username) == null)
            {
                this.ShowFieldMessage(BindingNames.ActiveContentLanguage, "The user doesn't have permissions to access the language you selected here. Assign permissions so the user may access this.");
                this.ShowMessage(DialogType.Warning, "User missing permissions for language", "The user doesn't have permissions to access the language you selected as 'Active content language'.");
            }
            else
            {
                if (reloadUsersConsoles)
                {
                    foreach (string consoleId in GetConsoleIdsOpenedByUser(user.Username))
                    {
                        ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), consoleId);
                    }
                }
            }

            SetSaveStatus(true);
            updateTreeRefresher.PostRefreshMesseges(user.GetDataEntityToken());
        }
コード例 #57
0
 protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
 {
     throw new NotImplementedException();
 }
コード例 #58
0
        protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
        {
            ICreateViewPageBaseModel pageModel = currentTarget as ICreateViewPageBaseModel;

            if (pageModel != null)
            {
                string physicalPath = string.Empty;

                if (pageModel.WebFolder != null)
                {
                    physicalPath = pageModel.WebFolder.ItemPath;
                }
                else
                {
                    physicalPath = pageModel.WebProject.ProjectPath;
                }

                string viewFileName      = String.Format(CultureInfo.CurrentCulture, "{0}.{1}", objectToValidate, pageModel.ViewFileExtension);
                string viewExistsMessage = DefaultFailureMessage;

                string pathToValidate = String.Empty;

                try
                {
                    pathToValidate = Path.Combine(physicalPath, viewFileName);
                }
                catch (ArgumentException ex)
                {
                    validationResults.AddResult(new ValidationResult(ex.Message, objectToValidate, key, "Bad file name", this));
                    return;
                }


                Validator <string> _viewViewFileValidator = new FileNotExistsValidator(
                    physicalPath,
                    String.Format(CultureInfo.CurrentCulture, viewExistsMessage, pathToValidate));
                _viewViewFileValidator.Validate(viewFileName, validationResults);
            }
        }
コード例 #59
0
        private void setValidationError(ValidationResults vr)
        {
            var message = "One or more validations failed: " + string.Join("; ", vr.Errors.Select(e => getDisplayText(e)).ToArray());

            setError(message);
        }
コード例 #60
0
        /// <summary>
        /// 执行校验
        /// </summary>
        /// <param name="objectToValidate">要进行校验的对象</param>
        /// <param name="currentObject">当前的对象</param>
        /// <param name="key">键</param>
        /// <param name="validateResults">校验结果</param>
        protected override void DoValidate(object objectToValidate, object currentObject, string key, ValidationResults validateResults)
        {
            List <Validator> innerValidators = GenerateValidators((SchemaObjectBase)objectToValidate);

            //如果已经存在SchemaPropertyValidatorContext则直接进行校验,否则自己创造一个上下文。
            if (SchemaPropertyValidatorContext.ExistsInContext)
            {
                innerValidators.ForEach(v => v.Validate(objectToValidate, validateResults));
            }
            else
            {
                SchemaPropertyValidatorContext.Current.DoActions(() =>
                {
                    SchemaPropertyValidatorContext.Current.Container = (SchemaObjectBase)objectToValidate;

                    innerValidators.ForEach(v => v.Validate(objectToValidate, validateResults));
                });
            }
        }