/// <summary>
        /// Validate min and max all property between entity and viewmodel.
        /// </summary>
        /// <typeparam name="T">The entity type.</typeparam>
        /// <typeparam name="TT">The view model type.</typeparam>
        /// <param name="validator"></param>
        /// <returns></returns>
        public static ValidationResultViewModel ValidateStringLength <T, TT>(TT validator)
        {
            var result = new ValidationResultViewModel();

            foreach (var propertyInfoModel in typeof(T).GetProperties().Where(m => m.PropertyType.FullName == "System.String"))
            {
                var propertyInfoViewModel = validator.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyInfoModel.Name);
                if (propertyInfoViewModel == null)
                {
                    continue;
                }
                int target = propertyInfoViewModel.GetValue(validator) != null?propertyInfoViewModel.GetValue(validator).ToString().Length : 0;

                var length = typeof(T).GetProperty(propertyInfoModel.Name).GetCustomAttributes(typeof(StringLengthAttribute), false).Cast <StringLengthAttribute>().SingleOrDefault();
                if (length != null && target > length.MaximumLength)
                {
                    var error = new ModelStateError();
                    result.ErrorFlag = true;
                    error.Key        = propertyInfoModel.Name;
                    error.Message    = string.Format("{0} ความยาวเกินกำหนด (ไม่เกิน {1} ตัวอักษร)", propertyInfoModel.Name, length.MaximumLength);
                    result.ModelStateErrorList.Add(error);
                }
            }
            return(result);
        }
