Esempio n. 1
0
        public static int Insertar(Proveedor objProxy)
        {
            ValidationException x = new ValidationException();
            //if (string.IsNullOrEmpty(objProxy.SProvider_name))
            //    x.AgregarError("Ingrese el nombre del empleado");

            //if (string.IsNullOrEmpty(objProxy.SProvider_rs))
            //    x.AgregarError("Ingrese el nombre del rs?");

            //if (string.IsNullOrEmpty(objProxy.SProvider_phone))
            //    x.AgregarError("Ingrese el nombre del telefono");

            //if (string.IsNullOrEmpty(objProxy.SProvider_email))
            //    x.AgregarError("Ingrese el nombre del correo");

            //if (string.IsNullOrEmpty(objProxy.SProvider_desc))
            //    x.AgregarError("Ingrese el nombre del descripcion");

            //if (string.IsNullOrEmpty(objProxy.SProvider_address))
            //    x.AgregarError("Ingrese el nombre del direccion");

            //if (x.Cantidad > 0)
            //    throw x;

              DAOProveedor daoProxy = new DAOProveedor();
            return daoProxy.Insertar(objProxy.SProvider_name,objProxy.SProvider_rs,objProxy.SProvider_phone, objProxy.SProvider_email,objProxy.SProvider_desc,objProxy.SProvider_address);
        }
 public void VerifyValidationExceptionMessage()
 {
     var ve = new ValidationException(
         new ValidationError("ERROR1"),
         new ValidationError("ERROR2"));
     Assert.That(ve.Message, Is.EqualTo("ERROR1\nERROR2"));
 }
