public INodeVisitor Validate(ValidationContext context)
        {
            var knownFragments = new Dictionary<string, FragmentDefinition>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<FragmentDefinition>(fragmentDefinition =>
            {
              var fragmentName = fragmentDefinition.Name;
              if (knownFragments.ContainsKey(fragmentName))
              {
              var error = new ValidationError(
                  context.OriginalQuery,
                  "5.4.1.1",
                  DuplicateFragmentNameMessage(fragmentName),
                  knownFragments[fragmentName],
                  fragmentDefinition);
            context.ReportError(error);
              }
              else
              {
            knownFragments[fragmentName] = fragmentDefinition;
              }
            });
              });
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var operationDefs = new List<Operation>();
              var fragmentDefs = new List<FragmentDefinition>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<Operation>(node => operationDefs.Add(node));
            _.Match<FragmentDefinition>(node => fragmentDefs.Add(node));
            _.Match<Document>(
              leave: document =>
              {
            var fragmentNameUsed = new List<string>();
            operationDefs.Apply(operation =>
            {
              context.GetRecursivelyReferencedFragments(operation).Apply(fragment =>
              {
                fragmentNameUsed.Add(fragment.Name);
              });
            });

            fragmentDefs.Apply(fragmentDef =>
            {
              var fragName = fragmentDef.Name;
              if (!fragmentNameUsed.Contains(fragName))
              {
                var error = new ValidationError(context.OriginalQuery, "5.4.1.4", UnusedFragMessage(fragName), fragmentDef);
                context.ReportError(error);
              }
            });
              });
              });
        }
        protected ValidationError CreateError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path)
        {
            if (_schemaDiscovery == null)
            {
                _schemaDiscovery = new JSchemaDiscovery();
                _schemaDiscovery.Discover(Schema, null);
            }

            ValidationError error = new ValidationError();
            error.Message = message;
            error.ErrorType = errorType;
            error.Path = path;
            if (lineInfo != null)
            {
                error.LineNumber = lineInfo.LineNumber;
                error.LinePosition = lineInfo.LinePosition;
            }
            error.Schema = schema;
            error.SchemaId = _schemaDiscovery.KnownSchemas.Single(s => s.Schema == schema).Id;
            error.SchemaBaseUri = schema.BaseUri;
            error.Value = value;
            error.ChildErrors = childErrors;

            return error;
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var frequency = new Dictionary<string, string>();

            return new EnterLeaveListener(_ =>
            {
                _.Match<Operation>(
                    enter: op =>
                    {
                        if (context.Document.Operations.Count < 2)
                        {
                            return;
                        }
                        if (string.IsNullOrWhiteSpace(op.Name))
                        {
                            return;
                        }

                        if (frequency.ContainsKey(op.Name))
                        {
                            var error = new ValidationError(
                                context.OriginalQuery,
                                "5.1.1.1",
                                DuplicateOperationNameMessage(op.Name),
                                op);
                            context.ReportError(error);
                        }
                        else
                        {
                            frequency[op.Name] = op.Name;
                        }
                    });
            });
        }
    public EntityError Resolve(EntityManager em) {
      IsServerError = true;
      try {
        EntityType entityType = null;
        if (EntityTypeName != null) {
          var stName = StructuralType.ClrTypeNameToStructuralTypeName(EntityTypeName);
          entityType = MetadataStore.Instance.GetEntityType(stName);
          var ek = new EntityKey(entityType, KeyValues);
          Entity = em.FindEntityByKey(ek);
        }

        if (PropertyName != null) {
          PropertyName = MetadataStore.Instance.NamingConvention.ServerPropertyNameToClient(PropertyName);
        }
        if (Entity != null) {
          Property = entityType.GetProperty(PropertyName);
          var vc = new ValidationContext(this.Entity);
          vc.Property = this.Property;
          var veKey = (ErrorName ?? ErrorMessage) + (PropertyName ?? "");
          var ve = new ValidationError(null, vc, ErrorMessage, veKey);
          ve.IsServerError = true;
          this.Entity.EntityAspect.ValidationErrors.Add(ve);
        }
      } catch (Exception e) {
        ErrorMessage = ( ErrorMessage ?? "") + ":  Unable to Resolve this error: " + e.Message;
      }
      return this;
    }
        public INodeVisitor Validate(ValidationContext context)
        {
            var variableNameDefined = new Dictionary<string, bool>();

            return new EnterLeaveListener(_ =>
            {
                _.Match<VariableDefinition>(varDef => variableNameDefined[varDef.Name] = true);

                _.Match<Operation>(
                    enter: op => variableNameDefined = new Dictionary<string, bool>(),
                    leave: op =>
                    {
                        var usages = context.GetRecursiveVariables(op);
                        usages.Apply(usage =>
                        {
                            var varName = usage.Node.Name;
                            bool found;
                            if (!variableNameDefined.TryGetValue(varName, out found))
                            {
                                var error = new ValidationError(
                                    context.OriginalQuery,
                                    "5.7.4",
                                    UndefinedVarMessage(varName, op.Name),
                                    usage.Node,
                                    op);
                                context.ReportError(error);
                            }
                        });
                    });
            });
        }
        public void TestInitialize()
        {
            node = new ConfigurationApplicationNode(ConfigurationApplicationFile.FromCurrentAppDomain());
            message = "Test";
			propertyInfo = node.GetType().GetProperty("ConfigurationFile");
            error = new ValidationError(node, propertyInfo.Name, message);
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var variableDefs = new List<VariableDefinition>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<VariableDefinition>(def => variableDefs.Add(def));

            _.Match<Operation>(
              enter: op => variableDefs = new List<VariableDefinition>(),
              leave: op =>
              {
            var usages = context.GetRecursiveVariables(op).Select(usage => usage.Node.Name);
            variableDefs.Apply(variableDef =>
            {
              var variableName = variableDef.Name;
              if (!usages.Contains(variableName))
              {
                var error = new ValidationError(context.OriginalQuery, "5.7.5", UnusedVariableMessage(variableName, op.Name), variableDef);
                context.ReportError(error);
              }
            });
              });
              });
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var knownArgs = new Dictionary<string, Argument>();

              return new EnterLeaveListener(_ =>
              {
            _.Match<Field>(field => knownArgs = new Dictionary<string, Argument>());
            _.Match<Directive>(field => knownArgs = new Dictionary<string, Argument>());

            _.Match<Argument>(argument =>
            {
              var argName = argument.Name;
              if (knownArgs.ContainsKey(argName))
              {
              var error = new ValidationError(context.OriginalQuery,
                  "5.3.2",
                  DuplicateArgMessage(argName),
                  knownArgs[argName],
                  argument);
            context.ReportError(error);
              }
              else
              {
            knownArgs[argName] = argument;
              }
            });
              });
        }
 public void OnField_WorksWithAllCommonCasing()
 {
     ValidationError fieldError = new ValidationError("", "1", "");
     ValidationErrors errors = new ValidationErrors();
     errors.AddError("country_name", fieldError);
     Assert.AreEqual(fieldError, errors.OnField("country_name")[0]);
     Assert.AreEqual(fieldError, errors.OnField("country-name")[0]);
     Assert.AreEqual(fieldError, errors.OnField("countryName")[0]);
     Assert.AreEqual(fieldError, errors.OnField("CountryName")[0]);
 }
        /// <summary>
        /// Adds a new <b>ValidationError</b> to the collection of errors.
        /// </summary>
        /// <param name="error">The <b>ValidationError</b> to add.</param>
        public void AddError(
            ValidationError error)
        {
            if (error != null) {
            if (Errors == null) {
                Errors = new ValidationErrorCollection();
            }

            Errors.Add(error);
            }
        }
        private void PopulateSchemaId(ValidationError error)
        {
            Uri schemaId = Schema.KnownSchemas.Single(s => s.Schema == error.Schema).Id;

            error.SchemaId = schemaId;

            foreach (ValidationError validationError in error.ChildErrors)
            {
                PopulateSchemaId(validationError);
            }
        }
 public override void Validate()
 {
     var value = Value.Trim();
     double num;
     bool isNum = double.TryParse(value, out num);
     IsValid = isNum;
     if (!IsValid)
     {
         Error = new ValidationError(ValidationErrorCode.ERROR_NOT_NUMBER, "Value must be number");
     }
 }
        /// <summary>
        /// Creates a <see cref="ValidationError"/> and adds it to the collection.
        /// </summary>
        /// <param name="collection">The target collection to add to.</param>
        /// <param name="message">The associated message.</param>
        /// <param name="targetFieldKeys">The list of fields to flag with the message.</param>
        public static void Add(this ICollection<IError> collection, string errorKey, string message, params string[] targetFieldKeys)
        {
            foreach (var fieldKey in targetFieldKeys)
            {
                var err = new ValidationError(fieldKey, errorKey, message);

                if (!collection.Contains(err))
                {
                    collection.Add(new ValidationError(fieldKey, errorKey, message));
                }
            }
        }
