public void RegisterMessageChaining()
		{
			ErrorSummary summ1 = new ErrorSummary().RegisterErrorMessage("test1", "test1");
			ErrorSummary summ2 = summ1.RegisterErrorMessage("test2", "test2").RegisterErrorMessage("test3", "test3");

			Assert.AreSame(summ1, summ2);
		}
Example #2
0
 protected void NotifyError(ErrorSummary es)
 {
     if(ErrorEvent != null) { ErrorEvent(es); }
 }
 /// <summary>
 /// Displays an error message and logs the specified exception to the event log.
 /// </summary>
 /// <param name="exception">The exception to handle.</param>
 private void HandleException(Exception exception)
 {
     ErrorSummary.Report(exception);
     StopProcessing = true;
     EventLogProvider.LogException("Data.com Connector", "ContactPage", exception);
 }
 public void AnotherInvalid(out ErrorSummary errors)
 {
     errors = new ErrorSummary();
 }
 public void ValidateOnUpdate(ErrorSummary errorSummary)
 {
     ValidateOnUpdateRan = true;
 }
			public void Validate(ErrorSummary errors)
			{
				errors.RegisterErrorMessage("errorKey", "errorMessage");
			}
Example #7
0
 /// <summary>
 /// Displays an error message and logs the specified exception to the event log.
 /// </summary>
 /// <param name="exception">The exception to handle.</param>
 private void HandleException(Exception exception)
 {
     ErrorSummary.Report(exception);
     ConfirmButton.Enabled = false;
     EventLogProvider.LogException("Data.com Connector", "SelectCompanyPage", exception);
 }
Example #8
0
 public void Refresh()
 {
     errorSummary = null;
 }
Example #9
0
        protected void lbSaveContinue_Click(object sender, EventArgs e)
        {
            string urlKey = txtUrlKey.Text.Trim();

            // If urlKey is empty, regenerate with given name
            if (urlKey == string.Empty)
            {
                urlKey         = AdminStoreUtility.GetFriendlyUrlKey(txtName.Text.Trim());
                txtUrlKey.Text = urlKey;
            }

            // Make sure urlKey is unique
            var    foundProduct = ProductService.GetProductByUrlKey(urlKey);
            int    productId    = QueryProductId;
            string message      = string.Empty;

            if (((foundProduct != null) && (foundProduct.Id != productId)))
            {
                ErrorSummary.AddError("Url Key is not unique.", "vgNewProduct", this.Page);
            }
            else
            {
                Product product = new Product();
                product.Name                          = Server.HtmlEncode(txtName.Text.Trim());
                product.Description                   = string.Empty;
                product.BrandId                       = Convert.ToInt32(ddlBrand.SelectedValue);
                product.DeliveryId                    = Convert.ToInt32(ddlDelivery.SelectedValue);
                product.UrlRewrite                    = urlKey;
                product.Enabled                       = ddlStatus.Items.FindByValue(product.Enabled ? ENABLED : DISABLED).Selected = true;
                product.IsPharmaceutical              = cbIsPharm.Checked;
                product.OpenForOffer                  = cbOpenForOffer.Checked;
                product.Discontinued                  = cbDiscontinued.Checked;
                product.ShowPreOrderButton            = cbDisplayPreOrder.Checked;
                product.EnforceStockCount             = cbEnforceStockCount.Checked;
                product.IsGoogleProductSearchDisabled = cbGoogleProductSearchDisabled.Checked;
                product.ProductCode                   = txtProductCode.Text.Trim();
                product.HasFreeWrapping               = cbFreeWrap.Checked;
                product.OptionType                    = Convert.ToInt32(ddlOptionType.SelectedValue);
                product.ProductMark                   = txtProductMark.Text.Trim();
                product.ProductMarkType               = Convert.ToInt32(ddlProductMarks.SelectedValue);

                if (!string.IsNullOrEmpty(txtProductMarkExpiryDate.Text.Trim()))
                {
                    product.ProductMarkExpiryDate = DateTime.ParseExact(txtProductMarkExpiryDate.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture);
                }

                product.IsPhoneOrder        = cbIsPhoneOrder.Checked;
                product.VisibleIndividually = cbVisibleIndividually.Checked;

                int taxCategoryId = Convert.ToInt32(ddlTaxCategory.SelectedValue);
                var taxCategory   = ProductService.GetTaxCategory(taxCategoryId);
                product.TaxCategory = taxCategory;

                if (txtStepQuantity.Text.Trim() != string.Empty)
                {
                    int defaultQty = 1;
                    if (!int.TryParse(txtStepQuantity.Text.Trim(), out defaultQty))
                    {
                        defaultQty = 1;
                    }

                    if (defaultQty <= 0)
                    {
                        defaultQty = 1;
                    }

                    product.StepQuantity = Convert.ToInt32(txtStepQuantity.Text.Trim());

                    if (cbIsPharm.Checked)
                    {
                        product.StepQuantity = 1;
                    }
                }

                product.Id = ProductService.InsertProduct(product);

                var categoryId = Convert.ToInt32(hfCategory.Value);
                if (categoryId != AppConstant.DEFAULT_CATEGORY)
                {
                    CategoryService.ProcessCategoryAssignmentForProduct(categoryId, product.Id);
                }

                Response.Redirect("/catalog/product_info.aspx?" + QueryKey.MSG_TYPE + "=" + (int)MessageType.ProductCreated + "&productid=" + product.Id);
            }
        }