Esempio n. 3
0
        public static bool InsertarFactura(Factura objProxy)
        {
            ValidationException x = new ValidationException();
            if (objProxy.Fecha < DateTime.Now.AddDays(-1))
                x.AgregarError("La fecha debe ser mayor a la fecha actual");

            if (objProxy.Detalle.Count < 1)
                x.AgregarError("No ingresó el detalle");

            foreach (DFactura detalle in objProxy.Detalle)
            {
                if (detalle.Producto_id < 1 || detalle.Cantidad < 1)
                    x.AgregarError("Alguno de los elementos del detalle presentan problemas.");
            }

            if (x.Cantidad > 0)
                throw x;

            // TODO: CAMBIAR A WORKFLOW
            DataSet dtsDetalle = new DataSet();
            DataTable tblProxy = dtsDetalle.Tables.Add();
            tblProxy.Columns.Add("Producto_id", typeof(Int32));
            tblProxy.Columns.Add("Cantidad", typeof(Int32));

            foreach (DFactura detalle in objProxy.Detalle)
            {
                tblProxy.Rows.Add(detalle.Producto_id, detalle.Cantidad);
            }

            CAD.WorkFlows.WFLFactura wflProxy = new CAD.WorkFlows.WFLFactura();
            return wflProxy.Insertar(objProxy.Fecha, objProxy.NombreFactura, objProxy.NitFactura, dtsDetalle) > 0;
        }
        public void VerifyMinimum()
        {
            var validationException = new ValidationException(ValidationRules.Minimum, "Id", 3);

            Assert.Equal(ValidationRules.Minimum, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' is less than minimum value of '3'.", validationException.ToString());
        }
        public void VerifyNotNull()
        {
            var validationException = new ValidationException(ValidationRules.CannotBeNull, "Id");

            Assert.Equal(ValidationRules.CannotBeNull, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' cannot be null.", validationException.ToString());
        }
        public void VerifyExclusiveMaximum()
        {
            var validationException = new ValidationException(ValidationRules.ExclusiveMaximum, "Id", 30);

            Assert.Equal(ValidationRules.ExclusiveMaximum, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' is equal or exceeds maximum value of '30'.", validationException.ToString());
        }
        public void VerifyExclusiveMinimum()
        {
            var validationException = new ValidationException(ValidationRules.ExclusiveMinimum, "Id", -1);

            Assert.Equal(ValidationRules.ExclusiveMinimum, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' is less than or equal minimum value of '-1'.", validationException.ToString());
        }
        public void VerifyMaxLenth()
        {
            var validationException = new ValidationException(ValidationRules.MaxLength, "Id", 100);

            Assert.Equal(ValidationRules.MaxLength, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' exceeds maximum length of '100'.", validationException.ToString());
        }
        public void VerifyMinLenth()
        {
            var validationException = new ValidationException(ValidationRules.MinLength, "Id", 12);

            Assert.Equal(ValidationRules.MinLength, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' is less than minimum length of '12'.", validationException.ToString());
        }
        public void VerifyMaximum()
        {
            var validationException = new ValidationException(ValidationRules.Maximum, "Id", 20);

            Assert.Equal(ValidationRules.Maximum, validationException.Rule);
            Assert.Equal("Id", validationException.Target);
            Assert.Equal("Microsoft.Rest.ValidationException: 'Id' exceeds maximum value of '20'.", validationException.ToString());
        }
Esempio n. 11
0
 public static void AddValidationExceptionToModel(this ModelStateDictionary model, string prefix,
     ValidationException exception)
 {
     var errors = exception.Errors;
     foreach (var error in errors)
     {
         model.AddModelError(string.Format("{0}.{1}", prefix, error.PropertyName), error.Message);
     }
 }
        public static void Ctor_Empty()
        {
            ValidationException ex = new ValidationException();
            Assert.NotEmpty(ex.Message);
            Assert.Null(ex.InnerException);

            Assert.NotEmpty(ex.ValidationResult.ErrorMessage);
            Assert.Null(ex.Value);
            Assert.Null(ex.ValidationAttribute);
        }
        public static void Ctor_String(string errorMessage)
        {
            ValidationException ex = new ValidationException(errorMessage);
            Assert.Equal(errorMessage, ex.Message);
            Assert.Null(ex.InnerException);

            Assert.Equal(errorMessage, ex.ValidationResult.ErrorMessage);
            Assert.Null(ex.ValidationAttribute);
            Assert.Null(ex.Value);
        }
        public static void Ctor_String_Exception(string errorMessage)
        {
            Exception innerException = new ArithmeticException();
            ValidationException ex = new ValidationException(errorMessage, innerException);
            Assert.Equal(errorMessage, ex.Message);
            Assert.Same(innerException, ex.InnerException);

            Assert.Equal(errorMessage, ex.ValidationResult.ErrorMessage);
            Assert.Null(ex.ValidationAttribute);
            Assert.Null(ex.Value);
        }
Esempio n. 15
0
        public static int Insert(clsSubFamilies objProxy)
        {
            ValidationException x = new ValidationException();
            if (string.IsNullOrEmpty(objProxy.SSubFamily_name))
                x.AgregarError("verifique el nombre de la subfamilia");
            if (x.Cantidad > 0)
                throw x;

            DAOSubFamily daoProxy = new DAOSubFamily();
            return daoProxy.Insert(objProxy.IFamily_id.IFamily_id,objProxy.SSubFamily_name, objProxy.SSubFamily_desc);
        }
Esempio n. 16
0
        public static bool EliminarLocalidad(int codigo)
        {
            ValidationException x = new ValidationException();
            if (codigo <= 0)
                x.AgregarError("Ingrese el código");

            //if (x.Cantidad > 0)
            //    throw x;

            DAOLocalidad daoProxy = new DAOLocalidad();
            return daoProxy.Eliminar(codigo);
        }
Esempio n. 17
0
        public static bool Delete(int iActive_id)
        {
            ValidationException x = new ValidationException();
            if (iActive_id <= 0)
                x.AgregarError("Ingrese el código del Activo");

            if (x.Cantidad > 0)
                throw x;

            DAOActive daoProxy = new DAOActive();
            return daoProxy.Delete(iActive_id);
        }
Esempio n. 18
0
        public static int Insert(clsCostCenter objProxy)
        {
            ValidationException x = new ValidationException();
            if (string.IsNullOrEmpty(objProxy.SCostCente_name))
                x.AgregarError("Ingrese el nombre del centro de costo");

            if (x.Cantidad > 0)
                throw x;

            DAOCostCenter daoProxy = new DAOCostCenter();
            return daoProxy.Insert(objProxy.SCostCente_name, objProxy.SCostCenter_desc, objProxy.DGestion_time);
        }
Esempio n. 19
0
        public static bool Eliminar(int iCostCenter_id)
        {
            ValidationException x = new ValidationException();
            if (iCostCenter_id <= 0)
                x.AgregarError("Ingrese el código");

            if (x.Cantidad > 0)
                throw x;

            DAOCostCenter daoProxy = new DAOCostCenter();
            return daoProxy.Eliminar(iCostCenter_id);
        }
Esempio n. 20
0
        public static int Insert(clsFamilies objProxy)
        {
            ValidationException x = new ValidationException();
            if (string.IsNullOrEmpty(objProxy.SFamily_name))
                x.AgregarError("Ingrese el nombre de la Familia");

            if (x.Cantidad > 0)
                throw x;

            DAOFamilies daoProxy = new DAOFamilies();
            return daoProxy.Insert(objProxy.SFamily_name,objProxy.SFamily_desc,objProxy.IDepreciation_time);
        }
Esempio n. 21
0
        public static bool Insertar(Empleado objProxy)
        {
            ValidationException x = new ValidationException();
            if (string.IsNullOrEmpty(objProxy.Nombre))
                x.AgregarError("Ingrese el nombre del empleado");

            if (x.Cantidad > 0)
                throw x;

            DAOEmpleado daoProxy = new DAOEmpleado();
            return daoProxy.Insertar(objProxy.Nombre) > 0;
        }
Esempio n. 22
0
        public static bool Delete(int iRol_id)
        {
            ValidationException x = new ValidationException();
            if (iRol_id <= 0)
                x.AgregarError("Ingrese el id del rol");

            if (x.Cantidad > 0)
                throw x;

            DAORol daoProxy = new DAORol();
            return daoProxy.Delete(iRol_id);
        }
Esempio n. 23
0
        public static bool EliminarEmpleado(int codigo)
        {
            ValidationException x = new ValidationException();
            if (codigo <= 0)
                x.AgregarError("Ingrese el código");

            if (x.Cantidad > 0)
                throw x;

            DAOEmpleado daoProxy = new DAOEmpleado();
            return daoProxy.Eliminar(codigo);
        }
Esempio n. 24
0
        public static bool Delete(int iSubFamily_id)
        {
            ValidationException x = new ValidationException();
            if (iSubFamily_id <= 0)
                x.AgregarError("Ingrese el código de la subfamilia");

            if (x.Cantidad > 0)
                throw x;

            DAOSubFamily daoProxy = new DAOSubFamily();
            return daoProxy.Delete(iSubFamily_id);
        }
Esempio n. 25
0
        public static int Insert(clsRol objProxy)
        {
            ValidationException x = new ValidationException();
            if (string.IsNullOrEmpty(objProxy.SRol_name))
                x.AgregarError("Ingrese el nombre del rol");

            if (x.Cantidad > 0)
                throw x;

            DAORol daoProxy = new DAORol();
            return daoProxy.Insert(objProxy.SRol_name,objProxy.sStatus);
        }
Esempio n. 26
0
        public static bool Delete(int iResponsible_id)
        {
            ValidationException x = new ValidationException();
            if (iResponsible_id <= 0)
                x.AgregarError("Ingrese el código de la persona");

            if (x.Cantidad > 0)
                throw x;

            DAOResponsible daoProxy = new DAOResponsible();
            return daoProxy.Delete(iResponsible_id);
        }
Esempio n. 27
0
        public static bool Delete(int iActive_id, int iResponsible_id)
        {
            ValidationException x = new ValidationException();
            if ((iActive_id <= 0)&&(iResponsible_id<=0))
                x.AgregarError("Ingrese el código de la persona y el codigo del activo");

            if (x.Cantidad > 0)
                throw x;

            DAOAsigResponsibleActive daoProxy = new DAOAsigResponsibleActive();
            return daoProxy.Delete(iResponsible_id,iActive_id);
        }
Esempio n. 28
0
        public static bool EliminarProveedor(int codigo)
        {
            ValidationException x = new ValidationException();
            if (codigo <= 0)
                x.AgregarError("Ingrese el código");

            //veamos si lo usamos
            //if (x.Cantidad > 0)
            //    throw x;

            DAOProveedor daoProxy = new DAOProveedor();
            return daoProxy.Eliminar(codigo);
        }
        public static void Ctor_String_ValidationAttribute_Object(string errorMessage)
        {
            ValidationAttribute validatingAttribute = new UrlAttribute();
            object value = new object();

            ValidationException ex = new ValidationException(errorMessage, validatingAttribute, value);
            Assert.Equal(errorMessage, ex.Message);
            Assert.Null(ex.InnerException);

            Assert.Equal(errorMessage, ex.ValidationResult.ErrorMessage);
            Assert.Same(validatingAttribute, ex.ValidationAttribute);
            Assert.Same(value, ex.Value);
        }
Esempio n. 30
0
        public static int Insert(clsAsigResponsibleActive objProxy)
        {
            ValidationException x = new ValidationException();
            //if (string.IsNullOrEmpty(objProxy.DtAsign_time)&& string.IsNullOrEmpty(objProxy.SPerson_lname))
            //    x.AgregarError("verifique el nombre del y el apellido de la persona");

            if (x.Cantidad > 0)
                throw x;

            DAOAsigResponsibleActive daoProxy = new DAOAsigResponsibleActive();

            return daoProxy.Insert(objProxy.SConfirmed_desc,objProxy.SAsignation_desc,objProxy.BStatus,objProxy.DtAsign_time,objProxy.DtDevolution_time,objProxy.BConfirmed,objProxy.IResponsible_id.IResponsible_id,objProxy.IActive_id.IActive_id);
        }
Esempio n. 31
0
 private static IActionResult OnValidationException(ValidationException ex)
 {
     return(ErrorResult(400, new ErrorDto {
         Message = ex.Message, Details = ex.Errors.Select(e => e.Message).ToArray()
     }));
 }
Esempio n. 32
0
        public DatabaseDataSource Update(Guid id, string name, string description, int weight, string eql, string parameters)
        {
            ValidationException validation = new ValidationException();

            if (string.IsNullOrWhiteSpace(eql))
            {
                throw new ArgumentException(nameof(eql));
            }

            List <EqlParameter>        eqlParams = new List <EqlParameter>();
            List <DataSourceParameter> dsParams  = new List <DataSourceParameter>();

            if (!string.IsNullOrWhiteSpace(parameters))
            {
                dsParams = ProcessParametersText(parameters);
                foreach (var dsPar in dsParams)
                {
                    eqlParams.Add(ConvertDataSourceParameterToEqlParameter(dsPar));
                }
            }

            EqlBuilder builder = new EqlBuilder(eql);
            var        result  = builder.Build(eqlParams);

            if (result.Errors.Count > 0)
            {
                foreach (var err in result.Errors)
                {
                    if (err.Line.HasValue || err.Column.HasValue)
                    {
                        validation.AddError("eql", $"{err.Message} [{err.Line},{err.Column}]");
                    }
                    else
                    {
                        validation.AddError("eql", err.Message);
                    }
                }
            }
            validation.CheckAndThrow();

            foreach (var par in result.Parameters)
            {
                if (!eqlParams.Any(x => x.ParameterName == par.ParameterName))
                {
                    validation.AddError("parameters", $"Parameter '{par.ParameterName}' is missing.");
                }
            }
            validation.CheckAndThrow();

            DatabaseDataSource ds = new DatabaseDataSource();

            ds.Id          = id;
            ds.Name        = name;
            ds.Description = description;
            ds.EqlText     = eql;
            ds.SqlText     = result.Sql;
            ds.EntityName  = result.FromEntity.Name;
            ds.Parameters.AddRange(dsParams);
            ds.Fields.AddRange(ProcessFieldsMeta(result.Meta));

            if (string.IsNullOrWhiteSpace(ds.Name))
            {
                validation.AddError("name", "Name is required.");
            }
            else
            {
                var existingDS = GetDatabaseDataSourceByName(ds.Name);
                if (existingDS != null && existingDS.Id != ds.Id)
                {
                    validation.AddError("name", "Another DataSource with same name already exists.");
                }
            }

            if (string.IsNullOrWhiteSpace(ds.EqlText))
            {
                validation.AddError("eql", "Eql is required.");
            }

            if (string.IsNullOrWhiteSpace(ds.SqlText))
            {
                validation.AddError("sql", "Sql is required.");
            }


            validation.CheckAndThrow();

            rep.Update(ds.Id, ds.Name, ds.Description, ds.Weight, ds.EqlText, ds.SqlText,
                       JsonConvert.SerializeObject(ds.Parameters), JsonConvert.SerializeObject(ds.Fields), ds.EntityName);

            RemoveFromCache();

            return(GetDatabaseDataSourceById(ds.Id));
        }
        public async Task UpdateWithInvalidJobDescription()
        {
            OAuth2Token oAuth2Token = new OAuth2TokenBuilder().Build();
            var         link        = $"{AdvertisementLink}/{AdvertisementId}";

            this.Fixture.AdPostingApiService
            .Given("There is a standout advertisement with maximum data")
            .UponReceiving("a PUT advertisement request for advertisement with invalid job description")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Put,
                Path    = link,
                Headers = new Dictionary <string, string>
                {
                    { "Authorization", "Bearer " + oAuth2Token.AccessToken },
                    { "Content-Type", RequestContentTypes.AdvertisementVersion1 },
                    { "Accept", $"{ResponseContentTypes.AdvertisementVersion1}, {ResponseContentTypes.AdvertisementErrorVersion1}" },
                    { "User-Agent", AdPostingApiFixture.UserAgentHeaderValue }
                },
                Body = new AdvertisementContentBuilder(this.MinimumFieldsInitializer)
                       .WithJobDescription("Ad details with <a href='www.youtube.com'>a link</a> and incomplete <h2> element")
                       .Build()
            })
            .WillRespondWith(
                new ProviderServiceResponse
            {
                Status  = 422,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", ResponseContentTypes.AdvertisementErrorVersion1 },
                    { "X-Request-Id", RequestId }
                },
                Body = new
                {
                    message = "Validation Failure",
                    errors  = new[] { new { field = "jobDescription", code = "InvalidFormat" } }
                }
            });

            ValidationException actualException;

            using (AdPostingApiClient client = this.Fixture.GetClient(oAuth2Token))
            {
                actualException = await Assert.ThrowsAsync <ValidationException>(
                    async() => await client.UpdateAdvertisementAsync(new Uri(this.Fixture.AdPostingApiServiceBaseUri, link),
                                                                     new AdvertisementModelBuilder(this.MinimumFieldsInitializer)
                                                                     .WithJobDescription("Ad details with <a href='www.youtube.com'>a link</a> and incomplete <h2> element")
                                                                     .Build()));
            }

            var expectedException =
                new ValidationException(
                    RequestId,
                    HttpMethod.Put,
                    new AdvertisementErrorResponse
            {
                Message = "Validation Failure",
                Errors  = new[] { new AdvertisementError {
                                      Field = "jobDescription", Code = "InvalidFormat"
                                  } }
            });

            actualException.ShouldBeEquivalentToException(expectedException);
        }
Esempio n. 34
0
        /// <summary>
        ///     ArchiveAssignedCourse
        ///     Description: This action archives a course by CourseId PK and cohortId FK
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="cohortId"></param>
        public static void ArchiveAssignedCourse(string courseId, string cohortId)
        {
            var parsedCourseId = 0;
            var parsedCohortId = 0;
            var exception      = new ValidationException();

            using var context = new AppDbContext();

            #region Validation

            courseId = string.IsNullOrEmpty(courseId) || string.IsNullOrWhiteSpace(courseId) ? null : courseId.Trim();
            cohortId = string.IsNullOrEmpty(cohortId) || string.IsNullOrWhiteSpace(cohortId) ? null : cohortId.Trim();

            if (courseId == null)
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(courseId),
                                                                             nameof(courseId) + " is null."));
            }
            else
            {
                if (!int.TryParse(courseId, out parsedCourseId))
                {
                    exception.ValidationExceptions.Add(new Exception("Invalid value for courseId"));
                }
                if (parsedCourseId > 2147483647 || parsedCourseId < 1)
                {
                    exception.ValidationExceptions.Add(
                        new Exception("courseId value should be between 1 & 2147483647 inclusive"));
                }
                else if (!context.Courses.Any(key => key.CourseId == parsedCourseId))
                {
                    exception.ValidationExceptions.Add(new Exception("courseId does not exist"));
                }
            }

            if (cohortId == null)
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(cohortId),
                                                                             nameof(cohortId) + " is null."));
            }
            else
            {
                if (!int.TryParse(cohortId, out parsedCohortId))
                {
                    exception.ValidationExceptions.Add(new Exception("Invalid value for cohortId"));
                }
                if (parsedCohortId > 2147483647 || parsedCohortId < 1)
                {
                    exception.ValidationExceptions.Add(
                        new Exception("cohortId value should be between 1 & 2147483647 inclusive"));
                }

                else if (!context.Cohorts.Any(key => key.CohortId == parsedCohortId))
                {
                    exception.ValidationExceptions.Add(new Exception("cohortId does not exist"));
                }
            }

            if (!context.CohortCourses.Any(key => key.CohortId == parsedCohortId && key.CourseId == parsedCourseId))
            {
                exception.ValidationExceptions.Add(new Exception("No valid Course and Cohort combination found"));
            }
            else if (context.CohortCourses.Any(key =>
                                               key.CohortId == parsedCohortId && key.CourseId == parsedCourseId && key.Archive))
            {
                exception.ValidationExceptions.Add(new Exception("Course and Cohort combination is already archived"));
            }

            if (exception.ValidationExceptions.Count > 0)
            {
                throw exception;
            }

            #endregion

            var homeworks = context.Homeworks
                            .Where(key => key.CohortId == parsedCohortId && key.CourseId == parsedCourseId).ToList();

            foreach (var homework in homeworks)
            {
                var rubrics = context.Rubrics.Where(key => key.HomeworkId == homework.HomeworkId).ToList();
                foreach (var rubric in rubrics)
                {
                    var grades = context.Grades.Where(key => key.RubricId == rubric.RubricId).ToList();
                    foreach (var grade in grades)
                    {
                        grade.Archive = true;
                    }

                    rubric.Archive = true;
                }

                var timesheets = context.Timesheets.Where(key => key.HomeworkId == homework.HomeworkId).ToList();
                foreach (var timesheet in timesheets)
                {
                    timesheet.Archive = true;
                }

                homework.Archive = true;
            }

            var cohortCourse = context.CohortCourses.Find(parsedCohortId, parsedCourseId);
            cohortCourse.Archive = true;

            context.SaveChanges();
        }
 private static ErrorDto OnValidationException(ValidationException ex)
 {
     return(new ErrorDto {
         StatusCode = 400, Message = ex.Summary, Details = ToDetails(ex)
     });
 }