Beispiel #15
0
        public void ShouldBuildAnElementFromErrors()
        {
            var error = new ValidationError("some error");
            var errors = new ValidationErrors<ParentInput>().Add(x => x.Child, error);
            var elementProvider = new Testable(typeof(NodeProvider<ParentInput>)).Create();

            var node = (NodeElement)elementProvider.With(errors).Build();

            Assert.That(node.Id, Is.Empty);
            var childElement = (LeafElement)node.Elements["Child"];
            Assert.That(childElement.Error, Is.EqualTo(error));
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var varDefMap = new Dictionary<string, VariableDefinition>();

            return new EnterLeaveListener(_ =>
            {
                _.Match<VariableDefinition>(
                    varDefAst => varDefMap[varDefAst.Name] = varDefAst
                );

                _.Match<Operation>(
                    enter: op => varDefMap = new Dictionary<string, VariableDefinition>(),
                    leave: op =>
                    {
                        var usages = context.GetRecursiveVariables(op);
                        usages.Apply(usage =>
                        {
                            var varName = usage.Node.Name;
                            VariableDefinition varDef;
                            if (!varDefMap.TryGetValue(varName, out varDef))
                            {
                                return;
                            }

                            if (varDef != null && usage.Type != null)
                            {
                                var varType = varDef.Type.GraphTypeFromType(context.Schema);
                                if (varType != null &&
                                    !effectiveType(varType, varDef).IsSubtypeOf(usage.Type, context.Schema))
                                {
                                    var error = new ValidationError(
                                        context.OriginalQuery,
                                        "5.7.6",
                                        BadVarPosMessage(varName, context.Print(varType), context.Print(usage.Type)));

                                    var source = new Source(context.OriginalQuery);
                                    var varDefPos = new Location(source, varDef.SourceLocation.Start);
                                    var usagePos = new Location(source, usage.Node.SourceLocation.Start);

                                    error.AddLocation(varDefPos.Line, varDefPos.Column);
                                    error.AddLocation(usagePos.Line, usagePos.Column);

                                    context.ReportError(error);
                                }
                            }
                        });
                    }
                );
            });
        }
        public void SerializeError()
        {
            ValidationError error = new ValidationError
            {
                LineNumber = 11,
                LinePosition = 5,
                Value = "A value!",
                Message = "A message!",
                Path = "sdf.sdf",
                ErrorType = ErrorType.MinimumLength,
                SchemaId = new Uri("test.xml", UriKind.RelativeOrAbsolute),
                SchemaBaseUri = new Uri("test.xml", UriKind.RelativeOrAbsolute),
                Schema = new JSchema { Type = JSchemaType.Number },
                ChildErrors =
                {
                    new ValidationError
                    {
                        Message = "Child message!"
                    }
                }
            };

            string json = JsonConvert.SerializeObject(error, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""Message"": ""A message!"",
  ""LineNumber"": 11,
  ""LinePosition"": 5,
  ""Path"": ""sdf.sdf"",
  ""Value"": ""A value!"",
  ""SchemaId"": ""test.xml"",
  ""SchemaBaseUri"": ""test.xml"",
  ""ErrorType"": ""minLength"",
  ""ChildErrors"": [
    {
      ""Message"": ""Child message!"",
      ""LineNumber"": 0,
      ""LinePosition"": 0,
      ""Path"": null,
      ""Value"": null,
      ""SchemaId"": null,
      ""SchemaBaseUri"": null,
      ""ErrorType"": ""none"",
      ""ChildErrors"": []
    }
  ]
}", json);
        }
 public INodeVisitor Validate(ValidationContext context)
 {
     return new EnterLeaveListener(_ =>
       {
     _.Match<FragmentSpread>(node =>
     {
       var fragmentName = node.Name;
       var fragment = context.GetFragment(fragmentName);
       if (fragment == null)
       {
     var error = new ValidationError(context.OriginalQuery, "5.4.2.1", UnknownFragmentMessage(fragmentName), node);
     context.ReportError(error);
       }
     });
       });
 }
        /// <summary>
        /// Returns a <see cref="bool"/> value indicating whether the resource is valid along with the associated
        /// collection of errors.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="errors">A read-only collection of the validation errors.</param>
        /// <returns>true if the resource is valid; otherwise, false.</returns>
        public virtual bool IsValid(object resource, out IReadOnlyCollection<ValidationError> errors)
        {
            if (resource == null || resource is DynamicObject || resource is JObject)
            {
                errors = new ValidationError[0];
                return true;
            }

            var context = new ValidationContext(resource, null, null);
            var results = new List<ValidationResult>();

            bool isValid = Validator.TryValidateObject(resource, context, results, true);

            errors = PopulateValidationErrors(results);
            return isValid;
        }
        public void Should_execute_all_rules_and_aggregate_results()
        {
            var record1 = new ValidationError(string.Empty);
            var record2 = new ValidationError(string.Empty);
            var record3 = new ValidationError(string.Empty);

            var xmlDocument = new HtmlDocument();

            var rule1 = MockRepository.GenerateStub<IHtmlRule>();
            var rule2 = MockRepository.GenerateStub<IHtmlRule>();
            var rule3 = MockRepository.GenerateStub<IHtmlRule>();

            rule1.Stub(rule => rule.ValidateHtml(xmlDocument)).Return(new[] {record1});
            rule2.Stub(rule => rule.ValidateHtml(xmlDocument)).Return(new ValidationError[0]);
            rule3.Stub(rule => rule.ValidateHtml(xmlDocument)).Return(new[] {record2, record3});

            ValidationError[] errors = null;

            Assert.That(errors, Is.EqualTo(new[] {record1, record2, record3}));
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            var operationCount = context.Document.Operations.Count;

            return new EnterLeaveListener(_ =>
            {
                _.Match<Operation>(op =>
                {
                    if (string.IsNullOrWhiteSpace(op.Name)
                        && operationCount > 1)
                    {
                        var error = new ValidationError(
                            context.OriginalQuery,
                            "5.1.2.1",
                            AnonOperationNotAloneMessage(),
                            op);
                        context.ReportError(error);
                    }
                });
            });
        }
Beispiel #22
0
        private void Field(GraphType type, Field field, ValidationContext context)
        {
            if (type == null)
            {
                return;
            }

            if (type.IsLeafType(context.Schema))
            {
                if (field.SelectionSet != null && field.SelectionSet.Selections.Any())
                {
                    var error = new ValidationError(context.OriginalQuery, "5.2.3", NoSubselectionAllowedMessage(field.Name, context.Print(type)), field.SelectionSet);
                    context.ReportError(error);
                }
            }
            else if(field.SelectionSet == null || !field.SelectionSet.Selections.Any())
            {
                var error = new ValidationError(context.OriginalQuery, "5.2.3", RequiredSubselectionMessage(field.Name, context.Print(type)), field);
                context.ReportError(error);
            }
        }
        public INodeVisitor Validate(ValidationContext context)
        {
            return new EnterLeaveListener(_ =>
            {
                _.Match<Argument>(argAst =>
                {
                    var argDef = context.TypeInfo.GetArgument();
                    if (argDef == null) return;

                    var type = context.Schema.FindType(argDef.Type);
                    var errors = type.IsValidLiteralValue(argAst.Value, context.Schema).ToList();
                    if (errors.Any())
                    {
                        var error = new ValidationError(
                            context.OriginalQuery,
                            "5.3.3.1",
                            BadValueMessage(argAst.Name, type, context.Print(argAst.Value), errors),
                            argAst);
                        context.ReportError(error);
                    }
                });
            });
        }
        ValidationErrorEventArgs CreateValidationErrorEventArgs(ValidationError error, ValidationErrorEventAction action)
        {
            ConstructorInfo constructor = typeof(ValidationErrorEventArgs).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(ValidationError), typeof(ValidationErrorEventAction) }, null);

            return((ValidationErrorEventArgs)constructor.Invoke(new object[] { error, action }));
        }
Beispiel #25
0
 private ValidationError AddValidationError(XmlNode n, ValidationErrorType type)
 {
     ValidationError ve=new ValidationError(n, type);
     AddValidationError(n, ve);
     return ve;
 }
