Exemplo n.º 1
0
        public void Should_persist_to_modelstate()
        {
            var modelstate = new ModelStateDictionary();

            result.AddToModelState(modelstate, null);

            modelstate.IsValid.ShouldBeFalse();
            modelstate["foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred");
            modelstate["bar"].Errors[0].ErrorMessage.ShouldEqual("A bar error occurred");
        }
Exemplo n.º 2
0
        public async Task <IActionResult> AddInvitation([CustomizeValidator(Skip = true)][FromBody]
                                                        InviteUserViewModel model)
        {
            ValidationResult validationResults = await this.inviteUserValidator
                                                 .ValidateAsync(model, CancellationToken.None).ConfigureAwait(false);

            validationResults.AddToModelState(this.ModelState, null);

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            IExecutionResult result = await this.commandBus
                                      .PublishAsync(this.mapper.Map <InviteUserCommand>(model), CancellationToken.None)
                                      .ConfigureAwait(false);

            if (!result.IsSuccess)
            {
                return(this.BadRequest());
            }

            return(this.Ok(await this.GetInvitationByRecipient(model.Id, model.Email, CancellationToken.None)
                           .ConfigureAwait(false)));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> AddLocation([CustomizeValidator(Skip = true)][FromBody]
                                                      AddLocationViewModel model)
        {
            ValidationResult validationResults = await this.addLocationValidator
                                                 .ValidateAsync(model, CancellationToken.None).ConfigureAwait(false);

            validationResults.AddToModelState(this.ModelState, null);

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            IExecutionResult result = await this.commandBus
                                      .PublishAsync(this.mapper.Map <AddLocationCommand>(model), CancellationToken.None).ConfigureAwait(false);

            if (!result.IsSuccess)
            {
                return(this.BadRequest());
            }

            Location location = await this.queryProcessor
                                .ProcessAsync(new LocationByName(model.Name), CancellationToken.None).ConfigureAwait(false);

            return(this.Ok(location));
        }
        public async Task <IActionResult> MembershipRequest([FromBody] int groupId)
        {
            Group group = await this._groupService.Get(groupId);

            if (group == null)
            {
                return(BadRequest());
            }

            User connectedUser = await this._userService.GetWithRequest(int.Parse(User.Identity.Name));

            if (connectedUser.ParticipantGroups.Any(pg => pg.Status == Status.Accepted))
            {
                return(BadRequest("A user can't send membership request if he is already accepted in a group !"));
            }
            if (connectedUser.ParticipantGroups.Any(pg => pg.BelongingGroupId == groupId && pg.Status == Status.Waiting))
            {
                return(BadRequest("A user can't send membership request if he is already in waiting in this group !"));
            }

            ValidationResult result = await this._groupService.MembershipRequest(groupId, connectedUser);

            if (result != null)
            {
                result.AddToModelState(ModelState, "MembershipRequest");
                return(this.BadRequest(this.ModelState));
            }

            return(Ok(true));
        }
        public async Task <IActionResult> Edit(GroupEdit groupEdit)
        {
            GroupEditValidator validator = new GroupEditValidator(this._groupService);
            ValidationResult   results   = await validator.ValidateAsync(groupEdit);

            results.AddToModelState(ModelState, "GroupEdit");

            if (!ModelState.IsValid)
            {
                return(BadRequest(this.ModelState));
            }

            int connectedUserId = int.Parse(User.Identity.Name);

            User connectedUser = await this._userService.GetWithRequest(connectedUserId);

            if (connectedUser.Role != Role.Admin && (connectedUser.Role == Role.Member && !connectedUser.ParticipantGroups.Any(pg => pg.IsCreator)))
            {
                return(BadRequest("You are not an admin or the creator of this group !"));
            }

            await this._groupService.Edit(groupEdit);

            return(Ok());
        }
 public ActionResult Create(Customer customer)
 {
     try
     {
         CustomerViewModelValidator validator = new CustomerViewModelValidator();
         ValidationResult           result    = validator.Validate(customer);
         if (result.IsValid)
         {
             //ViewBag.Name = model.Name;
             //ViewBag.Email = model.Email;
             var customerRepo = new CustomerRepository();
             customerRepo.Insert(customer);
             return(RedirectToAction("Index"));
         }
         else
         {
             result.AddToModelState(ModelState, null);
             return(View());
             //return RedirectToAction("Create");
         }
     }
     catch
     {
         return(RedirectToAction("Index"));
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Add ValidationResult to ModelState
 /// </summary>
 /// <param name="modelState"></param>
 /// <param name="validationResult"></param>
 public static void AddValidationResult(this ModelStateDictionary modelState, ValidationResult validationResult)
 {
     if (!validationResult.IsValid)
     {
         validationResult.AddToModelState(modelState, KEY);
     }
 }
Exemplo n.º 8
0
        public async Task <IActionResult> AddCharge([CustomizeValidator(Skip = true)][FromBody]
                                                    AddChargeViewModel model)
        {
            ValidationResult validationResults = await this.addChargeValidator
                                                 .ValidateAsync(model, CancellationToken.None).ConfigureAwait(false);

            validationResults.AddToModelState(this.ModelState, null);

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            AddChargeCommand command = this.mapper.Map <AddChargeCommand>(model);
            IExecutionResult result  =
                await this.commandBus.PublishAsync(command, CancellationToken.None).ConfigureAwait(false);

            if (!result.IsSuccess)
            {
                return(this.BadRequest());
            }

            Charge charge = await this.queryProcessor
                            .ProcessAsync(
                new ChargeById(command.AggregateId.Value.Replace("charge-", "",
                                                                 StringComparison.InvariantCultureIgnoreCase)), CancellationToken.None).ConfigureAwait(false);

            return(this.Ok(charge));
        }
 public override void OnException(ExceptionContext context)
 {
     if (context.Exception is ValidationException validationException)
     {
         var validationResult = new ValidationResult(validationException.Errors);
         validationResult.AddToModelState(context.ModelState, string.Empty);
         context.Result = new BadRequestObjectResult(context.ModelState);
     }
 }
Exemplo n.º 10
0
        protected virtual void Validate(IValidator validator, object instance, ModelStateDictionary modelState)
        {
            ValidationResult result = validator.Validate(instance);

            if (!result.IsValid)
            {
                // https://github.com/JeremySkinner/FluentValidation/blob/master/src/FluentValidation.WebApi/ValidationResultExtension.cs
                result.AddToModelState(modelState, null);
            }
        }
        public ActionResult Check(string control, DataModel model)
        {
            // Валидация только Fluent валидатором
            ModelState.Clear();

            Validator validator = new Validator();

            ValidationResult validationResults = validator.Validate(model);

            if (!validationResults.IsValid)
            {
                validationResults.AddToModelState(ModelState, null);
            }
            if (!ModelState.IsValid)
            {
                return(JavaScriptAlert(
                           "&nbsp;",
                           "<br clear='all'/><ul>" +
                           String.Join("\n",
                                       GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e))
                                       )
                           + "</ul>"));
            }

            var результатПроверки = Repository.Persons.CheckDateRange(model.PersonID, model.From, model.To);

            if (результатПроверки.Валидность == 0 || результатПроверки.От >= new DateTime(2050, 1, 1, 0, 0, 0, DateTimeKind.Utc))
            {
                return(JavaScriptAlert(
                           Kesco.Persons.Web.Localization.Resources.Validation_Card_ErrorDlg_Title,
                           Kesco.Persons.Web.Localization.Resources.Validation_Card_ErrorDlg_Message
                           ));
            }

            if (результатПроверки.От.Value == new DateTime(1980, 1, 1, 0, 0, 0, DateTimeKind.Utc))
            {
                результатПроверки.От = null;
            }

            if (результатПроверки.До.Value == new DateTime(2050, 1, 1, 0, 0, 0, DateTimeKind.Utc))
            {
                результатПроверки.До = null;
            }
            else
            {
                результатПроверки.До = результатПроверки.До.Value.AddDays(-1);              // До -> По
            }
            return(ReturnDialogValue(new {
                PersonID = результатПроверки.КодЛица,
                From = результатПроверки.От,
                To = результатПроверки.До
            }));
        }
 public override void OnException(ExceptionContext context)
 {
     if (context.Exception is ValidationException ex)
     {
         var validationResult = new ValidationResult(ex.Errors);
         validationResult.AddToModelState(context.ModelState, null);
         context.Result = new ViewResult {
             ViewData = new ViewDataDictionary(ModelMetadataProvider, context.ModelState)
         };
         context.ExceptionHandled = true;
     }
 }
        public async Task <IActionResult> Create(GroupByAdmin newGroupByAdmin)
        {
            GroupByAdminValidator validator = new GroupByAdminValidator(this._groupService);
            ValidationResult      results   = await validator.ValidateAsync(newGroupByAdmin);

            results.AddToModelState(ModelState, "GroupByAdmin");

            if (!ModelState.IsValid)
            {
                return(BadRequest(this.ModelState));
            }

            int groupId = await this._groupService.CreateByAdmin(newGroupByAdmin);

            return(Ok(newGroupByAdmin));
        }
Exemplo n.º 14
0
        public void OnException(ExceptionContext context)
        {
            switch (context.Exception)
            {
            case NotFoundException e:
                if (_environment.IsDevelopment())
                {
                    context.Result = new NotFoundObjectResult(e.Message);
                }
                else
                {
                    context.Result = new NotFoundResult();
                }

                break;

            case ValidationException e:
                var validationResult = new ValidationResult(e.Errors);
                validationResult.AddToModelState(context.ModelState, null);
                context.Result = new BadRequestObjectResult(context.ModelState);

                break;

            case Exception e:
                _logger.LogError(e, "Unknown exception thrown");

                if (_environment.IsProduction())
                {
                    context.Result =
                        new BadRequestObjectResult("An error occured. Check the logs.");
                }
                else
                {
                    context.Result = new BadRequestObjectResult(
                        new
                    {
                        Message =
                            "Unknown exception thrown. Check the logs.",
                        ExceptionMessage = e.Message
                    });
                }

                break;
            }
        }
        public async Task <IActionResult> Create(GroupByMember newGroupByMember)
        {
            GroupByMemberValidator validator = new GroupByMemberValidator(this._groupService);
            ValidationResult       results   = await validator.ValidateAsync(newGroupByMember);

            results.AddToModelState(ModelState, "NewGroupByMember");

            if (!ModelState.IsValid)
            {
                return(BadRequest(this.ModelState));
            }

            int  connectedUserId = int.Parse(User.Identity.Name);
            User connectedUser   = await this._userService.Get(int.Parse(User.Identity.Name));

            int groupId = await this._groupService.CreateByMember(newGroupByMember, connectedUser);

            return(Ok(groupId));
        }
        public async Task <IActionResult> Create(ChallengeCreate newChallenge)
        {
            ChallengeCreateValidator validator = new ChallengeCreateValidator(this._challengeService);
            ValidationResult         results   = await validator.ValidateAsync(newChallenge);

            results.AddToModelState(ModelState, "ChallengeCreate");

            if (!ModelState.IsValid)
            {
                return(BadRequest(this.ModelState));
            }

            int  connectedUserId = int.Parse(User.Identity.Name);
            User connectedUser   = await this._userService.Get(int.Parse(User.Identity.Name));

            int ChallengeId = await this._challengeService.Create(newChallenge, connectedUser);

            return(Ok(ChallengeId));
        }
Exemplo n.º 17
0
    public ActionResult Login([CustomizeValidator] LoginViewModel loginViewModel)
    {
        //ValidatorOptions.LanguageManager = new CustomLanguageManager();
        if (ModelState.IsValid)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", "zh", "CN"));

        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
        //ValidatorOptions.LanguageManager = new LanguageManager() {Culture = Thread.CurrentThread.CurrentCulture};
        ValidatorOptions.LanguageManager.Enabled = true;
        ValidatorOptions.ResourceProviderType    = typeof(MyResources);

        var validator           = new LoginViewModelValidator();
        ValidationResult result = validator.Validate(loginViewModel);

        result.AddToModelState(ModelState, null);

        return(View(loginViewModel));
    }
Exemplo n.º 18
0
        public void OnException(ExceptionContext context)
        {
            switch (context.Exception)
            {
            case NotFoundException exception:
                if (_environment.IsDevelopment())
                {
                    context.Result = new NotFoundObjectResult(exception);
                }
                else
                {
                    context.Result = new NotFoundResult();
                }
                break;

            case ValidationException exception:
                var validationResult = new ValidationResult(exception.Errors);
                validationResult.AddToModelState(context.ModelState, null);
                context.Result = new BadRequestObjectResult(context.ModelState);
                break;
            }
        }
Exemplo n.º 19
0
        public async Task <IActionResult> Login([FromBody] LoginDTO data)
        {
            LoginDTOValidator validator = new LoginDTOValidator();
            ValidationResult  results   = await validator.ValidateAsync(data);

            results.AddToModelState(ModelState, "LoginDTO");

            if (!ModelState.IsValid)
            {
                return(BadRequest(this.ModelState));
            }

            var user = await _authService.Authenticate(data.Email, data.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            User userUpdate = await _userService.UpdateToken(user);

            return(Ok(new{ token = userUpdate.Token }));
        }
Exemplo n.º 20
0
        public async Task <IActionResult> DeleteCar([CustomizeValidator(Skip = true)][FromBody]
                                                    DeleteCarViewModel model)
        {
            ValidationResult validationResults = await this.deleteCarValidator
                                                 .ValidateAsync(model, CancellationToken.None).ConfigureAwait(false);

            validationResults.AddToModelState(this.ModelState, null);

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            IExecutionResult result = await this.commandBus
                                      .PublishAsync(this.mapper.Map <DeleteCarCommand>(model), CancellationToken.None).ConfigureAwait(false);

            if (!result.IsSuccess)
            {
                return(this.BadRequest());
            }

            return(this.Ok());
        }
Exemplo n.º 21
0
        public async Task <IActionResult> RejectInvitation([CustomizeValidator(Skip = true)][FromBody]
                                                           RejectInvitationViewModel model)
        {
            ValidationResult validationResults = await this.rejectInvitationValidator
                                                 .ValidateAsync(model ?? new RejectInvitationViewModel(), CancellationToken.None).ConfigureAwait(false);

            validationResults.AddToModelState(this.ModelState, null);

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            Location location = await this.GetLocationByInvitationCode(model?.Code.ToString(), CancellationToken.None)
                                .ConfigureAwait(false);

            if (location == null)
            {
                this.ModelState.AddModelError("Code", LocationResources.InvitationNotFound);
                return(this.BadRequest(this.ModelState));
            }

            IExecutionResult result = await this.commandBus
                                      .PublishAsync(
                new RejectInvitationCommand(LocationId.With(Guid.Parse(location.Id)),
                                            InvitationId.With(Guid.Parse(model.Code.ToString()))), CancellationToken.None)
                                      .ConfigureAwait(false);

            if (!result.IsSuccess)
            {
                return(this.BadRequest());
            }

            return(this.Ok(await this.GetInvitationByCode(location.Id, model.Code.ToString(), CancellationToken.None)
                           .ConfigureAwait(false)));
        }
Exemplo n.º 22
0
 public static BadRequestObjectResult BadRequestFromValidationError(this ControllerBase controller, ValidationResult validationError)
 {
     validationError.AddToModelState(controller.ModelState, null);
     return(controller.BadRequest(controller.ModelState));
 }
Exemplo n.º 23
0
        /// <summary>
        /// Сохраняет карточку физ лица.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public ActionResult Save(string control, PersonModel model)
        {
            PersonModelValidator validator = new PersonModelValidator(model.EditCard || !model.Card.PersonID.HasValue || model.Card.PersonID.Value == 0);

            ValidationResult validationResults = validator.Validate(model);

            if (!validationResults.IsValid)
            {
                validationResults.AddToModelState(ModelState, null);
            }
            ModelState["Model.PersonTypes.PersonThemeID"].Errors.Clear();
            if (!ModelState.IsValid)
            {
                return(JavaScriptAlert(
                           Kesco.Persons.Web.Localization.Resources.Validation_ErrorDlg_Title,
                           Kesco.Persons.Web.Localization.Resources.Validation_Person_ErrorDlg_Message
                           + "<br clear='all'/><ul>" +
                           String.Join("\n",
                                       GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e))
                                       )
                           + "</ul>"));
            }

            // если указан идентификатор лица, то операция - создать/редактировать карточку
            // иначе вернуть карточку
            bool saveEmplsAndThemes = (model.Card.PersonID == null || model.Card.PersonID.Value == 0);

            try
            {
                //  Транслитерация
                if (!StringExtensions.HasOnlyLatinChars(model.Card.LastNameLat))
                {
                    model.Card.LastNameLat = Repository.Persons.TraslitSentence(StringExtensions.Coalesco(model.Card.LastNameLat, model.Card.LastNameRus));
                }
                if (!StringExtensions.HasOnlyLatinChars(model.Card.FirstNameLat))
                {
                    model.Card.FirstNameLat = Repository.Persons.TraslitSentence(StringExtensions.Coalesco(model.Card.FirstNameLat, model.Card.FirstNameRus));
                }
                if (!StringExtensions.HasOnlyLatinChars(model.Card.MiddleNameLat))
                {
                    model.Card.MiddleNameLat = Repository.Persons.TraslitSentence(StringExtensions.Coalesco(model.Card.MiddleNameLat, model.Card.MiddleNameRus));
                }

                List <FormatRegistration> FormatRegistrations = Repository.FormatRegistrations.GetAllFormats();
                if (!FormatRegistrations.Exists(f => f.ID == model.Card.TerritoryID))
                {
                    model.Card.INN = model.Card.OKPO = "";
                }

                var card = new IndividualCardForSave
                {
                    Check = model.Confirmed || (
                        model.EditCard
                                ? (model.Card.ID.HasValue && model.Card.ID.Value != 0)
                                : (model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0)
                        ),
                    NewID  = 0,
                    WhatDo = model.EditCard
                            ? ((model.Card.ID.HasValue && model.Card.ID.Value != 0)
                                ? SaveAction.едактироватьКарточку
                                : SaveAction.СоздатьКарточку)
                            : ((model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0)
                                ? SaveAction.едактироватьЛицо
                                : SaveAction.СоздатьЛицо),
                    ДатаРождения = model.Card.Birthday,
                    От           = model.Card.From ?? new DateTime(1980, 1, 1),
                    До           = (model.Card.To ?? new DateTime(2049, 12, 31)).AddDays(1),

                    ИмяЛат           = model.Card.FirstNameLat ?? String.Empty,
                    ИмяРус           = model.Card.FirstNameRus ?? String.Empty,
                    ИНН              = model.Card.INN ?? String.Empty,
                    Кличка           = model.Card.Nickname ?? String.Empty,
                    КодБизнесПроекта = model.Card.BusinessProjectID,
                    КодКарточки      = model.Card.ID ?? 0,
                    КодЛица          = model.Card.PersonID ?? 0,
                    КодОргПравФормы  = model.Card.IncorporationFormID,
                    КодТерритории    = model.Card.TerritoryID,
                    ОГРН             = model.Card.OGRN ?? String.Empty,
                    ОКПО             = model.Card.OKPO ?? String.Empty,
                    ОтчествоЛат      = model.Card.MiddleNameLat ?? String.Empty,
                    ОтчествоРус      = model.Card.MiddleNameRus ?? String.Empty,
                    Пол              = model.Card.Sex ?? 'М',
                    Примечание       = model.Card.Comment ?? String.Empty,
                    Проверено        = model.Card.Verified,
                    ФамилияЛат       = model.Card.LastNameLat ?? String.Empty,
                    ФамилияРус       = model.Card.LastNameRus ?? String.Empty,

                    ОКОНХ               = String.Empty,
                    ОКВЭД               = String.Empty,
                    КПП                 = String.Empty,
                    КодЖД               = String.Empty,
                    АдресЮридический    = model.Card.AddressLegal ?? String.Empty,
                    АдресЮридическийЛат = model.Card.AddressLegalLat ?? String.Empty,
                };

                if (model.Card.IncorporationFormID.HasValue)
                {
                    card.ОКОНХ = model.Card.OKONH ?? String.Empty;
                    card.ОКВЭД = model.Card.OKVED ?? String.Empty;
                    card.КПП   = model.Card.KPP ?? String.Empty;
                    card.КодЖД = model.Card.RwID ?? String.Empty;
                }

                // если редактируем реквизиты,
                // то всегда обновляем лицо
                if (model.EditCard)
                {
                    SaveAction action = card.WhatDo;
                    card.WhatDo = SaveAction.едактироватьЛицо;
                    Repository.Persons.TryToSaveIndividual(card);
                    card.WhatDo = action;
                }
                model.Card.PersonID = Repository.Persons.TryToSaveIndividual(card);
            }
            catch (SavePersonException ex)
            {
                string script2 = String.Format(@"(function() {{
					var duplicates = {3};
					var callbackUrl = encodeURIComponent('{0}');
					var url = '{1}&callbackUrl={{0}}';
					url = $.validator.format(url, callbackUrl);
					openPopupWindow(url, {{
							type: 'POST',
							Duplicates: duplicates
						}}, function (result) {{
							
							ViewModel.Model.Confirmed(false);
							if ($.isArray(result)) {{
								var person = result[0];
								if (person.value == {2}) {{ // если value == PersonID, создаём/сохраняем лицо
									ViewModel.Model.Confirmed(true);
									ViewModel.save();
								}} else {{ // иначе закрываем и открываем похожее лицо
									closeDialogAndReturnValue(JSON.stringify(result));
								}}

							}}
						}}, 'wnd_Duplicates', 670, 400);
				}})()"                ,
                                               Url.FullPathAction("DialogResult", "Default"),
                                               Url.Action("Index", "NaturalDuplicates", new { id = model.Card.PersonID ?? 0, t = 1 }),
                                               model.Card.PersonID ?? 0,
                                               Kesco.Web.Mvc.Json.Serialize(
                                                   ex.Issues
                                                   .GroupBy(issue => issue.PersonID)
                                                   .Select(gr => new
                {
                    PersonID = gr.Key,
                    Nickname = gr.First().Nickname,
                    Issues   = gr.Select(i => new
                    {
                        Field   = i.Field,
                        Granted = i.Granted,
                        R       = i.R,
                        Value   = i.Value
                    }).ToList()
                })
                                                   , true
                                                   )
                                               );

                return(JavaScript(script2));
            }

            // Создание связи между лицом-работником и работадателем
            if (model.EmployerId.HasValue && model.Card.PersonID.HasValue)
            {
                try
                {
                    PersonLinkAccessor.PersonLinkForSave sqlParams = new PersonLinkAccessor.PersonLinkForSave();
                    sqlParams.WhatDo          = 0;
                    sqlParams.КодЛицаРодителя = model.EmployerId.Value;
                    sqlParams.КодЛицаПотомка  = model.Card.PersonID.Value;
                    sqlParams.КодТипаСвязиЛиц = 1;
                    sqlParams.Параметр        = 0;
                    Repository.Links.MergePersonLink(sqlParams);
                }
                catch (Exception ex)
                {
                    Logger.WriteEx(new DetailedException("Ошибка создания связи между лицом-работником и работадателем", ex));
                }
            }

            string errMsg = String.Empty;

            if (saveEmplsAndThemes)
            {
                try
                {
                    var responsibleEmployeesIDs = model.ResponsibleEmployees.Select(employee => Convert.ToInt32(employee.ID)).ToList();
                    Repository.Persons.MergeResponsibleEmployees(model.Card.PersonID.Value, String.Join(",", responsibleEmployeesIDs));
                    //Repository.Persons.AssignResponsibleEmployee(
                    //        model.Card.PersonID.Value,
                    //        UserContext.EmployeeInfo.ID
                    //    );
                }
                catch (Exception ex)
                {
                    errMsg = String.Format(
                        Resources.Resources.Persons_Natural_SaveErrorWhileSavingResps,
                        ex.Message
                        );
                    Logger.WriteEx(new DetailedException(errMsg, ex));
                }
                try
                {
                    Repository.Persons.SavePersonTypes(
                        model.Card.PersonID.Value,
                        String.Join(",", model.PersonTypes.PersonTypeIDs)
                        );
                }
                catch (Exception ex2)
                {
                    var errMsg2 = String.Format(
                        Resources.Resources.Persons_Natural_SaveErrorWhileSavingPersonTypes,
                        ex2.Message
                        );
                    Logger.WriteEx(new DetailedException(errMsg2, ex2));
                    if (errMsg != String.Empty)
                    {
                        errMsg += "\n\n";
                    }
                    errMsg += errMsg2;
                }
            }


            var parametrs = Kesco.Web.Mvc.Json.Serialize(new
            {
                value = model.Card.PersonID,
                label = model.Card.Nickname
            }, true);

            string sectionID = HttpContext.Request["sectionId"] ??
                               HttpUtility.ParseQueryString(HttpContext.Request.UrlReferrer.ToString()).Get("sectionId");

            if (sectionID != null)
            {
                var values = JsonConvert.DeserializeObject <JObject>(parametrs);
                values.Add("sectionId", sectionID);
                parametrs = Kesco.Web.Mvc.Json.Serialize(values, true);
            }

            string script = String.Format(@"
					(function() {{
						var result = {0};
						var errMsg = {1};
						if (errMsg) {{
							alert(errMsg);
						}}
						returnResult(result);
					}})();"                    ,
                                          parametrs, Kesco.Web.Mvc.Json.Serialize(errMsg)
                                          );

            return(JavaScript(script));
        }