Esempio n. 36
0
 private static IHttpActionResult BadRequest(ValidationException exception)
 {
     return(new BadRequestResult(exception));
 }
        public async Task UpdateWithInvalidFieldValues()
        {
            OAuth2Token oAuth2Token = new OAuth2TokenBuilder().Build();
            var         link        = $"{AdvertisementLink}/{AdvertisementId}";

            this.Fixture.MockProviderService
            .Given("There is a standout advertisement with maximum data")
            .UponReceiving("a PUT advertisement request for advertisement with invalid field values")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Put,
                Path    = link,
                Headers = new Dictionary <string, object>
                {
                    { "Authorization", "Bearer " + oAuth2Token.AccessToken },
                    { "Content-Type", RequestContentTypes.AdvertisementVersion1 },
                    { "Accept", $"{ResponseContentTypes.AdvertisementVersion1}, {ResponseContentTypes.AdvertisementErrorVersion1}" },
                    { "User-Agent", AdPostingApiFixture.UserAgentHeaderValue }
                },
                Body = new AdvertisementContentBuilder(this.MinimumFieldsInitializer)
                       .WithSalaryMinimum(-1.0)
                       .WithAdvertisementType(AdvertisementType.StandOut.ToString())
                       .WithStandoutBullets("new Uzi", "new Remington Model".PadRight(85, '!'), "new AK-47")
                       .WithApplicationEmail("someone(at)some.domain")
                       .WithApplicationFormUrl("htp://somecompany.domain/apply")
                       .WithTemplateItems(
                    new KeyValuePair <object, object>("Template Line 1", "Template Value 1"),
                    new KeyValuePair <object, object>("", "value2"))
                       .Build()
            })
            .WillRespondWith(
                new ProviderServiceResponse
            {
                Status  = 422,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", ResponseContentTypes.AdvertisementErrorVersion1 },
                    { "X-Request-Id", RequestId }
                },
                Body = new
                {
                    message = "Validation Failure",
                    errors  = new[]
                    {
                        new { field = "applicationEmail", code = "InvalidEmailAddress" },
                        new { field = "applicationFormUrl", code = "InvalidUrl" },
                        new { field = "salary.minimum", code = "ValueOutOfRange" },
                        new { field = "standout.bullets[1]", code = "MaxLengthExceeded" },
                        new { field = "template.items[1].name", code = "Required" }
                    }
                }
            });

            ValidationException actualException;

            using (AdPostingApiClient client = this.Fixture.GetClient(oAuth2Token))
            {
                actualException = await Assert.ThrowsAsync <ValidationException>(
                    async() => await client.UpdateAdvertisementAsync(new Uri(this.Fixture.AdPostingApiServiceBaseUri, link),
                                                                     new AdvertisementModelBuilder(this.MinimumFieldsInitializer)
                                                                     .WithAdvertisementType(AdvertisementType.StandOut)
                                                                     .WithSalaryMinimum(-1)
                                                                     .WithStandoutBullets("new Uzi", "new Remington Model".PadRight(85, '!'), "new AK-47")
                                                                     .WithApplicationEmail("someone(at)some.domain")
                                                                     .WithApplicationFormUrl("htp://somecompany.domain/apply")
                                                                     .WithTemplateItems(
                                                                         new TemplateItem {
                    Name = "Template Line 1", Value = "Template Value 1"
                },
                                                                         new TemplateItem {
                    Name = "", Value = "value2"
                })
                                                                     .Build()));
            }

            var expectedException =
                new ValidationException(
                    RequestId,
                    HttpMethod.Put,
                    new AdvertisementErrorResponse
            {
                Message = "Validation Failure",
                Errors  = new[]
                {
                    new Error {
                        Field = "applicationEmail", Code = "InvalidEmailAddress"
                    },
                    new Error {
                        Field = "applicationFormUrl", Code = "InvalidUrl"
                    },
                    new Error {
                        Field = "salary.minimum", Code = "ValueOutOfRange"
                    },
                    new Error {
                        Field = "standout.bullets[1]", Code = "MaxLengthExceeded"
                    },
                    new Error {
                        Field = "template.items[1].name", Code = "Required"
                    }
                }
            });

            actualException.ShouldBeEquivalentToException(expectedException);
        }