Beispiel #26
0
        internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
        {
            CodeArrayCreateExpression newParent = (CodeArrayCreateExpression)expression;

            if (isWritten)
            {
                ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeObjectCreateExpression).ToString() }), 0x17a);
                item.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(item);
                return(null);
            }
            if (newParent.CreateType == null)
            {
                ValidationError error2 = new ValidationError(Messages.NullTypeType, 0x53d);
                error2.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(error2);
                return(null);
            }
            Type lhsType = validation.ResolveType(newParent.CreateType);

            if (lhsType == null)
            {
                return(null);
            }
            if (lhsType.IsArray)
            {
                ValidationError error3 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.ArrayTypeInvalid, new object[] { lhsType.Name }), 0x53d);
                error3.UserData["ErrorObject"] = newParent;
                validation.Errors.Add(error3);
                return(null);
            }
            try
            {
                if (!validation.PushParentExpression(newParent))
                {
                    return(null);
                }
                if (newParent.Size < 0)
                {
                    ValidationError error4 = new ValidationError(Messages.ArraySizeInvalid, 0x53d);
                    error4.UserData["ErrorObject"] = newParent;
                    validation.Errors.Add(error4);
                    return(null);
                }
                if (newParent.SizeExpression != null)
                {
                    RuleExpressionInfo info = RuleExpressionWalker.Validate(validation, newParent.SizeExpression, false);
                    if (info == null)
                    {
                        return(null);
                    }
                    if (((info.ExpressionType != typeof(int)) && (info.ExpressionType != typeof(uint))) && ((info.ExpressionType != typeof(long)) && (info.ExpressionType != typeof(ulong))))
                    {
                        ValidationError error5 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.ArraySizeTypeInvalid, new object[] { info.ExpressionType.Name }), 0x53d);
                        error5.UserData["ErrorObject"] = newParent;
                        validation.Errors.Add(error5);
                        return(null);
                    }
                }
                bool flag = false;
                for (int i = 0; i < newParent.Initializers.Count; i++)
                {
                    CodeExpression expression3 = newParent.Initializers[i];
                    if (expression3 == null)
                    {
                        ValidationError error6 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.MissingInitializer, new object[] { lhsType.Name }), 0x53d);
                        error6.UserData["ErrorObject"] = newParent;
                        validation.Errors.Add(error6);
                        return(null);
                    }
                    RuleExpressionInfo info2 = RuleExpressionWalker.Validate(validation, expression3, false);
                    if (info2 == null)
                    {
                        flag = true;
                    }
                    else
                    {
                        ValidationError error7;
                        if (!RuleValidation.StandardImplicitConversion(info2.ExpressionType, lhsType, expression3, out error7))
                        {
                            if (error7 != null)
                            {
                                error7.UserData["ErrorObject"] = newParent;
                                validation.Errors.Add(error7);
                            }
                            error7 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InitializerMismatch, new object[] { i, lhsType.Name }), 0x545);
                            error7.UserData["ErrorObject"] = newParent;
                            validation.Errors.Add(error7);
                            return(null);
                        }
                    }
                }
                if (flag)
                {
                    return(null);
                }
                double size = -1.0;
                if (newParent.SizeExpression != null)
                {
                    CodePrimitiveExpression sizeExpression = newParent.SizeExpression as CodePrimitiveExpression;
                    if ((sizeExpression != null) && (sizeExpression.Value != null))
                    {
                        size = (double)Executor.AdjustType(sizeExpression.Value.GetType(), sizeExpression.Value, typeof(double));
                    }
                    if (newParent.Size > 0)
                    {
                        ValidationError error8 = new ValidationError(Messages.ArraySizeBoth, 0x53d);
                        error8.UserData["ErrorObject"] = newParent;
                        validation.Errors.Add(error8);
                        return(null);
                    }
                }
                else if (newParent.Size > 0)
                {
                    size = newParent.Size;
                }
                if ((size >= 0.0) && (newParent.Initializers.Count > size))
                {
                    ValidationError error9 = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InitializerCountMismatch, new object[] { newParent.Initializers.Count, size }), 0x545);
                    error9.UserData["ErrorObject"] = newParent;
                    validation.Errors.Add(error9);
                    return(null);
                }
            }
            finally
            {
                validation.PopParentExpression();
            }
            return(new RuleExpressionInfo(lhsType.MakeArrayType()));
        }
        public virtual IHttpActionResult UpdateContent(string path, [FromBody] Dictionary <string, object> newProperties, EPiServer.DataAccess.SaveAction action = EPiServer.DataAccess.SaveAction.Save)
        {
            path = path ?? "";
            var contentRef = FindContentReference(path);

            if (contentRef == ContentReference.EmptyReference)
            {
                return(NotFound());
            }
            if (contentRef == ContentReference.RootPage)
            {
                return(BadRequestErrorCode("UPDATE_ROOT_NOT_ALLOWED"));
            }

            if (!TryGetCultureInfo(out string language, out CultureInfo cultureInfo))
            {
                return(BadRequestInvalidLanguage(language));
            }

            if (!_repo.TryGet(contentRef, cultureInfo, out IContent originalContent))
            {
                return(NotFound());
            }

            if (newProperties == null)
            {
                return(BadRequestErrorCode("BODY_EMPTY"));
            }

            foreach (String property in NonCreatingProperties)
            {
                if (newProperties.ContainsKey(property))
                {
                    newProperties.Remove(property);
                }
            }

            foreach (String property in NonUpdatingProperties)
            {
                if (newProperties.ContainsKey(property))
                {
                    newProperties.Remove(property);
                }
            }

            var content = (originalContent as IReadOnly).CreateWritableClone() as IContent;

            EPiServer.DataAccess.SaveAction saveaction = action;
            if (newProperties.ContainsKey("SaveAction") && ((string)newProperties["SaveAction"]) == "Publish")
            {
                saveaction = EPiServer.DataAccess.SaveAction.Publish;
                newProperties.Remove("SaveAction");
            }
            if (newProperties.ContainsKey("SaveAction") && ((string)newProperties["SaveAction"]) == "RequestApproval")
            {
                saveaction = EPiServer.DataAccess.SaveAction.RequestApproval;
                newProperties.Remove("SaveAction");
            }
            if (newProperties.ContainsKey("SaveAction") && ((string)newProperties["SaveAction"]) == "CheckIn")
            {
                saveaction = EPiServer.DataAccess.SaveAction.CheckIn;
                newProperties.Remove("SaveAction");
            }

            IContent moveTo = null;

            if (newProperties.ContainsKey(MoveEntityToPropertyKey))
            {
                if (!(newProperties[MoveEntityToPropertyKey] is string))
                {
                    return(BadRequestValidationErrors(ValidationError.InvalidType(MoveEntityToPropertyKey, typeof(string))));
                }

                var moveToPath = (string)newProperties[MoveEntityToPropertyKey];
                if (!moveToPath.StartsWith("/"))
                {
                    return(BadRequestValidationErrors(ValidationError.CustomError(MoveEntityToPropertyKey, "FIELD_INVALID_FORMAT", $"{MoveEntityToPropertyKey} should start with a /")));
                }

                if (!_repo.TryGet(FindContentReference(moveToPath.Substring(1)), out moveTo))
                {
                    return(BadRequestValidationErrors(ValidationError.CustomError(MoveEntityToPropertyKey, "TARGET_CONTAINER_NOT_FOUND", "The target container was not found")));
                }

                newProperties.Remove(MoveEntityToPropertyKey);
            }

            if (newProperties.ContainsKey("Name"))
            {
                content.Name = newProperties["Name"].ToString();
                newProperties.Remove("Name");
            }

            // Store the new information in the object.
            var errors = UpdateContentProperties(newProperties, content);

            if (errors.Any())
            {
                return(BadRequestValidationErrors(errors.ToArray()));
            }

            var validationErrors = _validationService.Validate(content);

            if (validationErrors.Any())
            {
                return(BadRequestValidationErrors(validationErrors.Select(ValidationError.FromEpiserver).ToArray()));
            }

            if (!HasAccess(content, EPiServer.Security.AccessLevel.Edit | EPiServer.Security.AccessLevel.Publish))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if (moveTo != null)
            {
                if (!HasAccess(content, EPiServer.Security.AccessLevel.Read | EPiServer.Security.AccessLevel.Delete))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }

                if (!HasAccess(moveTo, EPiServer.Security.AccessLevel.Create | EPiServer.Security.AccessLevel.Publish))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }
            }

            //from here on we're going to try to save things to the database, we have tried to optimize the chance of succeeding above

            if (moveTo != null)
            {
                try
                {
                    _repo.Move(contentRef, moveTo.ContentLink);
                }
                catch (ContentNotFoundException)
                {
                    //even though we already check for this above, we still handle it here for cases that we might not have foreseen
                    return(BadRequestValidationErrors(ValidationError.CustomError(MoveEntityToPropertyKey, "TARGET_CONTAINER_NOT_FOUND", "The target container was not found")));
                }
                catch (AccessDeniedException)
                {
                    //even though we already check for this above, we still handle it here for cases that we might not have foreseen
                    return(StatusCode(HttpStatusCode.Forbidden));
                }
            }

            try
            {
                var updatedReference = _repo.Save(content, saveaction);
                if (TryGetProject(out int projectId, out Project project))
                {
                    ProjectItem projectItem = new ProjectItem(projectId, content);
                    _projectrepo.SaveItems(new ProjectItem[] { projectItem });
                }
                return(Ok(new { reference = updatedReference.ToString() }));
            }
            catch (Exception)
            {
                if (moveTo != null)
                {
                    //try to undo the move. We've tried using TransactionScope for this, but it doesn't play well with Episerver (caching, among other problems)
                    _repo.Move(contentRef, originalContent.ParentLink);
                }
                throw;
            }
        }
        protected override void Simpan()
        {
            var total = SumGrid(this._listOfItemPengeluaran);

            if (!(total > 0))
            {
                MsgHelper.MsgWarning("Anda belum melengkapi inputan data produk !");
                return;
            }

            if (!MsgHelper.MsgKonfirmasi("Apakah proses ingin dilanjutkan ?"))
            {
                return;
            }

            if (_isNewData)
            {
                _pengeluaran = new PengeluaranBiaya();
            }

            _pengeluaran.pengguna_id = this._pengguna.pengguna_id;
            _pengeluaran.Pengguna    = this._pengguna;
            _pengeluaran.nota        = txtNota.Text;
            _pengeluaran.tanggal     = dtpTanggal.Value;
            _pengeluaran.keterangan  = txtKeterangan.Text;

            _pengeluaran.item_pengeluaran_biaya = this._listOfItemPengeluaran.Where(f => f.JenisPengeluaran != null).ToList();

            if (!_isNewData) // update
            {
                _pengeluaran.item_pengeluaran_biaya_deleted = _listOfItemPengeluaranDeleted;
            }

            var result          = 0;
            var validationError = new ValidationError();

            using (new StCursor(Cursors.WaitCursor, new TimeSpan(0, 0, 0, 0)))
            {
                if (_isNewData)
                {
                    result = _bll.Save(_pengeluaran, ref validationError);
                }
                else
                {
                    result = _bll.Update(_pengeluaran, ref validationError);
                }

                if (result > 0)
                {
                    Listener.Ok(this, _isNewData, _pengeluaran);

                    _listOfItemPengeluaran.Clear();
                    _listOfItemPengeluaranDeleted.Clear();

                    this.Close();
                }
                else
                {
                    if (validationError.Message.Length > 0)
                    {
                        MsgHelper.MsgWarning(validationError.Message);
                        base.SetFocusObject(validationError.PropertyName, this);
                    }
                    else
                    {
                        MsgHelper.MsgUpdateError();
                    }
                }
            }
        }