Ejemplo n.º 2
0
 private void AddErrors(ValidationResultViewModel result)
 {
     foreach (var error in result.Errors)
     {
         ModelState.AddModelError("", error);
     }
 }
        /// <summary>
        /// Config handle message status code 403.
        /// </summary>
        /// <param name="app"></param>
        public static void ConfigureHandlerStatusPages(this IApplicationBuilder app)
        {
            app.UseStatusCodePages(async context =>
            {
                if (context.HttpContext.Response.StatusCode == 403 || context.HttpContext.Response.StatusCode == 401)
                {
                    string message = string.Empty;
                    switch (context.HttpContext.Response.StatusCode)
                    {
                    case 403:
                        message = "Not Permissino.";
                        break;

                    case 401:
                        message = "Unauthorized.";
                        break;
                    }
                    var model = new ValidationResultViewModel
                    {
                        ErrorFlag = true,
                        Message   = message
                    };
                    string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    });
                    context.HttpContext.Response.ContentType = ConstantValue.CONTENT_TYPEJSON;
                    await context.HttpContext.Response.WriteAsync(json);
                }
            });
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Validate(PassportViewModel model)
        {
            if (ModelState.IsValid)
            {
                var endPoint = string.Concat(_apiSettings.Value.ValidationEndPoint, "ValidateMZR");

                var passportModel = new PassportModel(
                    model.PassportNo,
                    model.Nationality,
                    model.Gender,
                    model.DateOfBirth.ToString("yyMMdd"),
                    model.DateOfExpiration.ToString("yyMMdd"),
                    AlphaNumericChevronOnly(model.PassportNumber),
                    NumericOnly(model.PassportNumberChecksum),
                    AlphaChevronOnly(model.NationalityCode),
                    NumericOnly(model.DateOfBirthMzr),
                    NumericOnly(model.DOBChecksum),
                    GenderString(model.Sex),
                    NumericOnly(model.PassportExpiration),
                    NumericOnly(model.ExpirationChecksum),
                    AlphaNumericChevronOnly(model.PersonalNumber),
                    NumericChevronOnly(model.PersonalNumberChecksum),
                    NumericOnly(model.FinalChecksum),
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false,
                    false);


                var response = await ApiClientFactory.Instance.ValidatePassport(passportModel, endPoint);


                var results = new ValidationResultViewModel();
                results.PassportNumberChecksumValid = response.Data.PassportNumberChecksumValid;
                results.DOBChecksumValid            = response.Data.DateOfBirthChecksumValid;
                results.ExpirationChecksumValid     = response.Data.PassportExpirationChecksumValid;
                results.PersonalNumberChecksumValid = response.Data.PersonalNumberChecksumValid;
                results.FinalChecksumValid          = response.Data.FinalChecksumValid;
                results.GenderCCValid         = response.Data.GenderCrossCheckValid;
                results.DOBCCValid            = response.Data.DateOfBirthCrossCheckValid;
                results.ExpirationDateCCValid = response.Data.PassportExpCrossCheckValid;
                results.NationalityCCValid    = response.Data.NationalityCrossCheckValid;
                results.PassportNoCCValid     = response.Data.PassportNoCrossCheckValid;



                ModelState.Clear();
                return(View(results));
            }

            return(await Index());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// This method is responsible for persisting the incoming image into the database.
        /// </summary>
        /// <param name="idCompare">Id that the image belongs to</param>
        /// <param name="model">Instance of a class that contains the base64 encoded string</param>
        /// <param name="imageSide">Enum value that indicates the image side - ( 0 = Left and 1 = Right )</param>
        /// <returns></returns>
        public ValidationResultViewModel AddImage(int idCompare, IncomeImageViewModel model, Constants.ImageSide imageSide)
        {
            ValidationResultViewModel modelReturn = new ValidationResultViewModel();
            WAESImage item = _waesImageService.GetBySenderIdAndSide(idCompare, (int)imageSide);

            //I decided to remove the previous record, if exists, to keep comparison clear
            if (item != null)
            {
                Logger.LogInfo("Removing previous '" + SharedMethods.GetEnumDescription(imageSide) + "' image of Id '" + idCompare + "'");
                BeginTransaction();
                _waesImageService.Remove(item);
                Commit();
            }

            //Validating if the image content is valid
            if (SharedMethods.IsBase64Valid(model.Base64Image))
            {
                Logger.LogInfo("Creating new '" + SharedMethods.GetEnumDescription(imageSide) + "' image of Id '" + idCompare + "'");
                //Creating the instance of the model to persist on database
                item = new WAESImage()
                {
                    IdCompare = idCompare,
                    Side      = (int)imageSide
                };

                item.ImageContent = Convert.FromBase64String(model.Base64Image);
                //Validating the model before persist
                if (item.IsValid())
                {
                    try
                    {
                        BeginTransaction();
                        _waesImageService.Add(item);
                        Commit();

                        modelReturn         = MountReturn(Constants.PossibleReturns.SUCCESSFULLY_SAVED);
                        modelReturn.Message = String.Format(modelReturn.Message, idCompare);
                    }
                    catch (Exception ex)
                    {
                        modelReturn         = MountReturn(Constants.PossibleReturns.ERROR);
                        modelReturn.Message = modelReturn.Message + " : " + ex.Message;
                    }
                }
                else
                {
                    modelReturn = MountReturn(Constants.PossibleReturns.ERROR);
                }
            }
            else
            {
                modelReturn = MountReturn(Constants.PossibleReturns.INVALID_BASE64_PARAMETER);
            }
            Logger.LogInfo(modelReturn.Message);
            return(modelReturn);
        }
        public ValidationResultViewModel BuildResult(ValidationOutcome outcome, string reportingYear = "", string reportName = "", string datasetName = "")
        {
            var result = new ValidationResultViewModel();

            result.Quality = OutcomeQuality(outcome);

            result.HelpTopic = outcome.GetDescription();
            if (string.IsNullOrEmpty(result.HelpTopic))
            {
                result.HelpTopic = "DEPENDENCY CHECK";
                result.HelpText  = "Click here for more information";
            }
            else if (result.HelpTopic.ContainsIgnoreCase("Warning") || result.HelpTopic.ContainsIgnoreCase("Error"))
            {
                result.HelpTopic = result.HelpTopic.Replace("Warning ", null).Replace("Error ", null);
                result.HelpText  = "Click here for more information";
            }

            if (result.Quality == ValidationLevel.Success)
            {
                return(result);
            }

            var temp = OutcomeMesssage(outcome);

            switch (outcome)
            {
            case ValidationOutcome.StaleBaseData:
                temp = string.Format(temp, SourceViewModel.Website.ReportedYear, reportingYear, reportName);
                break;

            case ValidationOutcome.CostToChargeUndefined:
            case ValidationOutcome.RealtimePhysicianDataCannotHaveSubReports:
                temp = string.Format(temp, reportName);
                break;

            case ValidationOutcome.CmsProviderIdUnmapped:
            case ValidationOutcome.HospitalProfileMissingLocalHospIdOrProviderId:
            case ValidationOutcome.CostQualityAllFamilySelected:
                temp = string.Format(temp, reportName);
                break;

            //case ValidationOutcome.HospitalProfileMissingMedicareDataset:
            //case ValidationOutcome.HospitalProfileMissingIPDataset:
            case ValidationOutcome.NoMeasuresForTheDataSet:
            case ValidationOutcome.QIUnMappedHospitalLocalId:
            case ValidationOutcome.UnMappedHospitalLocalId:
            case ValidationOutcome.UnMappedHospitalProfileLocalId:
                temp = string.Format(temp, datasetName);
                break;
            }
            result.Message = temp;

            result.CompositionArea = OutcomeArea(outcome);
            return(result);
        }
Ejemplo n.º 7
0
        //I created this private method just to encapsulate creation of the return model, with a purpose to do not repeat code
        private ValidationResultViewModel MountReturn(Constants.PossibleReturns enmItem)
        {
            ValidationResultViewModel vrVW = new ValidationResultViewModel()
            {
                Result  = (int)enmItem,
                Message = SharedMethods.GetEnumDescription(enmItem) // Using am Enum, I can use its description as the message value
            };

            return(vrVW);
        }
        /// <summary>
        /// Guards the error.
        /// </summary>
        /// <param name="elementName">Name of the element.</param>
        /// <param name="error">The error.</param>
        /// <param name="recordNum">The record number.</param>
        /// <param name="resultType">Type of the result.</param>
        /// <param name="session">The session.</param>
        private void GuardError(string elementName, string error, int recordNum, RecordState resultType, IStatelessSession session)
        {
            var result = new ValidationResultViewModel(DataContextObject.DatasetItem)
            {
                ElementName  = elementName,
                Message      = error,
                ResultType   = resultType,
                RecordNumber = recordNum,
            };

            session.Insert(result.TransactionRecord);
        }
        public static ValidationResultViewModel GetValidationResultViewModel <TModel, TProperty>(this HtmlHelper <TModel> html, VacancyViewModel vacancyViewModel, Expression <Func <TModel, TProperty> > propertyExpression, ModelStateDictionary modelState, string viewWarningUrl, string comment)
        {
            var propertyName = ExpressionHelper.GetExpressionText(propertyExpression);

            var anchorName = propertyName.Replace(".", "_").ToLower();
            var hasError   = modelState.HasErrorsFor(propertyName);
            var error      = modelState.ErrorMessageFor(propertyName);
            var hasWarning = modelState.HasWarningsFor(propertyName);
            var warning    = modelState.WarningMessageFor(propertyName);

            viewWarningUrl = $"{viewWarningUrl}#{propertyName.Substring(propertyName.LastIndexOf(".", StringComparison.Ordinal) + 1).ToLower()}";

            var validationResultViewModel = new ValidationResultViewModel(vacancyViewModel.Status, anchorName, hasError, error, hasWarning, warning, viewWarningUrl, comment);

            return(validationResultViewModel);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Custom when request exception.
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        private static Task HandleExceptionAsync(HttpContext httpContext, Exception exception)
        {
            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode  = (int)System.Net.HttpStatusCode.InternalServerError;

            //var model = new { httpContext.Response.StatusCode, exception.Message };
            var model = new ValidationResultViewModel {
                ErrorFlag = true, Message = exception.Message
            };

            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            return(httpContext.Response.WriteAsync(json));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Update Ca and upload file.
        /// </summary>
        /// <param name="model">The infomation ca.</param>
        /// <returns></returns>
        public ValidationResultViewModel Delete(int id, string documentNo)
        {
            var result = new ValidationResultViewModel();

            using (var scope = new TransactionScope())
            {
                _unitOfWork.GetRepository <Ca>().Remove(id);
                _unitOfWork.Complete();

                //Attachment file
                _attachmemt.RemoveFile(id, CaViewModel.ProcessCode, documentNo);

                _elastic.Delete(id, ConstantValue.CAIndex, ConstantValue.CAType);

                scope.Complete();
            }
            return(result);
        }
        /// <summary>
        /// Add Jwt Authentication and Setting.
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        public static void ConfigureJwtAuthen(this IServiceCollection services, IConfiguration Configuration)
        {
            var option = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ClockSkew        = System.TimeSpan.Zero,
                ValidIssuer      = Configuration["Jwt:Issuer"],
                ValidAudience    = Configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = option;
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                        var model = new ValidationResultViewModel
                        {
                            ErrorFlag = true,
                            Message   = "Unauthorized."
                        };
                        string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });
                        context.Response.OnStarting(async() =>
                        {
                            context.Response.ContentType = ConstantValue.CONTENT_TYPEJSON;
                            await context.Response.WriteAsync(json);
                        });
                        return(System.Threading.Tasks.Task.CompletedTask);
                    },
                };
            });
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This method is responsible for comparing previously registered images based on the incoming id
        /// </summary>
        /// <param name="idCompare">Id for finding previously registered images</param>
        /// <returns></returns>
        public ValidationResultViewModel CompareImages(int idCompare)
        {
            ValidationResultViewModel modelReturn = new ValidationResultViewModel();
            int left  = (int)Constants.ImageSide.Left;
            int right = (int)Constants.ImageSide.Right;
            //Creating the list base on the incoming Id
            List <WAESImage> listItems = _waesImageService.GetAllBySenderId(idCompare).ToList();

            //Verifying the size of the list, and then processing the correct action based on list size
            switch (listItems.Count())
            {
            case 0:     // Case the list is empty, return the message where no files associated with the incoming Id were found
            {
                modelReturn         = MountReturn(Constants.PossibleReturns.NO_FILES);
                modelReturn.Message = String.Format(modelReturn.Message, idCompare);
                break;
            }

            case 1:     // Case there is only one image, must identify missing item side to return the correct message
            {
                modelReturn = MountReturn(Constants.PossibleReturns.FILE_NOT_FOUND);
                string    messageSide = "Left";
                WAESImage item        = _waesImageService.GetBySenderIdAndSide(idCompare, left);
                if (item != null)
                {
                    messageSide = "Right";
                }
                modelReturn.Message = String.Format(modelReturn.Message, messageSide);
                break;
            }

            case 2:     // Ok, there are 2 files, so must compare the images and return proper message
            {
                //Variable that will indicate that there are different pixels within two images with the same size
                int numberOfDiffs = 0;

                // Here I'm invoking a method that compares two different images. This method belongs to a shared library present in
                // the WAS.Infra.CrossCutting.Utilities project, I decided to put this method there to respect the Single Responsibility principle
                // If true, it means that the images have same size, but if numberOfDiffs > 0, then images have same size, but they are different
                // if false, it means that the images are different
                if (SharedMethods.GetDifferenceBetweenImages(listItems.Where(x => x.Side.Equals(left)).FirstOrDefault().ImageContent, listItems.Where(x => x.Side.Equals(right)).FirstOrDefault().ImageContent, ref numberOfDiffs))
                {
                    if (numberOfDiffs > 0)
                    {
                        modelReturn         = MountReturn(Constants.PossibleReturns.SAME_SIZE_DIFFERENT);
                        modelReturn.Message = String.Format(modelReturn.Message, idCompare);

                        Logger.LogInfo(modelReturn.Message);
                    }
                    else
                    {
                        modelReturn         = MountReturn(Constants.PossibleReturns.EQUAL_FILES);
                        modelReturn.Message = String.Format(modelReturn.Message, idCompare);
                    }
                }
                else
                {
                    modelReturn         = MountReturn(Constants.PossibleReturns.DIFFERENT_FILES);
                    modelReturn.Message = String.Format(modelReturn.Message, idCompare);
                }
                break;
            }
            }
            Logger.LogInfo(modelReturn.Message);
            return(modelReturn);
        }
 public ImportValidationResultPopUp()
 {
     InitializeComponent();
     _vm = DataContext as ValidationResultViewModel;
     
 }
 public ValidationResultsPopUp()
 {
     InitializeComponent();
     _vm = DataContext as ValidationResultViewModel;
     _vm.RequestClose += (s, e) => this.Close();
 }