Esempio n. 38
0
        public void CanConstruct()
        {
            var validationException = new ValidationException(new RuntimeBinderException("poopoo"));

            validationException.Message.Should().Be("poopoo");
        }
Esempio n. 39
0
 public void HandleValidation(ValidationException ex, IDeployEvents callback)
 {
     _logger.Error("Validation exception is catched", ex);
     HandleException(ex);
 }
Esempio n. 40
0
        private IdsException IterateFaultAndPrepareException(Fault fault)
        {
            if (fault == null)
            {
                return(null);
            }

            IdsException idsException = null;

            // Create a list of exceptions.
            List <IdsError> aggregateExceptions = new List <IdsError>();

            // Check whether the fault is null or not.
            if (fault != null)
            {
                // Fault types can be of Validation, Service, Authentication and Authorization. Run them through the switch case.
                switch (fault.type)
                {
                // If Validation errors iterate the Errors and add them to the list of exceptions.
                case "Validation":
                case "ValidationFault":
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw specific exception like ValidationException.
                        idsException = new ValidationException(aggregateExceptions);
                    }

                    break;

                // If Validation errors iterate the Errors and add them to the list of exceptions.
                case "Service":
                case "ServiceFault":
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw specific exception like ServiceException.
                        idsException = new ServiceException(aggregateExceptions);
                    }

                    break;

                // If Validation errors iterate the Errors and add them to the list of exceptions.
                case "Authentication":
                case "AuthenticationFault":
                case "Authorization":
                case "AuthorizationFault":
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw specific exception like AuthenticationException which is wrapped in SecurityException.
                        idsException = new SecurityException(aggregateExceptions);
                    }

                    break;

                // Use this as default if there was some other type of Fault
                default:
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw generic exception like IdsException.
                        idsException = new IdsException(string.Format(CultureInfo.InvariantCulture, "Fault Exception of type: {0} has been generated.", fault.type), aggregateExceptions);
                    }

                    break;
                }
            }

            // Return idsException which will be of type Validation, Service or Security.
            return(idsException);
        }
        public void DefaultConstructorCreatesAnEmptyErrorDictionary()
        {
            var actual = new ValidationException().Errors;

            actual.Keys.Should().BeEquivalentTo(Array.Empty <string>());
        }