Beispiel #29
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            InvokeWebServiceActivity invokeWebService = obj as InvokeWebServiceActivity;

            if (invokeWebService == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(InvokeWebServiceActivity).FullName), "obj");
            }

            if (invokeWebService.ProxyClass == null)
            {
                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "ProxyClass"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = "ProxyClass";
                validationErrors.Add(error);
            }
            else
            {
                ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
                }

                Type proxyClassType = invokeWebService.ProxyClass;

                // Validate method
                if (invokeWebService.MethodName == null || invokeWebService.MethodName.Length == 0)
                {
                    validationErrors.Add(ValidationError.GetNotSetValidationError("MethodName"));
                }
                else
                {
                    MethodInfo methodInfo = proxyClassType.GetMethod(invokeWebService.MethodName);
                    if (methodInfo == null)
                    {
                        ValidationError error = new ValidationError(SR.GetString(SR.Error_MethodNotExists, "MethodName", invokeWebService.MethodName), ErrorNumbers.Error_MethodNotExists);
                        error.PropertyName = "MethodName";
                        validationErrors.Add(error);
                    }
                    else
                    {
                        ArrayList paramInfos = new ArrayList(methodInfo.GetParameters());
                        if (methodInfo.ReturnType != typeof(void))
                        {
                            paramInfos.Add(methodInfo.ReturnParameter);
                        }

                        foreach (ParameterInfo paramInfo in paramInfos)
                        {
                            string paramName = paramInfo.Name;
                            if (paramInfo.Position == -1)
                            {
                                paramName = "(ReturnValue)";
                            }

                            object paramValue = null;
                            if (invokeWebService.ParameterBindings.Contains(paramName))
                            {
                                if (invokeWebService.ParameterBindings[paramName].IsBindingSet(WorkflowParameterBinding.ValueProperty))
                                {
                                    paramValue = invokeWebService.ParameterBindings[paramName].GetBinding(WorkflowParameterBinding.ValueProperty);
                                }
                                else
                                {
                                    paramValue = invokeWebService.ParameterBindings[paramName].GetValue(WorkflowParameterBinding.ValueProperty);
                                }
                            }
                            if (!invokeWebService.ParameterBindings.Contains(paramName) || paramValue == null)
                            {
                                ValidationError validationError = ValidationError.GetNotSetValidationError(paramName);
                                if (InvokeWebServiceActivity.ReservedParameterNames.Contains(paramName))
                                {
                                    validationError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(invokeWebService.GetType(), paramName);
                                }
                                validationError.PropertyName = paramName;
                                validationErrors.Add(validationError);
                            }
                            else
                            {
                                AccessTypes access = AccessTypes.Read;
                                if (paramInfo.IsOut || paramInfo.IsRetval)
                                {
                                    access = AccessTypes.Write;
                                }
                                else if (paramInfo.ParameterType.IsByRef)
                                {
                                    access |= AccessTypes.Write;
                                }

                                ValidationErrorCollection variableErrors = ValidationHelpers.ValidateProperty(manager, invokeWebService, paramValue,
                                                                                                              new PropertyValidationContext(invokeWebService.ParameterBindings[paramName], null, paramName), new BindValidationContext(paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType, access));
                                if (InvokeWebServiceActivity.ReservedParameterNames.Contains(paramName))
                                {
                                    foreach (ValidationError validationError in variableErrors)
                                    {
                                        validationError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(invokeWebService.GetType(), paramName);
                                    }
                                }
                                validationErrors.AddRange(variableErrors);
                            }
                        }

                        if (invokeWebService.ParameterBindings.Count > paramInfos.Count)
                        {
                            validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_AdditionalBindingsFound), ErrorNumbers.Warning_AdditionalBindingsFound, true));
                        }
                    }
                }
            }
            return(validationErrors);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BraintreeApiException"/> class.
 /// </summary>
 /// <param name="validationError">
 /// The validation error.
 /// </param>
 public BraintreeApiException(ValidationError validationError)
     : this(new[] { validationError})
 {
 }
 public void AddResult(string actionName, ValidationError error, ValidationOutcome?outcome = null)
 {
     this[actionName].AddResults(new ValidationError[] { error }, outcome);
 }
        protected override void Simpan()
        {
            if (this._supplier == null || txtSupplier.Text.Length == 0)
            {
                MsgHelper.MsgWarning("'Supplier' tidak boleh kosong !");
                txtSupplier.Focus();

                return;
            }

            var total = SumGrid(this._listOfItemBeli);

            if (!(total > 0))
            {
                MsgHelper.MsgWarning("Anda belum melengkapi inputan data produk !");
                return;
            }

            if (rdoKredit.Checked)
            {
                if (!DateTimeHelper.IsValidRangeTanggal(dtpTanggal.Value, dtpTanggalTempo.Value))
                {
                    MsgHelper.MsgNotValidRangeTanggal();
                    return;
                }
            }

            if (!MsgHelper.MsgKonfirmasi("Apakah proses ingin dilanjutkan ?"))
            {
                return;
            }

            if (_isNewData)
            {
                _beli = new BeliProduk();
            }

            _beli.pengguna_id   = this._pengguna.pengguna_id;
            _beli.Pengguna      = this._pengguna;
            _beli.supplier_id   = this._supplier.supplier_id;
            _beli.Supplier      = this._supplier;
            _beli.nota          = txtNota.Text;
            _beli.tanggal       = dtpTanggal.Value;
            _beli.tanggal_tempo = DateTimeHelper.GetNullDateTime();
            _beli.is_tunai      = rdoTunai.Checked;

            if (rdoKredit.Checked) // pembelian kredit
            {
                _beli.tanggal_tempo = dtpTanggalTempo.Value;
            }

            _beli.ppn        = NumberHelper.StringToDouble(txtPPN.Text);
            _beli.diskon     = NumberHelper.StringToDouble(txtDiskon.Text);
            _beli.keterangan = txtKeterangan.Text;

            _beli.item_beli = this._listOfItemBeli.Where(f => f.Produk != null).ToList();
            foreach (var item in _beli.item_beli)
            {
                if (!(item.harga > 0))
                {
                    item.harga = item.Produk.harga_beli;
                }
            }

            if (!_isNewData) // update
            {
                _beli.item_beli_deleted = _listOfItemBeliDeleted;
            }

            var result          = 0;
            var validationError = new ValidationError();

            using (new StCursor(Cursors.WaitCursor, new TimeSpan(0, 0, 0, 0)))
            {
                if (_isNewData)
                {
                    result = _bll.Save(_beli, ref validationError);
                }
                else
                {
                    result = _bll.Update(_beli, ref validationError);
                }

                if (result > 0)
                {
                    try
                    {
                        if (chkCetakNotaBeli.Checked)
                        {
                            CetakNota(_beli.beli_produk_id);
                        }
                    }
                    catch
                    {
                    }

                    Listener.Ok(this, _isNewData, _beli);

                    _supplier = null;
                    _listOfItemBeli.Clear();
                    _listOfItemBeliDeleted.Clear();

                    this.Close();
                }
                else
                {
                    if (validationError.Message.NullToString().Length > 0)
                    {
                        MsgHelper.MsgWarning(validationError.Message);
                        base.SetFocusObject(validationError.PropertyName, this);
                    }
                    else
                    {
                        MsgHelper.MsgUpdateError();
                    }
                }
            }
        }
        /// <summary>
        /// Tests whether a value is valid against a single <see cref="ValidationAttribute"/> using the <see cref="ValidationContext"/>.
        /// </summary>
        /// <param name="value">The value to be tested for validity.</param>
        /// <param name="validationContext">Describes the property member to validate.</param>
        /// <param name="attribute">The validation attribute to test.</param>
        /// <param name="validationError">The validation error that occurs during validation.  Will be <c>null</c> when the return value is <c>true</c>.</param>
        /// <returns><c>true</c> if the value is valid.</returns>
        /// <exception cref="ArgumentNullException">When <paramref name="validationContext"/> is null.</exception>
        private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute, out ValidationError validationError)
        {
            if (validationContext == null) {
                throw new ArgumentNullException("validationContext");
            }

            ValidationResult validationResult = attribute.GetValidationResult(value, validationContext);
            if (validationResult != ValidationResult.Success) {
                validationError = new ValidationError(attribute, value, validationResult);
                return false;
            }

            validationError = null;
            return true;
        }