Exemplo n.º 24
0
		public ActionResult Save(string control, Requisites model)
		{
			string script = String.Empty;

			RequisitesValidator validator = new RequisitesValidator();

			ValidationResult validationResults = validator.Validate(model);
			if (!validationResults.IsValid) {
				validationResults.AddToModelState(ModelState, null);
			}
			if (!ModelState.IsValid) {
				return JavaScriptAlert(
					Kesco.Persons.Web.Localization.Resources.Validation_ErrorDlg_Title,
					Kesco.Persons.Web.Localization.Resources.Validation_Person_ErrorDlg_Message
						+"<br clear='all'/><ul>"+
						String.Join("\n", 
								GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e))
							)
						+"</ul>");
			}

			// если указан идентификатор лица, то операция - создать/редактировать карточку
			if (model.PersonID.HasValue && model.PersonID.Value != 0) {
				Person person = Repository.Persons.GetInstance(model.PersonID.Value);

				if (person == null)
					throw new ApplicationException(
						String.Format(Kesco.Persons.Web.Localization.Resources
							.ViewModel_Exception_JuridicalPerson_Requisites_PersonNotFound,
						model.PersonID
					));

				try {
					var card = new JuridicalCardForSave {
						NewID = 0,
						WhatDo = (model.ID != 0) ? SaveAction.РедактироватьКарточку : SaveAction.СоздатьКарточку,
						//Check = control == "confirmed", // TODO: Переделать
                        Check = (model.OperationTypeId != 0),
						КодЛица = person.ID,
						Кличка = person.Nickname ?? String.Empty,
						КодБизнесПроекта = person.BusinessProjectID,
						КодТерритории = person.TerritoryID,
						ГосОрганизация = person.IsStateOrganization ? 1 : 0,
						БИК = person.BIK ?? String.Empty,
						ИНН = person.INN ?? String.Empty,
						ОГРН = person.OGRN ?? String.Empty,
						ОКПО = person.OKPO ?? String.Empty,
						КорСчет = person.LoroConto ?? String.Empty,
						БИКРКЦ = person.BIKRKC ?? String.Empty,
						SWIFT = person.SWIFT ?? String.Empty,
						Примечание = person.Comment ?? String.Empty,
						Проверено = person.Verified,

						КодКарточки = model.ID,
						От = model.From ?? new DateTime(1980, 1, 1),
						До = (model.To ?? new DateTime(2049, 12, 31)).AddDays(1),

						КраткоеНазваниеЛат = model.ShortNameLat ?? String.Empty,
						КраткоеНазваниеРус = model.ShortNameRus ?? String.Empty,
						КраткоеНазваниеРусРП = model.ShortNameRusGenitive ?? String.Empty,
						КодЖД = model.RwID ?? String.Empty,
						АдресЮридический = model.AddressLegal ?? String.Empty,
						АдресЮридическийЛат = model.AddressLegalLat ?? String.Empty,

						ПолноеНазвание = String.Empty,
						ОКОНХ = String.Empty,
						ОКВЭД = String.Empty,
						КПП = String.Empty
					};

					if (person.TerritoryID == JuridicalCardForSave.Russia) {
						card.КодОргПравФормы = model.IncorporationFormID;
						card.ПолноеНазвание = model.FullName ?? String.Empty;
						card.ОКОНХ = model.OKONH ?? String.Empty;
						card.ОКВЭД = model.OKVED ?? String.Empty;
						card.КПП = model.KPP ?? String.Empty;
					}

					Repository.Persons.TryToSaveJuridical(card);
				} catch (SavePersonException ex) {
					string script2 = String.Format(@"(function() {{
					var duplicates = {3};
					var callbackUrl = encodeURIComponent('{0}');
					var url = '{1}&callbackUrl={{0}}';
					url = $.validator.format(url, callbackUrl);
					openPopupWindow(url, {{
							type: 'POST',
							Duplicates: duplicates
						}}, function (result) {{
							
							ViewModel.Confirmed(false);
							if ($.isArray(result)) {{
								var person = result[0];
								if (person.value == {2}) {{ // если value == PersonID, создаём/сохраняем лицо
									ViewModel.Confirmed(true);
									ViewModel.save();
								}} else {{ // иначе закрываем и открываем похожее лицо
									//closeDialogAndReturnValue(JSON.stringify(result));
								}}

							}}
						}}, 'wnd_Duplicates', 670, 400);
				}})()",
						Url.FullPathAction("DialogResult", "Default"),
						Url.Action("Index", "NaturalDuplicates", new { id = model.PersonID, t = 1 }),
						model.PersonID,
						Kesco.Web.Mvc.Json.Serialize(
							ex.Issues
								.GroupBy(issue => issue.PersonID)
								.Select(gr => new {
									PersonID = gr.Key,
									Nickname = gr.First().Nickname,
									Issues = gr.Select(i => new {
										Field = i.Field,
										Granted = i.Granted,
										R = i.R,
										Value = i.Value
									}).ToList()
								})
							, true
						)
					);

					return JavaScript(script2);
				}
			}

			// иначе вернуть карточку
			return ReturnDialogValue(model);
		}
        public ActionResult Save(string control, string docview, DataModel model)
        {
            // Валидация только Fluent валидатором
            ModelState.Clear();

            ContactsValidator validator = new ContactsValidator();

            ValidationResult validationResults = validator.Validate(model.Contact);

            if (!validationResults.IsValid)
            {
                validationResults.AddToModelState(ModelState, null);
            }
            if (!ModelState.IsValid)
            {
                return(JavaScriptAlert(
                           Kesco.Persons.Web.Localization.Resources.Validation_Contact_ErrorDlg_Title,
                           Kesco.Persons.Web.Localization.Resources.Validation_Contact_ErrorDlg_Message
                           + "<br clear='all'/><ul>" +
                           String.Join("\n",
                                       GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e))
                                       )
                           + "</ul>"));
            }

            model.Contact.ChangedBy   = UserContext.EmployeeInfo.ID;
            model.Contact.ChangedDate = DateTime.UtcNow;

            var contact = new Kesco.Persons.ObjectModel.Contact
            {
                ID            = model.Contact.ID,
                PersonID      = model.Contact.PersonLinkID.HasValue ? ((int?)null) : model.Contact.PersonID,
                PersonLinkID  = model.Contact.PersonLinkID,
                ContactTypeID = model.Contact.ContactTypeID.Value,
                ContactText   = model.Contact.ContactText ?? string.Empty,
                ContactTextRL = model.Contact.ContactTextRL ?? string.Empty,

                CountryID   = 0,
                Zip         = string.Empty,
                Region      = string.Empty,
                CityName    = string.Empty,
                CityNameRus = string.Empty,
                Address     = string.Empty,

                CountryPhoneCode       = string.Empty,
                CityPhoneCode          = string.Empty,
                PhoneNumber            = string.Empty,
                PhoneNumberAdd         = string.Empty,
                PhoneNumberCorporative = string.Empty,

                OtherContact = String.Empty,
                Comment      = model.Contact.Comment ?? string.Empty,
            };

            if (model.Contact.ContactTypeID.Value < 20)
            {
                contact.CountryID   = model.Contact.CountryID ?? 0;
                contact.Zip         = model.Contact.Zip ?? string.Empty;
                contact.Region      = model.Contact.Region ?? string.Empty;
                contact.CityName    = model.Contact.CityName ?? string.Empty;
                contact.CityNameRus = model.Contact.CityNameRus ?? string.Empty;
                contact.Address     = model.Contact.Address ?? string.Empty;
            }

            if (model.Contact.ContactTypeID.Value >= 20 && model.Contact.ContactTypeID.Value < 40)
            {
                contact.CountryPhoneCode       = model.Contact.CountryPhoneCode ?? string.Empty;
                contact.CityPhoneCode          = model.Contact.CityPhoneCode ?? string.Empty;
                contact.PhoneNumber            = model.Contact.PhoneNumber ?? string.Empty;
                contact.PhoneNumberAdd         = model.Contact.PhoneNumberAdd ?? string.Empty;
                contact.PhoneNumberCorporative = model.Contact.PhoneNumberCorporative ?? string.Empty;
            }

            if (model.Contact.ContactTypeID.Value >= 40 && model.Contact.ContactTypeID.Value < 54)
            {
                contact.OtherContact = model.Contact.ContactText ?? string.Empty;
            }

            if (model.Contact.ContactTypeID.Value == 54)
            {
                contact.OtherContact = model.Contact.OtherContact ?? string.Empty;
            }
            if (model.Contact.ID != 0)
            {
                Repository.Contacts.Save(contact);
            }
            else
            {
                model.Contact.ID = Convert.ToInt32(Repository.Contacts.CreateContact(contact));
            }
            if ((docview ?? String.Empty) == "yes")
            {
                return(DialogPageReturn("{0}{1}{2}".FormatWith(
                                            model.Contact.ID,
                                            "\u001F",
                                            StringExtensions.Coalesco(model.Contact.ContactText, model.Contact.OtherContact)
                                            )));
            }
            return(ReturnDialogValue(model.Contact));
        }