Esempio n. 42
0
        /// <summary>
        ///     UpdateAssignedCourse
        ///     Description: This action updates a cohort assigned course details
        /// </summary>
        /// <param name="cohortId"></param>
        /// <param name="courseId"></param>
        /// <param name="instructorId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="resourcesLink"></param>
        public static void UpdateAssignedCourse(string cohortId, string courseId, string instructorId, string startDate,
                                                string endDate, string resourcesLink)
        {
            var parsedCohortId     = 0;
            var parsedCourseId     = 0;
            var parsedInstructorId = 0;
            var parsedStartDate    = new DateTime();
            var parsedEndDate      = new DateTime();
            var exception          = new ValidationException();

            using var context = new AppDbContext();

            #region Validation

            cohortId     = string.IsNullOrEmpty(cohortId) || string.IsNullOrWhiteSpace(cohortId) ? null : cohortId.Trim();
            courseId     = string.IsNullOrEmpty(courseId) || string.IsNullOrWhiteSpace(courseId) ? null : courseId.Trim();
            instructorId = string.IsNullOrEmpty(instructorId) || string.IsNullOrWhiteSpace(instructorId)
                ? null
                : instructorId.Trim();
            startDate = string.IsNullOrEmpty(startDate) || string.IsNullOrWhiteSpace(startDate)
                ? null
                : startDate.Trim();
            endDate       = string.IsNullOrEmpty(endDate) || string.IsNullOrWhiteSpace(endDate) ? null : endDate.Trim();
            resourcesLink = string.IsNullOrEmpty(resourcesLink) || string.IsNullOrWhiteSpace(resourcesLink)
                ? null
                : resourcesLink.Trim().ToLower();

            if (string.IsNullOrWhiteSpace(cohortId))
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(cohortId),
                                                                             nameof(cohortId) + " is null."));
            }
            else
            {
                if (!int.TryParse(cohortId, out parsedCohortId))
                {
                    exception.ValidationExceptions.Add(new Exception("Invalid value for cohortId"));
                }
                if (parsedCohortId > 2147483647 || parsedCohortId < 1)
                {
                    exception.ValidationExceptions.Add(
                        new Exception("cohortId value should be between 1 & 2147483647 inclusive"));
                }
                else if (!context.Cohorts.Any(key => key.CohortId == parsedCohortId))
                {
                    exception.ValidationExceptions.Add(new Exception("cohortId does not exist"));
                }
                else if (!context.Cohorts.Any(key => key.CohortId == parsedCohortId && key.Archive == false))
                {
                    exception.ValidationExceptions.Add(new Exception("Cohort is archived"));
                }
            }

            if (string.IsNullOrWhiteSpace(courseId))
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(courseId),
                                                                             nameof(courseId) + " is null."));
            }
            else
            {
                if (!int.TryParse(courseId, out parsedCourseId))
                {
                    exception.ValidationExceptions.Add(new Exception("Invalid value for courseId"));
                }
                if (parsedCourseId > 2147483647 || parsedCourseId < 1)
                {
                    exception.ValidationExceptions.Add(
                        new Exception("courseId value should be between 1 & 2147483647 inclusive"));
                }
                else if (!context.Courses.Any(key => key.CourseId == parsedCourseId))
                {
                    exception.ValidationExceptions.Add(new Exception("courseId does not exist"));
                }
                else if (!context.Courses.Any(key => key.CourseId == parsedCourseId && key.Archive == false))
                {
                    exception.ValidationExceptions.Add(new Exception("Course is archived"));
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(cohortId) && int.TryParse(cohortId, out parsedCohortId) &&
                        !context.CohortCourses.Any(key =>
                                                   key.CohortId == parsedCohortId && key.CourseId == parsedCourseId))
                    {
                        exception.ValidationExceptions.Add(new Exception("No Combination of Cohort and Course found"));
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(instructorId))
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(instructorId),
                                                                             nameof(instructorId) + " is null."));
            }
            else
            {
                if (!int.TryParse(instructorId, out parsedInstructorId))
                {
                    exception.ValidationExceptions.Add(new Exception("Invalid value for instructorId"));
                }
                if (parsedInstructorId > 2147483647 || parsedInstructorId < 1)
                {
                    exception.ValidationExceptions.Add(
                        new Exception("instructorId value should be between 1 & 2147483647 inclusive"));
                }
                else if (!context.Users.Any(key => key.UserId == parsedInstructorId && key.IsInstructor))
                {
                    exception.ValidationExceptions.Add(new Exception("instructorId does not exist"));
                }
                else if (!context.Users.Any(key =>
                                            key.UserId == parsedInstructorId && key.IsInstructor && key.Archive == false))
                {
                    exception.ValidationExceptions.Add(new Exception("Instructor is archived"));
                }
            }

            if (!string.IsNullOrWhiteSpace(resourcesLink))
            {
                if (resourcesLink.Length > 250)
                {
                    exception.ValidationExceptions.Add(new Exception("resourcesLink can only be 250 characters long."));
                }
                else
                {
                    /** Citation
                     *  https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url
                     *  Referenced above source to validate the incoming Resources Link (URL) before saving to DB.
                     */
                    Uri uri;
                    if (!(Uri.TryCreate(resourcesLink, UriKind.Absolute, out uri) &&
                          (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps ||
                           uri.Scheme == Uri.UriSchemeFtp)))
                    {
                        exception.ValidationExceptions.Add(new Exception("resourcesLink is not valid."));
                    }
                    /*End Citation*/
                }
            }

            if (string.IsNullOrWhiteSpace(startDate))
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(startDate),
                                                                             nameof(startDate) + " is null."));
            }
            else if (!DateTime.TryParse(startDate, out parsedStartDate))
            {
                exception.ValidationExceptions.Add(new Exception("Invalid value for startDate"));
            }
            if (string.IsNullOrWhiteSpace(endDate))
            {
                exception.ValidationExceptions.Add(new ArgumentNullException(nameof(endDate),
                                                                             nameof(endDate) + " is null."));
            }
            else if (!DateTime.TryParse(endDate, out parsedEndDate))
            {
                exception.ValidationExceptions.Add(new Exception("Invalid value for endDate"));
            }

            /* Business Logic*/
            if (DateTime.TryParse(startDate, out parsedStartDate) && DateTime.TryParse(endDate, out parsedEndDate))
            {
                if (parsedEndDate < parsedStartDate)
                {
                    exception.ValidationExceptions.Add(new Exception("endDate can not be before startDate."));
                }
            }
            if (exception.ValidationExceptions.Count > 0)
            {
                throw exception;
            }

            #endregion

            var course = context.CohortCourses.Find(parsedCohortId, parsedCourseId);
            course.CohortId      = parsedCohortId;
            course.CourseId      = parsedCourseId;
            course.InstructorId  = parsedInstructorId;
            course.StartDate     = parsedStartDate;
            course.EndDate       = parsedEndDate;
            course.ResourcesLink = resourcesLink;

            context.SaveChanges();
        }