Beispiel #34
0
        public void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object?value, IList <ValidationError>?childErrors)
        {
            ValidationError error = CreateError(message, errorType, schema, value, childErrors);

            RaiseError(error);
        }
Beispiel #35
0
        protected ValidationError CreateError(IFormattable message, ErrorType errorType, JSchema schema, object?value, IList <ValidationError>?childErrors, IJsonLineInfo?lineInfo, string path)
        {
            ValidationError error = ValidationError.CreateValidationError(message, errorType, schema, null, value, childErrors, lineInfo, path);

            return(error);
        }
Beispiel #36
0
 public AssemblyError(int lineNumber, LineSection lineSection, int causeStartIndex, int causeLength, ValidationError error)
     : base(Severity.Error, lineNumber, lineSection, causeStartIndex, causeLength, error)
 {
 }
 /// <summary>
 /// Overriden. Compares if a <see cref="ValidationError"/> instance is equal to this
 /// <see cref="ValidationError"/> instance.
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public bool Equals(ValidationError obj)
 {
     return Equals(obj.Message, Message) && Equals(obj.Property, Property);
 }
 private void DefaultLogMessage(ValidationError msg)
 {
     // Empty method
 }
Beispiel #39
0
        internal override bool Validate(RuleValidation validation)
        {
            bool flag = false;
            RuleExpressionInfo info = null;

            if (this.assignStatement.Left == null)
            {
                ValidationError item = new ValidationError(Messages.NullAssignLeft, 0x541);
                item.UserData["ErrorObject"] = this.assignStatement;
                validation.Errors.Add(item);
            }
            else
            {
                info = validation.ExpressionInfo(this.assignStatement.Left);
                if (info == null)
                {
                    info = RuleExpressionWalker.Validate(validation, this.assignStatement.Left, true);
                }
            }
            RuleExpressionInfo info2 = null;

            if (this.assignStatement.Right == null)
            {
                ValidationError error2 = new ValidationError(Messages.NullAssignRight, 0x543);
                error2.UserData["ErrorObject"] = this.assignStatement;
                validation.Errors.Add(error2);
            }
            else
            {
                info2 = RuleExpressionWalker.Validate(validation, this.assignStatement.Right, false);
            }
            if ((info == null) || (info2 == null))
            {
                return(flag);
            }
            Type expressionType = info2.ExpressionType;
            Type lhsType        = info.ExpressionType;

            if (lhsType == typeof(NullLiteral))
            {
                ValidationError error3 = new ValidationError(Messages.NullAssignLeft, 0x542);
                error3.UserData["ErrorObject"] = this.assignStatement;
                validation.Errors.Add(error3);
                return(false);
            }
            if (lhsType != expressionType)
            {
                ValidationError error = null;
                if (!RuleValidation.TypesAreAssignable(expressionType, lhsType, this.assignStatement.Right, out error))
                {
                    if (error == null)
                    {
                        error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.AssignNotAllowed, new object[] { RuleDecompiler.DecompileType(expressionType), RuleDecompiler.DecompileType(lhsType) }), 0x545);
                    }
                    error.UserData["ErrorObject"] = this.assignStatement;
                    validation.Errors.Add(error);
                    return(flag);
                }
            }
            return(true);
        }
 protected override string FormatErrorMessage(ValidationError error)
 {
     return(FormatErrorMessage(Errors.ResourceManager, Errors.Culture, error) ?? base.FormatErrorMessage(error));
 }
        private static void ProcessActivity(ChildActivity childActivity, ref ChildActivity nextActivity, ref Stack <ChildActivity> activitiesRemaining, ActivityCallStack parentChain, ref IList <ValidationError> validationErrors, ProcessActivityTreeOptions options, ProcessActivityCallback callback)
        {
            Activity                element            = childActivity.Activity;
            IList <Constraint>      runtimeConstraints = element.RuntimeConstraints;
            IList <ValidationError> list2 = null;

            if (!element.HasStartedCachingMetadata)
            {
                element.MemberOf.AddMember(element);
                element.InternalCacheMetadata(options.CreateEmptyBindings, ref list2);
                ActivityValidationServices.ValidateArguments(element, element.Parent == null, ref list2);
                ActivityLocationReferenceEnvironment environment  = null;
                ActivityLocationReferenceEnvironment environment2 = new ActivityLocationReferenceEnvironment(element.HostEnvironment)
                {
                    InternalRoot = element
                };
                int nextEnvironmentId = 0;
                ProcessChildren(element, element.Children, ActivityCollectionType.Public, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessChildren(element, element.ImportedChildren, ActivityCollectionType.Imports, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessChildren(element, element.ImplementationChildren, ActivityCollectionType.Implementation, !options.SkipPrivateChildren, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessArguments(element, element.RuntimeArguments, true, ref environment2, ref nextEnvironmentId, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessVariables(element, element.RuntimeVariables, ActivityCollectionType.Public, true, ref environment, ref nextEnvironmentId, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessVariables(element, element.ImplementationVariables, ActivityCollectionType.Implementation, !options.SkipPrivateChildren, ref environment2, ref nextEnvironmentId, ref nextActivity, ref activitiesRemaining, ref list2);
                if (element.HandlerOf != null)
                {
                    for (int i = 0; i < element.HandlerOf.RuntimeDelegateArguments.Count; i++)
                    {
                        RuntimeDelegateArgument argument      = element.HandlerOf.RuntimeDelegateArguments[i];
                        DelegateArgument        boundArgument = argument.BoundArgument;
                        if ((boundArgument != null) && boundArgument.InitializeRelationship(element, ref list2))
                        {
                            boundArgument.Id = nextEnvironmentId;
                            nextEnvironmentId++;
                        }
                    }
                }
                if (environment == null)
                {
                    element.PublicEnvironment = new ActivityLocationReferenceEnvironment(element.GetParentEnvironment());
                }
                else
                {
                    if (environment.Parent == null)
                    {
                        environment.InternalRoot = element;
                    }
                    element.PublicEnvironment = environment;
                }
                element.ImplementationEnvironment = environment2;
                ProcessDelegates(element, element.Delegates, ActivityCollectionType.Public, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessDelegates(element, element.ImportedDelegates, ActivityCollectionType.Imports, true, ref nextActivity, ref activitiesRemaining, ref list2);
                ProcessDelegates(element, element.ImplementationDelegates, ActivityCollectionType.Implementation, !options.SkipPrivateChildren, ref nextActivity, ref activitiesRemaining, ref list2);
                if (callback != null)
                {
                    callback(childActivity, parentChain);
                }
                if (list2 != null)
                {
                    Activity activity2;
                    if (validationErrors == null)
                    {
                        validationErrors = new List <ValidationError>();
                    }
                    string str = ActivityValidationServices.GenerateValidationErrorPrefix(childActivity.Activity, parentChain, out activity2);
                    for (int j = 0; j < list2.Count; j++)
                    {
                        ValidationError item = list2[j];
                        item.Source = activity2;
                        item.Id     = activity2.Id;
                        if (!string.IsNullOrEmpty(str))
                        {
                            item.Message = str + item.Message;
                        }
                        validationErrors.Add(item);
                    }
                    list2 = null;
                }
                if (options.StoreTempViolations && (validationErrors != null))
                {
                    childActivity.Activity.SetTempValidationErrorCollection(validationErrors);
                    validationErrors = null;
                }
            }
            else
            {
                SetupForProcessing(element.Children, true, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.ImportedChildren, false, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.RuntimeArguments, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.RuntimeVariables, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.Delegates, true, ref nextActivity, ref activitiesRemaining);
                SetupForProcessing(element.ImportedDelegates, false, ref nextActivity, ref activitiesRemaining);
                if (!options.SkipPrivateChildren)
                {
                    SetupForProcessing(element.ImplementationChildren, true, ref nextActivity, ref activitiesRemaining);
                    SetupForProcessing(element.ImplementationDelegates, true, ref nextActivity, ref activitiesRemaining);
                    SetupForProcessing(element.ImplementationVariables, ref nextActivity, ref activitiesRemaining);
                }
                if ((callback != null) && !options.OnlyCallCallbackForDeclarations)
                {
                    callback(childActivity, parentChain);
                }
                if (childActivity.Activity.HasTempViolations && !options.StoreTempViolations)
                {
                    childActivity.Activity.TransferTempValidationErrors(ref validationErrors);
                }
            }
            if ((!options.SkipConstraints && parentChain.WillExecute) && (childActivity.CanBeExecuted && (runtimeConstraints.Count > 0)))
            {
                ActivityValidationServices.RunConstraints(childActivity, parentChain, runtimeConstraints, options, false, ref validationErrors);
            }
        }
Beispiel #42
0
 public ValidationResult(ValidationError error, bool isValid)
 {
     this.Error   = error;
     this.IsValid = isValid;
 }
Beispiel #43
0
 public void AddError(ValidationError validationError)
 {
     _errors.Add(validationError);
 }
        private void DiscoverInternal(JSchema schema, string latestPath)
        {
            if (schema.Reference != null)
            {
                return;
            }

            if (_knownSchemas.Any(s => s.Schema == schema))
            {
                return;
            }

            Uri    newScopeId;
            string scopePath     = latestPath;
            Uri    schemaKnownId = GetSchemaIdAndNewScopeId(schema, ref scopePath, out newScopeId);

            // check whether a schema with the resolved id is already known
            // this will be hit when a schema contains duplicate ids or references a schema with a duplicate id
            bool existingSchema = _knownSchemas.Any(s => UriComparer.Instance.Equals(s.Id, schemaKnownId));

#if DEBUG
            if (_knownSchemas.Any(s => s.Schema == schema))
            {
                throw new InvalidOperationException("Schema with id '{0}' already a known schema.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId));
            }
#endif

            // add schema to known schemas whether duplicate or not to avoid multiple errors
            // the first schema with a duplicate id will be used
            _knownSchemas.Add(new KnownSchema(schemaKnownId, schema, _state));

            if (existingSchema)
            {
                if (ValidationErrors != null)
                {
                    ValidationError error = ValidationError.CreateValidationError("Duplicate schema id '{0}' encountered.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId.OriginalString), ErrorType.Id, schema, null, schemaKnownId, null, schema, schema.Path);
                    ValidationErrors.Add(error);
                }

                return;
            }

            _pathStack.Push(new SchemaPath(newScopeId, scopePath));

            // discover should happen in the same order as writer except extension data (e.g. definitions)
            if (schema._extensionData != null)
            {
                foreach (KeyValuePair <string, JToken> valuePair in schema._extensionData)
                {
                    DiscoverTokenSchemas(EscapePath(valuePair.Key), valuePair.Value);
                }
            }

            DiscoverSchema(Constants.PropertyNames.AdditionalProperties, schema.AdditionalProperties);
            DiscoverSchema(Constants.PropertyNames.AdditionalItems, schema.AdditionalItems);
            DiscoverDictionarySchemas(Constants.PropertyNames.Properties, schema._properties);
            DiscoverDictionarySchemas(Constants.PropertyNames.PatternProperties, schema._patternProperties);
            DiscoverDictionarySchemas(Constants.PropertyNames.Dependencies, schema._dependencies);
            DiscoverArraySchemas(Constants.PropertyNames.Items, schema._items);
            DiscoverArraySchemas(Constants.PropertyNames.AllOf, schema._allOf);
            DiscoverArraySchemas(Constants.PropertyNames.AnyOf, schema._anyOf);
            DiscoverArraySchemas(Constants.PropertyNames.OneOf, schema._oneOf);
            DiscoverSchema(Constants.PropertyNames.Not, schema.Not);

            _pathStack.Pop();
        }
        public virtual IHttpActionResult CreateContent(string path, [FromBody] Dictionary <string, object> contentProperties, EPiServer.DataAccess.SaveAction action = EPiServer.DataAccess.SaveAction.Save)
        {
            path = path ?? "";
            var parentContentRef = FindContentReference(path);

            if (parentContentRef == ContentReference.EmptyReference)
            {
                return(NotFound());
            }
            if (!ReferenceExists(parentContentRef))
            {
                return(NotFound());
            }

            // Instantiate content of named type.
            if (contentProperties == null)
            {
                return(BadRequestErrorCode("BODY_EMPTY"));
            }

            foreach (String property in NonCreatingProperties)
            {
                if (contentProperties.ContainsKey(property))
                {
                    contentProperties.Remove(property);
                }
            }
            object contentTypeString;

            if (!(contentProperties.TryGetValue("ContentType", out contentTypeString) || contentProperties.TryGetValue("__EpiserverContentType", out contentTypeString)))
            {
                return(BadRequestValidationErrors(ValidationError.Required("ContentType")));
            }

            if (contentProperties.ContainsKey("ContentType"))
            {
                contentProperties.Remove("ContentType");
            }

            if (contentProperties.ContainsKey("__EpiserverContentType"))
            {
                contentProperties.Remove("__EpiserverContentType");
            }

            if (!(contentTypeString is string))
            {
                return(BadRequestValidationErrors(ValidationError.InvalidType("ContentType", typeof(string))));
            }

            // Check ContentType.
            ContentType contentType = FindEpiserverContentType(contentTypeString);

            if (contentType == null)
            {
                return(BadRequestValidationErrors(ValidationError.CustomError("ContentType", "CONTENT_TYPE_INVALID", $"Could not find contentType {contentTypeString}")));
            }

            if (!contentProperties.TryGetValue("Name", out object nameValue))
            {
                return(BadRequestValidationErrors(ValidationError.Required("Name")));
            }
            contentProperties.Remove("Name");

            if (!(nameValue is string))
            {
                return(BadRequestValidationErrors(ValidationError.InvalidType("Name", typeof(string))));
            }

            EPiServer.DataAccess.SaveAction saveaction = action;
            if (contentProperties.ContainsKey("SaveAction") && (string)contentProperties["SaveAction"] == "Publish")
            {
                saveaction = EPiServer.DataAccess.SaveAction.Publish;
                contentProperties.Remove("SaveAction");
            }
            if (contentProperties.ContainsKey("SaveAction") && (string)contentProperties["SaveAction"] == "RequestApproval")
            {
                saveaction = EPiServer.DataAccess.SaveAction.RequestApproval;
                contentProperties.Remove("SaveAction");
            }
            if (contentProperties.ContainsKey("SaveAction") && ((string)contentProperties["SaveAction"]) == "CheckIn")
            {
                saveaction = EPiServer.DataAccess.SaveAction.CheckIn;
                contentProperties.Remove("SaveAction");
            }

            // Create content.
            IContent content;

            CultureInfo cultureInfo = null;

            // Check if a Language tag is set.
            if (contentProperties.TryGetValue("__EpiserverCurrentLanguage", out object languageValue))
            {
                if (!(languageValue is string))
                {
                    return(BadRequestValidationErrors(ValidationError.InvalidType("__EpiserverCurrentLanguage", typeof(string))));
                }

                if (!TryGetCultureInfo((string)languageValue, out cultureInfo))
                {
                    if (cultureInfo == null || !GetLanguages().Any(ci => ci.TwoLetterISOLanguageName == cultureInfo.TwoLetterISOLanguageName))
                    {
                        return(BadRequestInvalidLanguage(languageValue.ToString()));
                    }
                    cultureInfo = new CultureInfo(cultureInfo.TwoLetterISOLanguageName);
                }

                if (!GetLanguages().Any(ci => ci.TwoLetterISOLanguageName == cultureInfo.TwoLetterISOLanguageName))
                {
                    return(BadRequestInvalidLanguage(languageValue.ToString()));
                }
                cultureInfo = new CultureInfo(cultureInfo.TwoLetterISOLanguageName);


                if (_repo.TryGet <IContent>(parentContentRef, cultureInfo, out IContent parent))
                {
                    return(BadRequestLanguageBranchExists(parent, cultureInfo.TwoLetterISOLanguageName));
                }

                content = _repo.CreateLanguageBranch <IContent>(parentContentRef, cultureInfo);
            }
            else
            {
                content = _repo.GetDefault <IContent>(parentContentRef, contentType.ID);
            }
            if (contentProperties.ContainsKey("__EpiserverCurrentLanguage"))
            {
                contentProperties.Remove("__EpiserverCurrentLanguage");
            }

            content.Name = (string)nameValue;

            // Set all the other values.
            var errors = UpdateContentProperties(contentProperties, content);

            if (errors.Any())
            {
                return(BadRequestValidationErrors(errors.ToArray()));
            }

            var validationErrors = _validationService.Validate(content);

            if (validationErrors.Any())
            {
                return(BadRequestValidationErrors(validationErrors.Select(ValidationError.FromEpiserver).ToArray()));
            }

            // Save the reference with the requested save action.
            try
            {
                var createdReference = _repo.Save(content, saveaction);
                if (TryGetProject(out int projectId, out Project project))
                {
                    ProjectItem projectItem = new ProjectItem(projectId, content);
                    _projectrepo.SaveItems(new ProjectItem[] { projectItem });
                }
                return(Created(path, new { reference = createdReference.ID, __EpiserverCurrentLanguage = cultureInfo }));
            }
            catch (AccessDeniedException)
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }
            catch (EPiServerException)
            {
                return(BadRequestValidationErrors(ValidationError.TypeCannotBeUsed("ContentType", contentType.Name, _repo.Get <IContent>(parentContentRef).GetOriginalType().Name)));
            }
        }
Beispiel #46
0
        /// <summary>
        /// Tests whether a value is valid against a single <see cref="ValidationAttribute"/> using the <see cref="ValidationContext"/>.
        /// </summary>
        /// <param name="value">The value to be tested for validity.</param>
        /// <param name="validationContext">Describes the property member to validate.</param>
        /// <param name="attribute">The validation attribute to test.</param>
        /// <param name="validationError">The validation error that occurs during validation.  Will be <c>null</c> when the return value is <c>true</c>.</param>
        /// <returns><c>true</c> if the value is valid.</returns>
        /// <exception cref="ArgumentNullException">When <paramref name="validationContext"/> is null.</exception>
        private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute, out ValidationError validationError)
        {
            if (validationContext == null)
            {
                throw new ArgumentNullException("validationContext");
            }

            ValidationResult validationResult = attribute.GetValidationResult(value, validationContext);

            if (validationResult != ValidationResult.Success)
            {
                validationError = new ValidationError(attribute, value, validationResult);
                return(false);
            }

            validationError = null;
            return(true);
        }
Beispiel #47
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (manager.Context == null)
            {
                throw new InvalidOperationException(Messages.ContextStackMissing);
            }

            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            RuleConditionReference declarativeCondition = obj as RuleConditionReference;

            if (declarativeCondition == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.UnexpectedArgumentType, typeof(RuleConditionReference).FullName, "obj");
                throw new ArgumentException(message, "obj");
            }

            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, typeof(Activity).Name);
                throw new InvalidOperationException(message);
            }

            PropertyValidationContext validationContext = manager.Context[typeof(PropertyValidationContext)] as PropertyValidationContext;

            if (validationContext == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, typeof(PropertyValidationContext).Name);
                throw new InvalidOperationException(message);
            }
            if (!string.IsNullOrEmpty(declarativeCondition.ConditionName))
            {
                RuleDefinitions         rules = null;
                RuleConditionCollection conditionDefinitions = null;

                CompositeActivity declaringActivity = Helpers.GetDeclaringActivity(activity);
                if (declaringActivity == null)
                {
                    declaringActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
                }
                if (activity.Site != null)
                {
                    rules = ConditionHelper.Load_Rules_DT(activity.Site, declaringActivity);
                }
                else
                {
                    rules = ConditionHelper.Load_Rules_RT(declaringActivity);
                }

                if (rules != null)
                {
                    conditionDefinitions = rules.Conditions;
                }

                if (conditionDefinitions == null || !conditionDefinitions.Contains(declarativeCondition.ConditionName))
                {
                    string          message         = string.Format(CultureInfo.CurrentCulture, Messages.ConditionNotFound, declarativeCondition.ConditionName);
                    ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_ConditionNotFound);
                    validationError.PropertyName = GetFullPropertyName(manager) + "." + "ConditionName";
                    validationErrors.Add(validationError);
                }
                else
                {
                    RuleCondition actualCondition = conditionDefinitions[declarativeCondition.ConditionName];

                    ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));

                    IDisposable localContextScope = (WorkflowCompilationContext.Current == null ? WorkflowCompilationContext.CreateScope(manager) : null);
                    try
                    {
                        RuleValidation ruleValidator = new RuleValidation(activity, typeProvider, WorkflowCompilationContext.Current.CheckTypes);
                        actualCondition.Validate(ruleValidator);

                        ValidationErrorCollection actualConditionErrors = ruleValidator.Errors;

                        if (actualConditionErrors.Count > 0)
                        {
                            string expressionPropertyName = GetFullPropertyName(manager);
                            string genericErrorMsg        = string.Format(CultureInfo.CurrentCulture, Messages.InvalidConditionExpression, expressionPropertyName);
                            int    errorNumber            = ErrorNumbers.Error_InvalidConditionExpression;

                            if (activity.Site != null)
                            {
                                ValidationError validationError = new ValidationError(genericErrorMsg, errorNumber);
                                validationError.PropertyName = expressionPropertyName + "." + "Expression";
                                validationErrors.Add(validationError);
                            }
                            else
                            {
                                foreach (ValidationError actualError in actualConditionErrors)
                                {
                                    ValidationError validationError = new ValidationError(genericErrorMsg + " " + actualError.ErrorText, errorNumber);
                                    validationError.PropertyName = expressionPropertyName + "." + "Expression";
                                    validationErrors.Add(validationError);
                                }
                            }
                        }

                        // Test duplicates
                        foreach (RuleCondition definition in conditionDefinitions)
                        {
                            if (definition.Name == declarativeCondition.ConditionName && definition != actualCondition)
                            {
                                string          message         = string.Format(CultureInfo.CurrentCulture, Messages.DuplicateConditions, declarativeCondition.ConditionName);
                                ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_DuplicateConditions);
                                validationError.PropertyName = GetFullPropertyName(manager) + "." + "ConditionName";
                                validationErrors.Add(validationError);
                            }
                        }
                    }
                    finally
                    {
                        if (localContextScope != null)
                        {
                            localContextScope.Dispose();
                        }
                    }
                }
            }
            else
            {
                string          message         = string.Format(CultureInfo.CurrentCulture, Messages.InvalidConditionName, "ConditionName");
                ValidationError validationError = new ValidationError(message, ErrorNumbers.Error_InvalidConditionName);
                validationError.PropertyName = GetFullPropertyName(manager) + "." + "ConditionName";
                validationErrors.Add(validationError);
            }
            return(validationErrors);
        }