Exemplo n.º 26
0
        public ActionResult Save(string control, PersonModel model)
        {
            PersonModelValidator validator = new PersonModelValidator(model.Card.PersonID == null || model.Card.PersonID.Value == 0);

            ValidationResult validationResults = validator.Validate(model);

            if (!validationResults.IsValid)
            {
                validationResults.AddToModelState(ModelState, null);
            }
            ModelState["Model.PersonTypes.PersonThemeID"].Errors.Clear();
            if (!ModelState.IsValid)
            {
                return(JavaScriptAlert(
                           Kesco.Persons.Web.Localization.Resources.Validation_ErrorDlg_Title,
                           Kesco.Persons.Web.Localization.Resources.Validation_Person_ErrorDlg_Message

                           + "<br clear='all'/><ul>" +
                           String.Join("\n",
                                       GetModelErrorMessages().Select(e => String.Format("<li>{0}</li>", e))
                                       )
                           + "</ul>"));
            }

            List <FormatRegistration> FormatRegistrations = Repository.FormatRegistrations.GetAllFormats();

            if (!FormatRegistrations.Exists(f => f.ID == model.Card.TerritoryID))
            {
                model.Card.INN = model.Card.OKPO = "";
            }

            // если указан идентификатор лица, то операция - редактировать карточку
            // иначе вернуть карточку
            bool saveEmplsAndThemes = (model.Card.PersonID == null || model.Card.PersonID.Value == 0);

            try {
                model.Card.PersonID = Repository.Persons.TryToSaveJuridical(new JuridicalCardForSave {
                    NewID  = 0,
                    WhatDo = (model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0)
                                                ? SaveAction.едактироватьЛицо
                                                : SaveAction.СоздатьЛицо,
                    Check            = model.Confirmed || (model.Card.PersonID.HasValue && model.Card.PersonID.Value != 0),
                    КодЛица          = model.Card.PersonID ?? 0,
                    КодКарточки      = model.Card.ID ?? 0,
                    Кличка           = model.Card.Nickname ?? String.Empty,
                    КодБизнесПроекта = model.Card.BusinessProjectID,
                    КодТерритории    = model.Card.TerritoryID,
                    ГосОрганизация   = model.Card.IsStateOrganization ? 1 : 0,
                    БИК        = model.Card.BIK ?? String.Empty,
                    ИНН        = model.Card.INN ?? String.Empty,
                    ОГРН       = model.Card.OGRN ?? String.Empty,
                    ОКПО       = model.Card.OKPO ?? String.Empty,
                    КорСчет    = model.Card.LoroConto ?? String.Empty,
                    БИКРКЦ     = model.Card.BIKRKC ?? String.Empty,
                    SWIFT      = model.Card.SWIFT ?? String.Empty,
                    Примечание = model.Card.Comment ?? String.Empty,
                    Проверено  = model.Card.Verified,

                    От = model.Card.Requisites.From ?? new DateTime(1980, 1, 1),
                    До = (model.Card.Requisites.To ?? new DateTime(2049, 12, 31)).AddDays(1),
                    КодОргПравФормы      = model.Card.Requisites.IncorporationFormID,
                    КраткоеНазваниеЛат   = model.Card.Requisites.ShortNameLat ?? String.Empty,
                    КраткоеНазваниеРус   = model.Card.Requisites.ShortNameRus ?? String.Empty,
                    КраткоеНазваниеРусРП = model.Card.Requisites.ShortNameRusGenitive ?? String.Empty,
                    ПолноеНазвание       = model.Card.Requisites.FullName ?? String.Empty,
                    ОКОНХ               = model.Card.Requisites.OKONH ?? String.Empty,
                    ОКВЭД               = model.Card.Requisites.OKVED ?? String.Empty,
                    КПП                 = model.Card.Requisites.KPP ?? String.Empty,
                    КодЖД               = model.Card.Requisites.RwID ?? String.Empty,
                    АдресЮридический    = model.Card.Requisites.AddressLegal ?? String.Empty,
                    АдресЮридическийЛат = model.Card.Requisites.AddressLegalLat ?? String.Empty
                });
            } catch (System.Data.SqlClient.SqlException ex) {
            }
            catch (SavePersonException ex) {
                string script2 = String.Format(@"(function() {{
					var duplicates = {3};
					var callbackUrl = encodeURIComponent('{0}');
					var url = '{1}&callbackUrl={{0}}';
					url = $.validator.format(url, callbackUrl);
					openPopupWindow(url, {{
							type: 'POST',
							Duplicates: duplicates
						}}, function (result) {{
							
							ViewModel.Model.Confirmed(false);
							if ($.isArray(result)) {{
								var person = result[0];
								if (person.value == {2}) {{ // если value == PersonID, создаём/сохраняем лицо
									ViewModel.Model.Confirmed(true);
									ViewModel.save();
								}} else {{ // иначе закрываем и открываем похожее лицо
									closeDialogAndReturnValue(JSON.stringify(result));
								}}
								
							}}
						}}, 'wnd_Duplicates', 670, 400);
				}})()"                ,
                                               Url.FullPathAction("DialogResult", "Default"),
                                               Url.Action("Index", "NaturalDuplicates", new { id = model.Card.PersonID ?? 0, t = 1 }),
                                               model.Card.PersonID ?? 0,
                                               Kesco.Web.Mvc.Json.Serialize(
                                                   ex.Issues
                                                   .GroupBy(issue => issue.PersonID)
                                                   .Select(gr => new {
                    PersonID = gr.Key,
                    Nickname = gr.First().Nickname,
                    Issues   = gr.Select(i => new {
                        Field   = i.Field,
                        Granted = i.Granted,
                        R       = i.R,
                        Value   = i.Value
                    }).ToList()
                })
                                                   , true
                                                   )
                                               );

                return(JavaScript(script2));
            }

            string errMsg = String.Empty;

            if (saveEmplsAndThemes)
            {
                try {
                    var responsibleEmployeesIDs = model.ResponsibleEmployees.Select(employee => Convert.ToInt32(employee.ID)).ToList();
                    Repository.Persons.MergeResponsibleEmployees(model.Card.PersonID.Value, String.Join(",", responsibleEmployeesIDs));
                    //Repository.Persons.AssignResponsibleEmployee(
                    //        model.Card.PersonID.Value,
                    //        UserContext.EmployeeInfo.ID
                    //    );
                } catch (Exception ex) {
                    errMsg = String.Format(
                        Resources.Resources.Persons_Natural_SaveErrorWhileSavingResps,
                        ex.Message
                        );
                    Logger.WriteEx(new DetailedException(errMsg, ex));
                }
                try {
                    Repository.Persons.SavePersonTypes(
                        model.Card.PersonID.Value,
                        String.Join(",", model.PersonTypes.PersonTypeIDs)
                        );
                } catch (Exception ex2) {
                    var errMsg2 = String.Format(
                        Resources.Resources.Persons_Natural_SaveErrorWhileSavingPersonTypes,
                        ex2.Message
                        );
                    Logger.WriteEx(new DetailedException(errMsg2, ex2));
                    if (errMsg != String.Empty)
                    {
                        errMsg += "\n\n";
                    }
                    errMsg += errMsg2;
                }
            }
            string sectionID = HttpContext.Request["sectionId"] ??
                               HttpUtility.ParseQueryString(HttpContext.Request.UrlReferrer.ToString()).Get("sectionId");
            string script = String.Format(@"
					(function() {{
						var result = {0};
						var errMsg = {1};
						if (errMsg) {{
							alert(errMsg);
						}}
						returnResult(result);
					}})();"                    ,
                                          Kesco.Web.Mvc.Json.Serialize(new {
                value     = model.Card.PersonID,
                label     = model.Card.Nickname,
                sectionId = sectionID
            }, true),
                                          Kesco.Web.Mvc.Json.Serialize(errMsg)
                                          );

            return(JavaScript(script));
        }