Esempio n. 43
0
        protected void ValidateRecordSubmission(EntityRecord postObject, Entity entity, ValidationException validation)
        {
            if (entity == null || postObject == null || postObject.Properties.Count == 0 || validation == null)
            {
                return;
            }

            foreach (var property in postObject.Properties)
            {
                //TODO relations validation
                if (property.Key.StartsWith("$"))
                {
                    continue;
                }

                Field fieldMeta = entity.Fields.FirstOrDefault(x => x.Name == property.Key);
                if (fieldMeta != null)
                {
                    switch (fieldMeta.GetFieldType())
                    {
                    case FieldType.AutoNumberField:
                        if (property.Value != null && !String.IsNullOrWhiteSpace(property.Value.ToString()))
                        {
                            validation.Errors.Add(new ValidationError(property.Key, "Autonumber field value should be null or empty string"));
                        }
                        break;

                    default:
                        if (fieldMeta.Required &&
                            (property.Value == null || String.IsNullOrWhiteSpace(property.Value.ToString())))
                        {
                            validation.Errors.Add(new ValidationError(property.Key, "Required"));
                        }
                        break;
                    }
                }
            }
        }
Esempio n. 44
0
    private void ValidatePermission()
    {
        try
        {
            ValidationException exception = new ValidationException(VALIDATIONERROR);

            //*** Locations ***//
            bool isLocationChecked = false;
            foreach (TreeNode node in tvLocations.Nodes)
            {
                if (node.Checked == true)
                {
                    isLocationChecked = true;
                }
            }

            if (!isLocationChecked)
            {
                exception.Data.Add("LOCATIONS", ALERTMSGFIELD + " " + lblLocations.Text);
            }


            //*** Client ***//
            bool isClientChecked = false;
            foreach (TreeNode node in tvClients.Nodes)
            {
                if (node.Checked == true)
                {
                    isClientChecked = true;
                }
            }

            if (!isClientChecked)
            {
                exception.Data.Add("CLIENTS", ALERTMSGFIELD + " " + lblClients.Text);
            }


            //*** Report ***//
            bool isReportChecked = false;
            foreach (TreeNode node in tvReports.Nodes)
            {
                if (node.Checked == true)
                {
                    isReportChecked = true;
                }
            }

            if (!isReportChecked)
            {
                exception.Data.Add("REPORTS", ALERTMSGFIELD + " " + lblReports.Text);
            }


            if (UIMODEPERMISSION == UIMODEPERMISSION.EDIT)
            {
                if (string.IsNullOrEmpty(Convert.ToString(txtReason.Value)))
                {
                    exception.Data.Add("REASON", lblreason.Text + ALERTMSG);
                }
            }


            // Throw an exception.
            if (exception.Data.Count > 0)
            {
                throw exception;
            }
        }
        catch { throw; }
    }
        public async Task UpdateWithInvalidFieldValues()
        {
            OAuth2Token oAuth2Token = new OAuth2TokenBuilder().Build();
            var         link        = $"{AdvertisementLink}/{AdvertisementId}";

            this.Fixture.AdPostingApiService
            .Given("There is a standout advertisement with maximum data")
            .UponReceiving("a PUT advertisement request for advertisement with invalid field values")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Put,
                Path    = link,
                Headers = new Dictionary <string, string>
                {
                    { "Authorization", "Bearer " + oAuth2Token.AccessToken },
                    { "Content-Type", RequestContentTypes.AdvertisementVersion1 },
                    { "Accept", $"{ResponseContentTypes.AdvertisementVersion1}, {ResponseContentTypes.AdvertisementErrorVersion1}" },
                    { "User-Agent", AdPostingApiFixture.UserAgentHeaderValue }
                },
                Body = new AdvertisementContentBuilder(this.MinimumFieldsInitializer)
                       .WithSalaryMinimum((decimal) - 1.0)
                       .WithSalaryMaximum((decimal)3000.0)
                       .WithSalaryCurrencyCode(1)
                       .WithApplicationEmail("klang(at)seekasia.domain")
                       .WithApplicationFormUrl("htp://ww.seekasia.domain/apply")
                       .WithJobTitle("Temporary part-time libraries North-West inter-library loan business unit administration assistant")
                       .Build()
            })
            .WillRespondWith(
                new ProviderServiceResponse
            {
                Status  = 422,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", ResponseContentTypes.AdvertisementErrorVersion1 },
                    { "X-Request-Id", RequestId }
                },
                Body = new
                {
                    message = "Validation Failure",
                    errors  = new[]
                    {
                        new { field = "applicationEmail", code = "InvalidEmailAddress" },
                        new { field = "applicationFormUrl", code = "InvalidUrl" },
                        new { field = "salary.minimum", code = "ValueOutOfRange" },
                        new { field = "jobTitle", code = "MaxLengthExceeded" },
                        new { field = "salary.display", code = "Required" }
                    }
                }
            });

            ValidationException actualException;

            using (AdPostingApiClient client = this.Fixture.GetClient(oAuth2Token))
            {
                actualException = await Assert.ThrowsAsync <ValidationException>(
                    async() => await client.UpdateAdvertisementAsync(new Uri(this.Fixture.AdPostingApiServiceBaseUri, link),
                                                                     new AdvertisementModelBuilder(this.MinimumFieldsInitializer)
                                                                     .WithSalaryMinimum((decimal) - 1.0)
                                                                     .WithSalaryMaximum((decimal)3000.0)
                                                                     .WithSalaryCurrencyCode(1)
                                                                     .WithApplicationEmail("klang(at)seekasia.domain")
                                                                     .WithApplicationFormUrl("htp://ww.seekasia.domain/apply")
                                                                     .WithJobTitle("Temporary part-time libraries North-West inter-library loan business unit administration assistant")
                                                                     .Build()));
            }

            var expectedException =
                new ValidationException(
                    RequestId,
                    HttpMethod.Put,
                    new AdvertisementErrorResponse
            {
                Message = "Validation Failure",
                Errors  = new[]
                {
                    new AdvertisementError {
                        Field = "applicationEmail", Code = "InvalidEmailAddress"
                    },
                    new AdvertisementError {
                        Field = "applicationFormUrl", Code = "InvalidUrl"
                    },
                    new AdvertisementError {
                        Field = "salary.minimum", Code = "ValueOutOfRange"
                    },
                    new AdvertisementError {
                        Field = "jobTitle", Code = "MaxLengthExceeded"
                    },
                    new AdvertisementError {
                        Field = "salary.display", Code = "Required"
                    }
                }
            });

            actualException.ShouldBeEquivalentToException(expectedException);
        }