Beispiel #48
0
 public static Failure ValidationError(ValidationError validationError)
 {
     return(new ValidationFailure(validationError));
 }
Beispiel #49
0
        public void ProcessRawSegment(string name, string[] content, int rowPos, string compositeSeparator)
        {
            List <AllowedEntitity> allowedEntities = GetNextAllowedEntities(_currentLoopDef);

            if (allowedEntities.All(e => e.Entity.EdiName != name))
            {
                string          expected = string.Join(", ", allowedEntities.Select(e => e.Entity.Name).ToList());
                string          msgPart  = allowedEntities.Count > 1 ? "Expected one of" : "Expected";
                ValidationError err      = new ValidationError()
                {
                    SegmentPos  = rowPos,
                    SegmentName = name,
                    Message     = $"Unexpected Segment. {msgPart} {expected}. Found {name}."
                };
                _trans.ValidationErrors.Add(err);
                return;
            }

            AllowedEntitity ae = allowedEntities.FirstOrDefault(e => e.Entity.EdiName == name);

            if (ae?.Entity is MapSegment)
            {
                ae.Entity.OccuredTimes++;

                _currentLoopDef            = ae.LoopContext;
                _currentLoopDef.CurrentPos = _currentLoopDef.Content.IndexOf(ae.Entity);

                while (((MapLoop)_currentLoopInstance.Definition) != ae.LoopContext && _currentLoopInstance.Parent != null)
                {
                    _currentLoopInstance = _currentLoopInstance.Parent;
                }
                _currentLoopInstance.Content.Add(ProcessSegment(ae.Entity, content, rowPos, compositeSeparator, _trans));
            }
            else if (ae?.Entity is MapLoop)
            {
                //find loop definition in map and reset counters
                ae.LoopContext.CurrentPos  = ae.LoopContext.Content.IndexOf(ae.Entity);
                _currentLoopDef            = (MapLoop)ae.Entity;
                _currentLoopDef.CurrentPos = 0;
                _currentLoopDef.OccuredTimes++;
                _currentLoopDef.Content.ForEach(c => c.OccuredTimes = 0);


                EdiLoop newLoop;
                if (name == "HL")
                {
                    int hl01;
                    int hl02;
                    int.TryParse(content[1], out hl01);
                    bool res02 = int.TryParse(content[2], out hl02);

                    if (hl01 > 1 && res02)
                    {
                        FindParentHlLoopContext(hl02);
                    }
                    else
                    {
                        FindParentLoopContext(ae.LoopContext);
                    }


                    newLoop = new EdiHlLoop(ae.Entity, _currentLoopInstance, hl01, (res02 ? hl02 : (int?)null));
                }
                else
                {
                    FindParentLoopContext(ae.LoopContext);
                    newLoop = new EdiLoop(ae.Entity, _currentLoopInstance);
                }

                _currentLoopInstance.Content.Add(newLoop);
                _currentLoopInstance = newLoop;

                ProcessRawSegment(name, content, rowPos, compositeSeparator);
            }
        }
        protected override void Simpan()
        {
            if (this._customer == null || txtCustomer.Text.Length == 0)
            {
                MsgHelper.MsgWarning("'Customer' tidak boleh kosong !");
                txtCustomer.Focus();

                return;
            }

            var total = SumGrid(this._listOfItemPembayaranPiutang);

            if (!(total > 0))
            {
                MsgHelper.MsgWarning("Anda belum melengkapi inputan data pembayaran !");
                return;
            }

            if (!MsgHelper.MsgKonfirmasi("Apakah proses ingin dilanjutkan ?"))
            {
                return;
            }

            if (_isNewData)
            {
                _pembayaranPiutang = new PembayaranPiutangProduk();
            }

            _pembayaranPiutang.pengguna_id = this._pengguna.pengguna_id;
            _pembayaranPiutang.Pengguna    = this._pengguna;
            _pembayaranPiutang.customer_id = this._customer.customer_id;
            _pembayaranPiutang.Customer    = this._customer;
            _pembayaranPiutang.nota        = txtNota.Text;
            _pembayaranPiutang.tanggal     = dtpTanggal.Value;
            _pembayaranPiutang.keterangan  = txtKeterangan.Text;

            _pembayaranPiutang.item_pembayaran_piutang = this._listOfItemPembayaranPiutang.Where(f => f.JualProduk != null).ToList();

            if (!_isNewData) // update
            {
                _pembayaranPiutang.item_pembayaran_piutang_deleted = _listOfItemPembayaranPiutangDeleted.ToList();
            }

            var result          = 0;
            var validationError = new ValidationError();

            using (new StCursor(Cursors.WaitCursor, new TimeSpan(0, 0, 0, 0)))
            {
                if (_isNewData)
                {
                    result = _bll.Save(_pembayaranPiutang, false, ref validationError);
                }
                else
                {
                    result = _bll.Update(_pembayaranPiutang, false, ref validationError);
                }

                if (result > 0)
                {
                    Listener.Ok(this, _isNewData, _pembayaranPiutang);

                    _customer = null;
                    _listOfItemPembayaranPiutang.Clear();
                    _listOfItemPembayaranPiutangDeleted.Clear();

                    this.Close();
                }
                else
                {
                    if (validationError.Message.NullToString().Length > 0)
                    {
                        MsgHelper.MsgWarning(validationError.Message);
                        base.SetFocusObject(validationError.PropertyName, this);
                    }
                    else
                    {
                        MsgHelper.MsgUpdateError();
                    }
                }
            }
        }
 public void AddError(ValidationError error)
 {
     this.ValidationErrors.AddIfNotExists(error.Title, () => new List <ValidationError>());
     this.ValidationErrors[error.Title].Add(error);
 }
        public static bool TryGenerateLinqDelegate <TOperand, TResult>(ExpressionType operatorType, out Func <TOperand, TResult> operation, out ValidationError validationError)
        {
            operation       = null;
            validationError = null;

            ParameterExpression operandParameter = Expression.Parameter(typeof(TOperand), "operand");

            try
            {
                UnaryExpression unaryExpression     = Expression.MakeUnary(operatorType, operandParameter, typeof(TResult));
                Expression      expressionToCompile = OperatorPermissionHelper.InjectReflectionPermissionIfNecessary(unaryExpression.Method, unaryExpression);
                Expression <Func <TOperand, TResult> > lambdaExpression = Expression.Lambda <Func <TOperand, TResult> >(expressionToCompile, operandParameter);
                operation = lambdaExpression.Compile();
                return(true);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                validationError = new ValidationError(e.Message);
                return(false);
            }
        }
