public bool Save(ITransaction transaction = null, List <Guid> saveFlags = null) { if (!isEditable) { throw new System.Data.ReadOnlyException("Attempt to call Save on a Read Only Data Object"); } PreValidate(); Validate(isInsert ? Validator.SaveModes.Insert : Validator.SaveModes.Update, saveFlags); if (Errors.Any()) { return(false); } ITransaction localTransaction = transaction == null?SQLProviderFactory.GenerateTransaction() : transaction; try { if (!PreSave(localTransaction)) { return(false); } if (!(isInsert ? SaveInsert(localTransaction) : SaveUpdate(localTransaction))) { return(false); } if (!PostSave(localTransaction)) { return(false); } isInsert = false; foreach (Schema.Field field in Schema.Schema.GetSchemaObject(GetType()).GetFields()) { originalValues[field.FieldName] = field.GetValue(this); } if (transaction == null) { localTransaction.Commit(); } } finally { if (transaction == null && localTransaction.IsActive) { localTransaction.Rollback(); } } return(true); }
/// <summary>Adds an error to the Errors list if it doesn't already contain it.</summary> public void AddError(DisplayError error) { if (!Errors.Any(e => e.Name == error.Name)) { Errors.Add(error); } }
private void SaveProject() { Base.WPF.Helpers.PushTextBoxChanges(); if (Errors.Any()) { throw new InvalidDataException(Errors.ToString("\n")); } if (string.IsNullOrEmpty(_projectViewModel.Project.FilePath)) { SaveAsProject(); } else { try { ProjectPersist.Save(_projectViewModel.Project); _projectViewModel.IsDirty = false; } catch (Exception e) { MainViewModel.Instance.Application.ShowMessage( string.Format(Properties.Resources.ErrorSavingProject, e.Message), Severity.Error); } } }
public void Enforce() { if (Errors.Any()) { throw this; } }
internal Result(IEnumerable <Error> errors, IEnumerable <ValidationIssue> validationIssues) { Errors = errors ?? new List <Error>(); ValidationIssues = validationIssues ?? new List <ValidationIssue>(); IsSuccessful = !Errors.Any() && !ValidationIssues.Any(); }
public override void MoveNext() { if (Validate()) { Profile = ClientProfileDTO.CreateFromView(this); var json = JsonConvert.SerializeObject(Profile); _settings.AddOrUpdateValue(GetType().Name, json); var indexId = null != IndexClientDTO?IndexClientDTO.Id.ToString() : string.Empty; if (MoveNextLabel == "SAVE" || null != Profile.PreventEnroll && Profile.PreventEnroll.Value) { Save(); } else { ShowViewModel <ClientEnrollmentViewModel>(new { clientinfo = ClientInfo, indexId = indexId }); } } else { if (null != Errors && Errors.Any()) { _dialogService.ShowErrorToast(Errors.First().Value); } } }
public async Task <IActionResult> Post(IFormFile upload) { var parserToUse = _fileParsers.FirstOrDefault(p => p.CanParseFile(upload.FileName)); if (parserToUse is null) { var validExtenstions = _fileParsers.Select(p => p.Extension); return(ValidationProblem($"File format not supported. Valid formats: {string.Join(", ", validExtenstions)}")); } var(Result, Errors) = parserToUse.ParseContent(upload.OpenReadStream()); if (Errors.Any()) { foreach (var e in Errors) { ModelState.AddModelError("ParsingError", e); } return(ValidationProblem(ModelState)); } await _repository.AddAsync(Result); await _repository.SaveChangesAsync(); return(Ok()); }
public void EnsureNoErrors() { if (Errors.Any()) { throw new Proto3RecognitionException(Errors); } }
protected virtual void AddErrorsToMessage() { AddToMessage( "".AppendLine("Errors:").AppendLine(RenderErrors).AppendLine(), !IsRenderPayloadOnly && Errors.Any(), Errors.Any()); }
private void SaveTesting() { if (Validate()) { if (null != ObsFinalTestResult) { ObsFinalTestResult.ResultGiven = SelectedResultGiven.ItemId; var isIndividial = _settings.GetValue("client.disco", false); EnableCoupleDiscordant = !isIndividial; ObsFinalTestResult.CoupleDiscordant = SelectedCoupleDiscordant.ItemId; ObsFinalTestResult.SelfTestOption = SelectedSelfTest.ItemId; ObsFinalTestResult.PnsDeclined = SelectedPnsDeclined.ItemId; ObsFinalTestResult.Remarks = Remarks; ObsFinalTestResult.ClientId = Client.Id; _testingService.SaveFinalTest(ObsFinalTestResult); _testingService.MarkEncounterCompleted(ObsFinalTestResult.EncounterId, AppUserId, true); _testingService.UpdateEncounterDate(ObsFinalTestResult.EncounterId, Client.Id); Encounter = _testingService.OpenEncounter(Encounter.Id); // _dialogService.ShowToast("Tests saved successfully"); GoBack(); } } else { if (null != Errors && Errors.Any()) { ShowErrorInfo(Errors.First().Value); } } }
private GenerationResults([CanBeNull] IEnumerable <SingleFileGenerationResult> singleFileGenerationResults, [CanBeNull] IEnumerable <Error> errors) { GeneratedFiles = singleFileGenerationResults ?? new SingleFileGenerationResult[0]; Errors = errors ?? new Error[0]; Success = !Errors.Any(); }
public void Submit(User submittingUser) { Guard.ArgumentNotNull(() => submittingUser, submittingUser); if (IsSubmitted) { throw new InvalidOperationException("IsSubmitted status must be false to transition to true"); } if (Errors != null && Errors.Any(e => e.ErrorLevel == ErrorLevel.Error)) { throw new InvalidOperationException("A member upload cannot be submitted when it contains errors"); } IsSubmitted = true; SubmittedByUser = submittingUser; SubmittedDate = SystemTime.UtcNow; foreach (ProducerSubmission producerSubmission in ProducerSubmissions) { producerSubmission.RegisteredProducer.SetCurrentSubmission(producerSubmission); } RaiseEvent(new SchemeMemberSubmissionEvent(this)); }
public bool IsValid() { if (ConfigurationId == Guid.Empty) { AddError("Configuração Inválida ou vazia"); } if (CurriculumId == Guid.Empty) { AddError("Curriculo Inválido ou não fornecido"); } if (StartDate == default(DateTime)) { AddError("Data de Início inválida"); } if (FinishDate != null) { if (FinishDate < StartDate) { AddError("A Data de Início deve ser anterior a data de término."); } if (FinishDate <= DateTime.Now) { AddError($"A data de término deve valer pelo menos um dia além da data cadastrada {DateTime.Now: dd/MM/yyyy}"); } } return(!Errors.Any()); }
public async Task <MorestachioDocumentResult> CreateAsync([NotNull] object data, CancellationToken token) { if (Errors.Any()) { throw new AggregateException("You cannot Create this Template as there are one or more Errors. See Inner Exception for more infos.", Errors.Select(e => e.GetException())).Flatten(); } var timeoutCancellation = new CancellationTokenSource(); if (ParserOptions.Timeout != TimeSpan.Zero) { timeoutCancellation.CancelAfter(ParserOptions.Timeout); var anyCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutCancellation.Token); token = anyCancellationToken.Token; } var sourceStream = ParserOptions.SourceFactory(); try { if (sourceStream == null) { throw new NullReferenceException("The created stream is null."); } if (!sourceStream.CanWrite) { throw new InvalidOperationException($"The stream '{sourceStream.GetType()}' is ReadOnly."); } using (var byteCounterStream = new ByteCounterStream(sourceStream, ParserOptions.Encoding, BufferSize, true)) { var context = new ContextObject(ParserOptions, "", null) { Value = data, CancellationToken = token }; await MorestachioDocument.ProcessItemsAndChildren(new[] { Document }, byteCounterStream, context, new ScopeData()); } if (timeoutCancellation.IsCancellationRequested) { sourceStream.Dispose(); throw new TimeoutException($"The requested timeout of '{ParserOptions.Timeout:g}' for report generation was reached."); } } catch (Exception ex) { //If there is any exception while generating the template we must dispose any data written to the stream as it will never returned and might //create a memory leak with this. This is also true for a timeout sourceStream?.Dispose(); throw; } return(new MorestachioDocumentResult() { Stream = sourceStream }); }
public virtual bool IsValid() { if (string.IsNullOrEmpty(FirstName)) { AddError("Nome é obrigatório"); } if (!Documents.Any(x => x.DocumentTypeId == EDocumentType.CPF)) { AddError($"CPF é Obrigatório"); } foreach (var phone in Phones) { if (!phone.ValidateBrazilianNumber()) { AddError($"Número {phone.ToString()} com formato inválido."); } } foreach (var address in Addresses) { if (!address.IsValid()) { AddError(address.Errors.ToArray()); } } if (BirthDate == default(DateTime)) { AddError($"Data de Nascimento inválida. Data Informada:{BirthDate.ToShortDateString()}"); } return(!Errors.Any()); }
public override void Validate() { if (string.IsNullOrEmpty(Name)) { AddError("Name is required!"); } if (string.IsNullOrEmpty(Login)) { AddError("Login is required!"); } if (string.IsNullOrEmpty(Password)) { AddError("Password is required!"); } if (CreationDate == DateTime.MinValue) { AddError("Creation date not defined"); } if (Errors.Any()) { throw new DomainException(Errors.Select(e => e.Error)); } }
List <int> FixMultiFileIndices(IEnumerable <int>?multiFileIndices, int targetCount) { if (Errors.Any()) { return new List <int> { 0 } } ; var indices = multiFileIndices?.ToList() ?? new List <int> { 0 }; if (indices.Count > 0) { int startCount = indices.Count; indices = indices.Where(i => i < targetCount).ToList(); if (startCount > indices.Count) { Warnings.Add("Multi-file index was higher than the number of targets."); } indices.Sort(); } if (indices.Count == 0 || indices[0] != 0) { indices.Insert(0, 0); } return(indices); }
/// <summary> /// Validate this instance. /// </summary> /// <returns>The validate.</returns> public bool Validate() { Errors = Rules.Where(v => !v.Check(Value)) .Select(v => v.ValidationMessage).ToList(); IsValid = !Errors.Any(); return(this.IsValid); }
/// <summary> /// Performs validation asynchronously based on provided rules and populates <see cref="Errors"/> if any errors occured /// </summary> /// <returns>A <see cref="Task{T}"/> including whether the operation succeeded.</returns> public async Task <bool> ValidateAsync() { _errors.Clear(); var results = new List <Task <bool> >(); foreach (var validation in _validations) { results.Add(validation.ValidateAsync(Value)); } var r = await Task.WhenAll(results); var errors = new List <string>(); for (var i = 0; i < _validations.Count; i++) { var isValid = r[i]; var validation = _validations[i]; if (!isValid) { errors.Add(validation.ValidationMessage); } } _errors.AddRange(errors); IsValid = !Errors.Any(); return(IsValid); }
private void SaveReferral() { if (Validate()) { ObsLinkage obs; if (null == ObsLinkage) { obs = ObsLinkage.CreateNew(ReferredTo, DatePromised, ParentViewModel.Encounter.Id); } else { obs = ObsLinkage; obs.ReferredTo = ReferredTo; obs.DatePromised = DatePromised; _linkageService.SaveLinkage(obs, ParentViewModel.Client.Id); } _linkageService.SaveLinkage(obs, ParentViewModel.Client.Id); _linkageService.MarkEncounterCompleted(ParentViewModel.Encounter.Id, ParentViewModel.AppUserId, true); ParentViewModel.Encounter = _linkageService.OpenEncounter(ParentViewModel.Encounter.Id); _dialogService.ShowToast("Referral info saved successfully"); ParentViewModel.GoBack(); } else { if (null != Errors && Errors.Any()) { ShowErrorInfo(Errors.First().Value); } } }
public int Execute(ErrorHandler errorHandler) { if (errorHandler == null) { throw new ArgumentNullException(nameof(errorHandler)); } if (HelpRequested) { return(0); } if (Errors.Any()) { return(errorHandler(Errors)); } if (_method == null) { throw new LogicException("No help was requested and no errors exist, but no target method exists."); } var result = _method.Invoke(_instance, _parameters); if (result is int exitCode) { return(exitCode); } return(0); }
public override IEnumerable <string> GetDynamicMemberNames() { if (ReferenceId.IsEmptyNullOrWhiteSpace()) { var msg = $"Although {GetType().Name}.{nameof(ReferenceId)} " + "is not required by RFC7807, we still want it!"; if (NoThrow) { Logger.LogWarning(() => msg); } else { throw new ArgumentException(msg, nameof(ReferenceId)); } } else { Properties.TryAdd("ReferenceId", ReferenceId); } if (Errors is not null && Errors.Any()) { Properties.TryAdd("Errors", Errors); } return(base.GetDynamicMemberNames()); }
public IValidatorResult Validate(T entity) { var ruleBuilders = _ruleBuilders?.Where(x => x.PropertiesValidations.Any()); foreach (var ruleBuilder in ruleBuilders) { if (ruleBuilder.IsValidRule(entity) && (ruleBuilder?.PropertiesValidations?.Any() ?? false)) { foreach (var propertieValidation in ruleBuilder.PropertiesValidations) { var propertyValues = propertieValidation.Compile(entity); foreach (var rule in propertieValidation.Rules) { rule.Validate(ruleBuilder.CustomNameField ?? propertyValues.FieldName, propertyValues.FieldValue); } } } } IsValid = !Errors.Any(); if (!IsValid) { //TODO: resolve that // throw new DomainException(Errors); } return(this); }
public void Add(string error) { if (Errors.Any(x => x == error)) { return; } Errors.Add(error); }
public virtual bool HasCriticalError() { // себя bool res = Errors.Any(e => e.Value.HasCriticalErrors); // детей return(res || ChildValidatedObjects.Any(o => o.Validator != null && o.Validator.HasCriticalError())); }
private void Extract() { ClearStatusMessage(); if (!ValidateInputValues()) { return; } var loadTask = LoadExtractedDataAsync(); ProgressDialog.Start(ParentForm, loadTask, false, SessionKey); if (loadTask.Exception != null) { NLogHandler.WriteErrorLog(this, loadTask.Exception, SessionKey); ShowWarningDialog(MsgErrSomethingError, "抽出"); return; } var result = loadTask.Result; if (!result) { ShowWarningDialog(MsgWngNotExistSearchData); return; } BaseContext.SetFunction01Enabled(false); BaseContext.SetFunction03Enabled(true); var loadPcaTask = LoadPcaMasterDataAsync(); ProgressDialog.Start(ParentForm, loadPcaTask, false, SessionKey); if (Errors.Any()) { BaseContext.SetFunction09Enabled(true); } if (loadPcaTask.Exception != null) { NLogHandler.WriteErrorLog(this, loadPcaTask.Exception, SessionKey); ShowWarningDialog(MsgErrSomethingError, "抽出"); return; } var loadResult = loadPcaTask.Result; if (!loadResult) { ShowWarningDialog(MsgErrSomethingError, "抽出"); return; } if (!TransferExtractedData()) { if (Errors.Any()) { BaseContext.SetFunction09Enabled(true); } ShowWarningDialog(MsgErrTransformErrorWithLog); return; } BaseContext.SetFunction04Enabled(true); }
public bool Validate() { Errors.Clear(); IEnumerable <string> errors = _validations.Where(x => x.Check(Value) == false).Select(x => x.ValidationMessage); Errors = errors.ToList(); IsValid = !Errors.Any(); return(this.IsValid); }
public bool Validate() { Errors.Clear(); var errors = _validations.Where(v => !v.Check(Value)).Select(v => v.ValidationMessage); Errors = errors.ToList(); IsValid = !Errors.Any(); return(IsValid); }
public bool IsValid() { if (string.IsNullOrEmpty(Description)) { AddError("Preencha uma informação para a descrição do curriculo escolar."); } return(!Errors.Any()); }
public void Handle(string key, string value) { if (Errors.Any(m => m.Key == key) || string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value)) { return; } Errors.Add(key, value); }