Ejemplo n.º 16
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var email = await _userManager.GetEmailAsync(user);

            if (Input.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email);

                if (!setEmailResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
                }
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
                }
            }

            if (Input.Upload != null)
            {
                var allowedContentTypes = new List <string>
                {
                    FileHelpers.GetMimeType("png"),
                    FileHelpers.GetMimeType("jpg")
                };

                var uploadFile = await FileHelpers.ProcessFormFile(Input.Upload, ModelState, allowedContentTypes);

                if (!ModelState.IsValid)
                {
                    var validationResult = new ValidationResultViewModel(ModelState);
                    var body             = string.Empty;

                    foreach (var vm in validationResult.Errors)
                    {
                        body += string.Format("{0}: {1}", vm.FieldName, vm.Message);
                    }

                    AlertViewModel alert = new AlertViewModel
                    {
                        AlertType  = AlertTypes.Danger.ToString().ToLower(),
                        AlertTitle = validationResult.Message,
                        AlertBody  = body
                    };
                    TempData.Put <AlertViewModel>("alert", alert);

                    return(Page());
                }
                var applicationUser = _context.ApplicationUsers.FirstOrDefault(x => x.UserName == user.UserName);
                if (applicationUser == null)
                {
                    throw new Exception("Application User not found.");
                }
                var avatarUrl = Path.Combine("/img/avatars/", Path.GetFileName(Input.Upload.FileName));

                applicationUser.AvatarURL = avatarUrl;

                var file = Path.Combine(_hostingEnvironment.WebRootPath, "img", "avatars", Path.GetFileName(Input.Upload.FileName));

                using (var fileStream = new FileStream(file, FileMode.Create))
                {
                    await Input.Upload.CopyToAsync(fileStream);
                }

                await _context.SaveChangesAsync();
            }

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Your profile has been updated";
            return(RedirectToPage());
        }