Example #10
0
        }                                               // the method declaration itself

        public MethodSymbolTable(ClassSymbolTable parentClass, DeclaringNode methodDeclaring, ErrorSummary errorSummary)
        {
            _parentClass         = parentClass;
            MethodDeclaring      = methodDeclaring;
            _methodVarDeclarings = new Dictionary <string, DeclaringNode>();
            _errorSummary        = errorSummary;
        }
Example #11
0
        /// <summary>
        /// Called when the validator finds an invalid method.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="errors">The errors.</param>
        protected virtual void OnInvalidMethod(MethodInfo method, ErrorSummary errors)
        {
            string errorMessage = BuildErrorMessage(method, errors);

            throw new ValidationException(errorMessage, errors.ErrorMessages);
        }
Example #12
0
 public Parser(CharStream charStream, ErrorSummary errorSummary, string fileName)
 {
     _tokenStream  = new TokenStream(charStream, errorSummary, fileName);
     _errorSummary = errorSummary;
     _currentToken = _tokenStream.Read();
 }
 public void Save(ErrorSummary entity)
 {
     this.errorMapper.Save(entity);
 }
Example #14
0
 private void _underlyingTransport_ErrorEvent(ErrorSummary es)
 {
     recorder.Record(new MillipedeEvent(milliDescriptor, MillipedeEventType.Error, es));
     if (ErrorEvent != null)
     {
         ErrorEvent(es);
     }
 }
Example #15
0
        /// <summary>
        /// Validates the parameter.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <param name="parameterPosition">The parameter position.</param>
        /// <param name="runWhen">The run when.</param>
        /// <param name="errors">The errors.</param>
        protected virtual void ValidateParameter(IInvocation invocation, int parameterPosition, RunWhen runWhen, ErrorSummary errors)
        {
            MethodInfo method = invocation.Method;


            ParameterInfoMeta parameterInfoMeta;

            IValidator[] validators = methodValidatorMetaStore.GetValidatorsFor(method, parameterPosition, null, runWhen, out parameterInfoMeta);

            foreach (IValidator validator in validators)
            {
                IPropertyAccessAware propertyAccessAware = (IPropertyAccessAware)validator;
                object value = invocation.Arguments[parameterPosition];

                if (parameterInfoMeta == ParameterInfoMeta.ParamsArray)
                {
                    ValidateParamsArray(validator, propertyAccessAware, value, errors);
                    continue;
                }

                propertyAccessAware.PropertyAccessor = delegate { return(invocation.Arguments[parameterPosition]); };

                if (validator.IsValid(value))
                {
                    continue;
                }

                AppendError(validator, errors);
            }
        }
Example #16
0
 public static void AddError(string message, Page page)
 {
     ErrorSummary error = new ErrorSummary(message);
     page.Validators.Add(error);
 }
Example #17
0
 protected void NotifyError(ErrorSummary summary)
 {
     if (ErrorEvent != null)
     {
         ErrorEvent(summary);
     }
     else
     {
         summary.LogTo(log);
     }
 }