Beispiel #53
0
 public ErrorDescriptor(IViewModelDependencies dependencies, IZetboxContext dataCtx, WorkspaceViewModel parent, ValidationError error)
     : base(dependencies, dataCtx, parent)
 {
     this._error = error;
     this._workspace = parent;
 }
Beispiel #54
0
 public static ResponseStatus ToResponseStatus(this ValidationError validationException)
 {
     return(ResponseStatusUtils.CreateResponseStatus(validationException.ErrorCode, validationException.Message, validationException.Violations));
 }
 public BadRequestException(ValidationError error)
 {
     this.Error = error;
 }
Beispiel #56
0
        private void LoginBTN_Clicked(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            MaterialDesignThemes.Wpf.ButtonProgressAssist.SetIsIndeterminate(btn, true);
            MaterialDesignThemes.Wpf.ButtonProgressAssist.SetValue(btn, -1);
            MaterialDesignThemes.Wpf.ButtonProgressAssist.SetIsIndicatorVisible(btn, true);
            btn.IsEnabled       = false;
            SignupBTN.IsEnabled = false;
            bool EverythingFine = true;

            if (String.IsNullOrEmpty(UsernameBox.Text))
            {
                UsernameBox.GetBindingExpression(TextBox.TextProperty);
                ValidationError validationError = new ValidationError(new NotEmptyValidationRule(), UsernameBox.GetBindingExpression(TextBox.TextProperty));
                validationError.ErrorContent = "Field is required.";

                Validation.MarkInvalid(
                    UsernameBox.GetBindingExpression(TextBox.TextProperty),
                    validationError);
                EverythingFine = false;
            }
            else
            {
                Validation.ClearInvalid(UsernameBox.GetBindingExpression(TextBox.TextProperty));
            }
            if (String.IsNullOrEmpty(PasswordBox.Password))
            {
                PasswordBox.GetBindingExpression(TextBox.TextProperty);
                ValidationError validationError = new ValidationError(new NotEmptyValidationRule(), PasswordBox.GetBindingExpression(PasswordBox.DataContextProperty));
                validationError.ErrorContent = "Field is required.";

                Validation.MarkInvalid(
                    PasswordBox.GetBindingExpression(PasswordBox.DataContextProperty),
                    validationError);
                EverythingFine = false;
            }
            else if (PasswordBox.Password.Length < 1)
            {
                PasswordBox.GetBindingExpression(TextBox.TextProperty);
                ValidationError validationError = new ValidationError(new NotEmptyValidationRule(), PasswordBox.GetBindingExpression(PasswordBox.DataContextProperty));
                validationError.ErrorContent = "At least 8 characters.";

                Validation.MarkInvalid(
                    PasswordBox.GetBindingExpression(PasswordBox.DataContextProperty),
                    validationError);
                EverythingFine = false;
            }
            else
            {
                Validation.ClearInvalid(PasswordBox.GetBindingExpression(PasswordBox.DataContextProperty));
            }
            if (EverythingFine)
            {
                LoginRequest loginRequest = new LoginRequest();
                loginRequest.username = UsernameBox.Text;
                loginRequest.password = PasswordBox.Password;

                app.communicator.SocketSendReceive(JsonSerializer.serializeRequest(loginRequest, Constants.LOGIN_REQUEST_CODE)).ContinueWith(task =>
                {
                    ResponseInfo response       = task.Result;
                    LoginResponse loginResponse = JsonDeserializer.deserializeResponse <LoginResponse>(response.buffer);
                    switch (loginResponse.status)
                    {
                    case Constants.LOGIN_SUCCESS:
                        MyMessageQueue.Enqueue("Sign in Successfully!");
                        this.Dispatcher.Invoke(() =>
                        {
                            app.username         = UsernameBox.Text;
                            NavigationService ns = NavigationService.GetNavigationService(this);
                            ns.Navigate(new Uri("Menu.xaml", UriKind.Relative));
                        });
                        break;

                    case Constants.LOGIN_INCORRECT_PASSWORD:
                        MyMessageQueue.Enqueue("Incorrect password.");
                        break;

                    case Constants.LOGIN_USERNAME_NOT_EXIST:
                        MyMessageQueue.Enqueue("Username not exist.");
                        break;

                    case Constants.LOGIN_UNEXPECTED_ERR:
                        MyMessageQueue.Enqueue("There was an unexpected error.");
                        break;

                    case Constants.LOGIN_ALREADY_ONLINE:
                        MyMessageQueue.Enqueue("This Username is already online.");
                        break;
                    }
                    this.Dispatcher.Invoke(() =>
                    {
                        ButtonProgressAssist.SetIsIndeterminate(btn, false);
                        ButtonProgressAssist.SetIsIndicatorVisible(btn, false);
                        btn.IsEnabled       = true;
                        SignupBTN.IsEnabled = true;
                    });
                });
            }
            else
            {
                MaterialDesignThemes.Wpf.ButtonProgressAssist.SetIsIndeterminate(btn, false);
                MaterialDesignThemes.Wpf.ButtonProgressAssist.SetIsIndicatorVisible(btn, false);
                btn.IsEnabled       = true;
                SignupBTN.IsEnabled = true;
            }
        }
 private ModelValidationResult Convert(ValidationError validationError, Type modelType)
 {
     return new ModelValidationResult {MemberName = validationError.TargetMemberMetadata.GetRootRelativePath(modelType), Message = validationError.Message};
 }
Beispiel #58
0
 private static string GetPropertyName(ValidationError error)
 {
     return(error.Path.Split('.').LastOrDefault());
 }
Beispiel #59
0
 public LeafElement(string id, string value, ValidationError error)
 {
     _id = id;
     _error = error;
     _value = value;
 }
Beispiel #60
0
 public ValidationInfo(ValidationError error)
 {
     ErrorContent = error.ErrorContent;
     Exception    = error.Exception;
     IsException  = error.Exception != null;
 }