Example #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MethodValidationException"/> class.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="errors">The errors.</param>
 public MethodValidationException(string message, ErrorSummary errors) : base(message, errors.ErrorMessages)
 {
     this.errors = errors;
 }
Example #19
0
 public void Validate(ErrorSummary errors)
 {
     errors.RegisterErrorMessage("errorKey", "errorMessage");
 }
Example #20
0
        protected void NotifyError(ErrorSummary es)
        {
            if (ErrorEvent == null)
            {
                es.LogTo(log);
                return;
            }

            try { ErrorEvent(es); }
            catch (Exception e)
            {
                log.Warn("Exception occurred when processing application ErrorEvent handlers", e);
                ErrorEvent(new ErrorSummary(Severity.Information, SummaryErrorCode.UserException,
                    "Exception occurred when processing application ErrorEvent handlers", e));
            }
        }
Example #21
0
 /// <summary>
 /// Displays a default error message and logs the specified exception to the event log.
 /// </summary>
 /// <param name="exception">The exception to handle.</param>
 private void HandleException(Exception exception)
 {
     ErrorSummary.Report(exception);
     EventLogProvider.LogException("Data.com Connector", "EditMappingPage", exception);
 }
Example #22
0
		private void CheckForValidationFailures(object instance, string prefix, Node node, ErrorSummary summary)
		{
			if (validator == null)
			{
				return;
			}
			if (!validator.IsValid(instance))
			{
				ErrorSummary errorSummaryFromValidator = validator.GetErrorSummary(instance);
				foreach (string invalidProperty in errorSummaryFromValidator.InvalidProperties)
				{
					if (ShouldIgnoreProperty(string.Format("{0}.{1}", node.FullName, invalidProperty)))
						continue;

					foreach (string errorMessage in errorSummaryFromValidator.GetErrorsForProperty(invalidProperty))
					{
						summary.RegisterErrorMessage(invalidProperty, errorMessage);
						errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
					}
				}
			}
		}
Example #23
0
 /// <summary>
 /// Validate method parameters that are decorated with the params keyword.
 /// </summary>
 /// <param name="validator">The validator.</param>
 /// <param name="propertyAccessAware">The property access aware.</param>
 /// <param name="value">The value.</param>
 /// <param name="errors">The errors.</param>
 private void ValidateParamsArray(IValidator validator, IPropertyAccessAware propertyAccessAware, object value, ErrorSummary errors)
 {
     object[] paramsValue = (object[])value;
     foreach (object paramValue in paramsValue)
     {
         propertyAccessAware.PropertyAccessor = delegate { return(paramValue); };
         if (validator.IsValid(paramValue))
         {
             continue;
         }
         AppendError(validator, errors);
     }
 }
Example #24
0
        protected void InternalRecursiveBindObjectInstance(object instance, String prefix, CompositeNode node)
        {
            if (node == null || instance == null)
            {
                return;
            }

            BeforeBinding(instance, prefix, node);

            if (PerformCustomBinding(instance, prefix, node))
            {
                return;
            }

            PushInstance(instance, prefix);

            var summary = new ErrorSummary();

            validationErrorSummaryPerInstance[instance] = summary;

            Type instanceType = instance.GetType();

            PropertyInfo[] props = instanceType.GetProperties(PropertiesBindingFlags);

            string nodeFullName = node.FullName;

            foreach (PropertyInfo prop in props)
            {
                if (ShouldIgnoreProperty(string.Format("{0}.{1}", nodeFullName, prop.Name)))
                {
                    continue;
                }

                Type   propType  = prop.PropertyType;
                String paramName = prop.Name;

                String translatedParamName = Translate(instanceType, paramName);

                if (translatedParamName == null)
                {
                    continue;
                }

                bool isSimpleProperty = IsSimpleProperty(propType);

                if (isSimpleProperty && prop.CanWrite == false)
                {
                    continue;
                }

                BeforeBindingProperty(instance, prop, prefix, node);

                try
                {
                    bool conversionSucceeded;

                    if (isSimpleProperty)
                    {
                        object value = ConvertToSimpleValue(propType, translatedParamName, node, out conversionSucceeded);

                        if (conversionSucceeded)
                        {
                            SetPropertyValue(instance, prop, value);
                        }
                    }
                    else
                    {
                        // if the property is an object, we look if it is already instantiated
                        Node nestedNode = node.GetChildNode(paramName);

                        if (nestedNode != null)
                        {
                            object value = prop.GetValue(instance, null);

                            if (ShouldRecreateInstance(value, propType, paramName, nestedNode))
                            {
                                value = InternalBindObject(propType, paramName, nestedNode, out conversionSucceeded);

                                if (conversionSucceeded)
                                {
                                    SetPropertyValue(instance, prop, value);
                                }
                            }
                            else
                            {
                                InternalRecursiveBindObjectInstance(value, paramName, nestedNode);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errors.Add(new DataBindError(prefix, prop.Name, ex));
                }
            }

            CheckForValidationFailures(instance, prefix, node, summary);

            PopInstance(instance, prefix);

            AfterBinding(instance, prefix, node);
        }
 public void Valid(ErrorSummary errorSummary)
 {
 }
Example #26
0
        private void CheckForValidationFailures(object instance, string prefix, Node node, ErrorSummary summary)
        {
            if (validator == null)
            {
                return;
            }
            if (!validator.IsValid(instance))
            {
                ErrorSummary errorSummaryFromValidator = validator.GetErrorSummary(instance);
                foreach (string invalidProperty in errorSummaryFromValidator.InvalidProperties)
                {
                    if (ShouldIgnoreProperty(string.Format("{0}.{1}", node.FullName, invalidProperty)))
                    {
                        continue;
                    }

                    foreach (string errorMessage in errorSummaryFromValidator.GetErrorsForProperty(invalidProperty))
                    {
                        summary.RegisterErrorMessage(invalidProperty, errorMessage);
                        errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
                    }
                }
            }
        }
Example #27
0
        public ViewResult Register(UserRegistration userRegistration)
        {
            var errors = userRegistration.Validate();

            if (errors == null)
            {
                IList <UserFlavor> userFlavors = Session["UserFlavorSelected"] as List <UserFlavor>;
                IList <EventType>  eventTypes  = Session["EventTypeSelected"] as List <EventType>;
                IList <Garment>    mygarments  = Session["MyGarments"] as List <Garment>;
                IList <Garment>    mywishlist  = Session["MyWishList"] as List <Garment>;

                PublicUser user = new PublicUser();
                user.EmailAddress = userRegistration.Email;
                user.ChangeZipCode(userRegistration.ZipCode);
                user.SetFlavors(userFlavors);
                user.Size = new UserSize(Convert.ToInt32(userRegistration.UserSize));

                //TODO: Get the UserId from ASP.NET Membership
                MembershipCreateStatus status;
                MembershipUser         mu = Membership.CreateUser(userRegistration.UserName, userRegistration.Password, userRegistration.Email, securityQuestionRepository.Get(Convert.ToInt32(userRegistration.SecurityQuestion)).Description, userRegistration.SecurityAnswer, true, out status);
                if (status != MembershipCreateStatus.Success)
                {
                    errors = new ErrorSummary();
                    errors.RegisterErrorMessage("MembershipUser", status.ToString());
                    return(RegistrationError(userRegistration, errors.ErrorMessages));
                }
                user.MembershipUserId = Convert.ToInt32(mu.ProviderUserKey);
                user.FirstName        = string.Empty;
                user.LastName         = string.Empty;
                user.PhoneNumber      = string.Empty;

                if (eventTypes != null)
                {
                    foreach (EventType eventType in eventTypes)
                    {
                        user.AddEventType(eventType);
                    }
                }

                registeredUserRepository.SaveOrUpdate(user);
                Closet closet = new Closet();
                closet.User         = user;
                closet.PrivacyLevel = PrivacyLevel.Private;

                closetRepository.SaveOrUpdate(closet);
                if (mygarments != null)
                {
                    foreach (Garment garment in mygarments)
                    {
                        closet.AddGarment(garment);
                    }
                    closetRepository.SaveOrUpdate(closet);
                }
                user.Closet = closet;

                registeredUserRepository.SaveOrUpdate(user);

                if (mywishlist != null && mywishlist.Count > 0)
                {
                    WishList wl = new WishList();
                    wl.User = user;
                    foreach (Garment wishlist in mywishlist)
                    {
                        wl.AddGarment(wishlist);
                    }
                    wishListRepository.SaveOrUpdate(wl);
                }
                closetRepository.GenerateCloset(user);

                Session.Abandon();
                Session["UserRegistration"] = mu;
                return(View("RegistrationFinish", userRegistration));
            }

            return(RegistrationError(userRegistration, errors.ErrorMessages));
        }
			public void Validate(ErrorSummary errorSummary)
			{
				if (total > 1000 && ItemSKUs.Length == 1)
					//TODO Make it easy to register an error message with a key
					errorSummary.RegisterErrorMessage("total", "Customers cannot purchase 1 item if it is more than $1000 dollars.");
			}
		/// <summary>
		/// Determines whether the specified instance is valid.  Returns an
		/// <see cref="ErrorSummary"/> that will be appended to the existing
		/// error summary for an object.
		/// </summary>
		/// <param name="instance">The instance.</param>
		/// <param name="when">The when.</param>
		/// <returns></returns>
		protected override ErrorSummary IsValidInternal(object instance, RunWhen when)
		{
			ErrorSummary summary = new ErrorSummary();

			// perform validation on each validator container interfaces
			foreach (Type validatorContainerType in GetValidatorContainerInterfacesForType(instance.GetType()))
			{
				// don't run any other contributors
				IValidationContributor[] contributors = null;

				validationPerformer.PerformValidation(
					instance,
					RequestValidatorsToRegistry(validatorContainerType, when),
					contributors,
					when,
					summary
					);
			}
			return summary;
		}
			public void ValidateOnUpdate(ErrorSummary errorSummary)
			{
				ValidateOnUpdateRan = true;
			}
        private (ErrorSummary errorSummary, int?httpStatusCode) prepareErrorDetails(Exception exception)
        {
            var res = new ErrorSummary()
            {
                CorrelationId = Guid.NewGuid().ToString()
            };

            switch (exception)
            {
            case DetailedException detailedException:
            {
                var currentErrorCatalog = errorsInformation.GetErrorCatalogByCode(detailedException.LocationCodePairs.Value);
                res.Errors = new List <ErrorDetails>
                {
                    new ErrorDetails()
                    {
                        Location = detailedException.LocationCodePairs.Key,
                        Code     = detailedException.LocationCodePairs.Value,
                        Problem  = (string.IsNullOrEmpty(detailedException.JsonData) ? currentErrorCatalog.Problem : JsonConvert.DeserializeObject <object>(detailedException.JsonData)),
                        Action   = currentErrorCatalog.Action
                    }
                };

                return(res, currentErrorCatalog.HttpResponseCode);
            }

            case XmlException ex1:
            case UnsupportedContentTypeException ex:
            {
                ErrorCatalog currentErrorCatalog;
                string       errorLocation;

                currentErrorCatalog = errorsInformation.GetErrorCatalogByCode(ErrorCodes.UnsupportedMediaTypeHeader);
                errorLocation       = exception.Message;

                var errorDetails = new ErrorDetails()
                {
                    Location = errorLocation,
                    Code     = currentErrorCatalog.Code,
                    Problem  = currentErrorCatalog.Problem,
                    Action   = currentErrorCatalog.Action
                };
                res.Errors.Add(errorDetails);
                return(res, currentErrorCatalog.HttpResponseCode);
            }

            default:
            {
                var currentErrorCatalog = errorsInformation.GetErrorCatalogByCode(ErrorCodes.UnrecoverableTechnicalIssue);
                var errorDetails        = new ErrorDetails()
                {
                    Location = "Service",
                    Code     = currentErrorCatalog.Code,
                    Problem  = currentErrorCatalog.Problem,
                    Action   = currentErrorCatalog.Action
                };
                res.Errors.Add(errorDetails);
                return(res, currentErrorCatalog.HttpResponseCode);
            }
            }
        }
			public void Valid(ErrorSummary errorSummary)
			{
			}
Example #33
0
 protected virtual void NotifyError(ErrorSummary es)
 {
     es.LogTo(log);
     if(ErrorEvent != null)
     {
         ErrorEvent(es);
     }
 }
			public void AnotherInvalid(out ErrorSummary errors)
			{
				errors = new ErrorSummary();
			}
Example #35
0
        public bool IsInstallationValid(out ErrorSummary errors)
        {
            if (errorSummary != null)
            {
                errors = errorSummary;
                return(errors.IsEmpty());
            }

            errors       = new ErrorSummary();
            errorSummary = errors;

            PluginData data = PluginsManifest.Instance.GetPluginData(this);

            if (data.installed == false)
            {
                return(false);
            }

            foreach (var symbol in GetSymbols())
            {
                if (DefineSymbols.Instance.IsEnabled(symbol.symbolName) == false)
                {
                    errors.RegisterInvalidItem($"{symbol.symbolName}", PluginDependencyType.DefineSymbol);
                }
            }

            foreach (ModuleInstallInfo moduleInfo in GetModules())
            {
                if (ModuleInstaller.IsModuleInstallationValid(moduleInfo) == false)
                {
                    errors.RegisterInvalidItem($"{AssetDatabase.GetAssetPath(moduleInfo)}", PluginDependencyType.Module);
                }
            }

            foreach (PackageDependency packageDependency in GetPackages())
            {
                if (Util.HasPackageDependency(packageDependency.packageName, packageDependency.version) == false)
                {
                    errors.RegisterInvalidItem($"{packageDependency.FullName}", PluginDependencyType.Package);
                }
            }

            foreach (PluginInfo dependency in GetDependencies())
            {
                if (dependency == this)
                {
                    Debug.LogWarning($"Circular dependency: {description} depends on itself!");
                    continue;
                }
                if (dependency == null)
                {
                    Debug.LogWarning($"Empty dependency detected on {description}!");
                    continue;
                }
                if (dependency.IsInstallationValid(out var depErrors) == false)
                {
                    errors.RegisterInvalidItem($"{AssetDatabase.GetAssetPath(dependency)}", PluginDependencyType.Plugin);
                }
            }

            return(errors.IsEmpty());
        }
Example #36
0
 public TokenStream(CharStream charStream, ErrorSummary errorSummary, string fileName)
 {
     _scanner = new Scanner(charStream, errorSummary, fileName);
     Read();
 }
Example #37
0
            }                                               // the declaration for the class or interface itself

            public ClassSymbolTable(DeclaringNode n, Dictionary <string, DeclaringNode> stdlib, ErrorSummary errorSummary)
            {
                _classVarDeclarings      = new Dictionary <string, DeclaringNode>();
                _classMethodSymbolTables = new Dictionary <string, MethodSymbolTable>();
                ClassDeclaring           = n;
                _stdlib       = stdlib;
                _errorSummary = errorSummary;
            }
Example #38
0
 public ErrorPageBuilder(ErrorSummary error)
 {
     Summary = error;
 }
Example #39
0
 private void s_ErrorEvent(ErrorSummary es)
 {
     string message = es.ToString();
     switch(es.Severity)
     {
     case Severity.Error:
         log.Error(message, es.Context);
         break;
     case Severity.Warning:
         log.Warn(message, es.Context);
         break;
     case Severity.Fatal:
         log.Fatal(message, es.Context);
         break;
     case Severity.Information:
         log.Info(message, es.Context);
         break;
     }
     if (ErrorEvent != null) { ErrorEvent(es); }
 }
		protected void InternalRecursiveBindObjectInstance(object instance, String prefix, CompositeNode node)
		{
			if (node == null || instance == null)
			{
				return;
			}

			BeforeBinding(instance, prefix, node);

			if (PerformCustomBinding(instance, prefix, node))
			{
				return;
			}

			PushInstance(instance, prefix);

			var summary = new ErrorSummary();

			validationErrorSummaryPerInstance[instance] = summary;

			Type instanceType = instance.GetType();

			PropertyInfo[] props = instanceType.GetProperties(PropertiesBindingFlags);
			var nodeFullName = node.FullNameWithoutIndexer();

			foreach (PropertyInfo prop in props)
			{
				if (ShouldIgnoreProperty(prop, nodeFullName))
				{
					continue;
				}

				Type propType = prop.PropertyType;
				String paramName = prop.Name;

				String translatedParamName = Translate(instanceType, paramName);

				if (translatedParamName == null)
				{
					continue;
				}

				bool isSimpleProperty = IsSimpleProperty(propType);

				BeforeBindingProperty(instance, prop, prefix, node);

				try
				{
					bool conversionSucceeded;

					if (isSimpleProperty)
					{
						object value = ConvertToSimpleValue(propType, translatedParamName, node, out conversionSucceeded);

						if (conversionSucceeded)
						{
							SetPropertyValue(instance, prop, value);
						}
					}
					else
					{
						// if the property is an object, we look if it is already instantiated
						Node nestedNode = node.GetChildNode(paramName);

						if (nestedNode != null)
						{
							object value = prop.GetValue(instance, null);

							if (ShouldRecreateInstance(value, propType, paramName, nestedNode))
							{
								value = InternalBindObject(propType, paramName, nestedNode, out conversionSucceeded);

								if (conversionSucceeded)
								{
									SetPropertyValue(instance, prop, value);
								}
							}
							else
							{
								InternalRecursiveBindObjectInstance(value, paramName, nestedNode);
							}
						}
					}
				}
				catch (Exception ex)
				{
					errors.Add(new DataBindError(prefix, prop.Name, ex));
				}
			}

			CheckForValidationFailures(instance, prefix, summary);

			PopInstance(instance, prefix);

			AfterBinding(instance, prefix, node);
		}
		private void CheckForValidationFailures(object instance, string prefix, ErrorSummary summary)
		{
			if (validator == null)
			{
				return;
			}
			if (!validator.IsValid(instance))
			{
				summary.RegisterErrorsFrom(validator.GetErrorSummary(instance));
				foreach (string invalidProperty in summary.InvalidProperties)
				{
					foreach (string errorMessage in summary.GetErrorsForProperty(invalidProperty))
					{
						errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
					}
				}
			}
		}
		protected bool CheckForValidationFailures(object instance, Type instanceType,
		                                          PropertyInfo prop, CompositeNode node,
		                                          string name, string prefix,
		                                          ErrorSummary summary)
		{
			object value = null;

			if (validator == null)
			{
				return false;
			}

			IValidator[] validators = validator.GetValidators(instanceType, prop);

			if (validators.Length != 0)
			{
				Node valNode = node.GetChildNode(name);

				if (valNode != null && valNode.NodeType == NodeType.Leaf)
				{
					value = ((LeafNode) valNode).Value;
				}

				if (value == null && IsDateTimeType(prop.PropertyType))
				{
					bool conversionSucceeded;
					value = TryGetDateWithUTCFormat(node, name, out conversionSucceeded);
				}

				if (value == null && valNode == null)
				{
					// Value was not present on the data source. Skip validation
					return false;
				}
			}

			return CheckForValidationFailures(instance, instanceType, prop, value, name, prefix, summary);
		}
Example #43
0
 /// <summary>
 /// Displays an error message and logs the specified exception to the event log.
 /// </summary>
 /// <param name="exception">The exception to handle.</param>
 private void HandleException(Exception exception)
 {
     ErrorSummary.Report(exception);
     EventLogProvider.LogException("Data.com Connector", "ContactControl", exception);
 }
		protected bool CheckForValidationFailures(object instance, Type instanceType,
		                                          PropertyInfo prop, object value,
		                                          string name, string prefix,
		                                          ErrorSummary summary)
		{
			bool hasFailure = false;

			if (validator == null)
			{
				return false;
			}

			IValidator[] validators = validator.GetValidators(instanceType, prop);

			foreach (IValidator validatorItem in validators)
			{
				if (!validatorItem.IsValid(instance, value))
				{
					string propName = validatorItem.FriendlyName ?? validatorItem.Name;

					errors.Add(new DataBindError(prefix, prop.Name, validatorItem.ErrorMessage));

					summary.RegisterErrorMessage(propName, validatorItem.ErrorMessage);

					hasFailure = true;
				}
			}

			return hasFailure;
		}
			public ErrorSummary IsValid(object instance, RunWhen runWhen)
			{
				ErrorSummary errors =  new ErrorSummary();
				errors.RegisterErrorMessage("someKey", "error");
				return errors;
			}
Example #46
0
 private void server_ErrorEvent(ErrorSummary summary)
 {
     Console.WriteLine("Server: {0}", summary);
     errorOccurred = summary.Severity >= Severity.Warning;
 }