/// <summary> /// Does the validate. /// </summary> /// <param name="objectToValidate">The object to validate.</param> /// <param name="currentTarget">The current target.</param> /// <param name="key">The key.</param> /// <param name="validationResults">The validation results.</param> protected override void DoValidate(ModelBusReference objectToValidate, object currentTarget, string key, ValidationResults validationResults) { ModelElement currentElement = currentTarget as ModelElement; Debug.Assert(currentElement != null); if (!validationResults.IsValid) { return; } if (objectToValidate != null) { using (ModelBusReferenceResolver resolver = new ModelBusReferenceResolver()) { ModelElement referenced = resolver.Resolve(objectToValidate); // Check if we are not in the same model and we had visited this model before if (!currentElement.Store.Id.Equals(referenced.Store.Id) && Visited(referenced.Store.Id)) { this.LogValidationResult(validationResults, String.Format(CultureInfo.CurrentUICulture, this.MessageTemplate, ValidatorUtility.GetTargetName(currentTarget), objectToValidate.ElementDisplayName, objectToValidate.ModelDisplayName), currentTarget, key); return; } } // store the current model to compare with references // If referenced model == current model implies that we have a circular ref. alreadyVisited.Add(currentElement.Store.Id); } }
protected override string GetMessage(object objectToValidate, string key) { return(ValidatorUtility.ShowFormattedMessage( this.MessageTemplate, ValidatorUtility.GetTargetName(currentTarget), this.maxLength, base.GetMessage(objectToValidate, key))); }
public void ValidateFirstName_NullValue_ReturnsFalse(string name) { bool isValid = false; isValid = ValidatorUtility.IsFirstNameValid(name); Assert.IsTrue(isValid); }
public FactsBase() { _validationContext = new Mock <IValidationEntitiesContext>(); _logger = new Mock <ILogger <ValidatorStateService> >(); _validationRequest = new Mock <IValidationRequest>(); _validationRequest.Setup(x => x.NupkgUrl).Returns(NupkgUrl); _validationRequest.Setup(x => x.PackageId).Returns(PackageId); _validationRequest.Setup(x => x.PackageKey).Returns(PackageKey); _validationRequest.Setup(x => x.PackageVersion).Returns(PackageVersion); _validationRequest.Setup(x => x.ValidationId).Returns(ValidationId); _target = CreateValidatorStateService(ValidatorUtility.GetValidatorName(typeof(AValidator))); }
protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { base.DoValidate(objectToValidate, currentTarget, key, validationResults); IArtifactLinkContainer container = objectToValidate as IArtifactLinkContainer; if (validationResults.IsValid && ModelCollector.HasValidArtifacts(container) && !ModelCollector.HasRoles(container)) { this.LogValidationResult(validationResults, ValidatorUtility.ShowFormattedMessage(Resources.ExtenderObjectValidatorMessage, currentTarget), currentTarget, key); } }
public void CanGetValidator() { var validator = new TestValidator(); var validatorType = validator.GetType(); ServiceProviderMock .Setup(sp => sp.GetService(validatorType)) .Returns(() => validator); var result = Target.GetValidator(ValidatorUtility.GetValidatorName(validatorType)); ServiceProviderMock .Verify(sp => sp.GetService(validatorType), Times.Once); Assert.IsType(validatorType, result); }
public FactsBase(ITestOutputHelper output) { _output = output ?? throw new ArgumentNullException(nameof(output)); _validationContext = new Mock <IValidationEntitiesContext>(); _logger = new LoggerFactory().AddXunit(_output).CreateLogger <ValidatorStateService>(); _validationRequest = new Mock <IValidationRequest>(); _validationRequest.Setup(x => x.NupkgUrl).Returns(NupkgUrl); _validationRequest.Setup(x => x.PackageId).Returns(PackageId); _validationRequest.Setup(x => x.PackageKey).Returns(PackageKey); _validationRequest.Setup(x => x.PackageVersion).Returns(PackageVersion); _validationRequest.Setup(x => x.ValidationId).Returns(ValidationId); _target = CreateValidatorStateService(ValidatorUtility.GetValidatorName(typeof(AValidator))); }
/// <summary> /// Discovers all <see cref="INuGetValidator"/> and <see cref="INuGetProcessor"/> types available and caches the result. /// </summary> private void InitializeEvaluatedTypes(Assembly callingAssembly) { if (_evaluatedTypes != null) { return; } lock (_evaluatedTypesLock) { if (_evaluatedTypes != null) { return; } using (_logger.BeginScope($"Enumerating all {nameof(INuGetValidator)} implementations")) { _logger.LogTrace("Before enumeration"); IEnumerable <Type> candidateTypes = GetCandidateTypes(callingAssembly); var nugetValidatorTypes = candidateTypes .Where(type => typeof(INuGetValidator).IsAssignableFrom(type) && type != typeof(INuGetValidator) && type != typeof(INuGetProcessor) && ValidatorUtility.HasValidatorNameAttribute(type)) .ToDictionary(ValidatorUtility.GetValidatorName); var nugetProcessorTypes = nugetValidatorTypes .Values .Where(IsProcessorType) .ToDictionary(ValidatorUtility.GetValidatorName); _logger.LogTrace("After enumeration, got {NumImplementations} implementations: {TypeNames}", nugetValidatorTypes.Count, nugetValidatorTypes.Keys); _evaluatedTypes = new EvaluatedTypes(nugetValidatorTypes, nugetProcessorTypes); } } }
protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { //TODO: Fix this call if not working if (objectToValidate != null) { // Ignore objects than have already been validated. // if (IsValidated(objectToValidate)) { return; } Type targetType = objectToValidate.GetType(); using (FileConfigurationSource configurationSource = new FileConfigurationSource(TargetConfigurationFile)) { Validator v = ValidationFactory.CreateValidator(targetType, "Common", configurationSource); v.Validate(objectToValidate, validationResults); v = ValidationFactory.CreateValidator(targetType, targetRuleset, configurationSource); v.Validate(objectToValidate, validationResults); } Debug.WriteLine(String.Format(CultureInfo.CurrentUICulture, "{0} {1}", objectToValidate.ToString(), validationResults.IsValid ? "Succeeded" : "Failed")); } //base.DoValidate(objectToValidate, currentTarget, key, validationResults); IArtifactLinkContainer container = objectToValidate as IArtifactLinkContainer; if (validationResults.IsValid && ModelCollector.HasValidArtifacts(container) && !ModelCollector.HasRoles(container)) { this.LogValidationResult(validationResults, ValidatorUtility.ShowFormattedMessage(Resources.ExtenderObjectValidatorMessage, currentTarget), currentTarget, key); } }
public async Task <NodeCache> ExecuteAsync(Node node) { var allRpcMethods = _rpcMethodSettings.Items; var indexes = _rpcMethodSettings.Indexes ?? new HashSet <int>(); var client = _clientFactory.CreateClient(); client.BaseAddress = new Uri(node.Url); client.Timeout = TimeSpan.FromMilliseconds(_commonOption.Timeout); var result = new NodeCache(node); var rpcMethods = indexes.Select(i => allRpcMethods[i]).ToArray(); var tasks = rpcMethods.AsParallel().Select(async m => { IValidatePipeline pipeline; if (m.ResultType != ResultTypeEnum.None) { var resultValidator = ValidatorUtility.GetCachedValidator(m.ResultType); pipeline = _pipelineBuilder.Use(resultValidator).Build(); } else { pipeline = _pipelineBuilder.Build(); } var r = await pipeline.ValidateAsync(async() => { var body = new RpcRequestBody(m.Name.ToLower()) { JsonRpc = _commonOption.Jsonrpc, Params = m.Params ?? Enumerable.Empty <object>(), Id = _commonOption.Id }; string bodyStr = JsonSerializer.Serialize(body, jsonSerializerOptions); var httpContent = new StringContent(bodyStr, Encoding.UTF8, "application/json"); return(await client.PostAsync(string.Empty, httpContent)); }, m.Result ?? string.Empty); var typeResult = r.Result ? new ValidateResult <ValidationResultType>() { Result = ValidationResultType.Available } : new ValidateResult <ValidationResultType>() { Result = ValidationResultType.Unavailable, Exception = r.Exception, ExtraErrorMsg = r.ExtraErrorMsg }; result.MethodsResult.TryAdd(m.Name, typeResult); }); await Task.WhenAll(tasks); var uncheckedTypeResult = new ValidateResult <ValidationResultType>() { Result = ValidationResultType.Unchecked }; if (allRpcMethods.Length > indexes.Count) { for (int i = 0; i < allRpcMethods.Length; i++) { if (!indexes.Contains(i)) { result.MethodsResult.TryAdd(allRpcMethods[i].Name, uncheckedTypeResult); } } } return(result); }
/// <summary> /// Does the validate. /// </summary> /// <param name="objectToValidate">The object to validate.</param> /// <param name="currentTarget">The current target.</param> /// <param name="key">The key.</param> /// <param name="validationResults">The validation results.</param> protected override void DoValidate(ModelBusReference objectToValidate, object currentTarget, string key, ValidationResults validationResults) { this.MessageTemplate = currentMessageTemplate; base.DoValidate(objectToValidate, currentTarget, key, validationResults); if (!validationResults.IsValid) { return; } ServiceReference serviceReference = currentTarget as ServiceReference; if (serviceReference == null) { return; } using (ModelBusReferenceResolver resolver = new ModelBusReferenceResolver()) { ModelElement referencedElement = resolver.Resolve(objectToValidate); if (referencedElement != null) { ServiceContractModel dcm = referencedElement.Store.ElementDirectory.FindElements <ServiceContractModel>()[0]; if (dcm.ImplementationTechnology == null || String.IsNullOrWhiteSpace(dcm.ProjectMappingTable) || !dcm.ImplementationTechnology.Name.Equals(GetItName(currentTarget), StringComparison.OrdinalIgnoreCase)) { validationResults.AddResult( new ValidationResult(String.Format(CultureInfo.CurrentUICulture, this.MessageTemplate, ValidatorUtility.GetTargetName(currentTarget)), currentTarget, key, String.Empty, this)); } } } }
/// <summary> /// Determines whether the specified attr is valid. /// </summary> /// <param name="attribute">The attr.</param> /// <returns> /// <c>true</c> if the specified attr is valid; otherwise, <c>false</c>. /// </returns> public static bool IsValid(QualifiedTypeNameAttribute attribute) { return(attribute != null && !ValidatorUtility.IsNullOrEmpty(attribute.AssemblyFileName) && !ValidatorUtility.IsNullOrEmpty(attribute.QualifiedTypeName)); }
/// <summary> /// Determines whether the specified attr is valid. /// </summary> /// <param name="attribute">The attr.</param> /// <returns> /// <c>true</c> if the specified attr is valid; otherwise, <c>false</c>. /// </returns> public static bool IsValid(DisplayTextKeyAttribute attribute) { return(attribute != null && !ValidatorUtility.IsNullOrEmpty(attribute.Key)); }
// MBR format: // modelbus://logicalAdapterId/model display name/element display name/adapter reference data. // V3 format: // mel://[DSLNAMESPACE]\[MODELELEMENTTYPE]\[MODELELEMENT]@[PROJECT]\[MODELFILE] private object ConvertToModelBusReference <T>(SerializationContext serializationContext, string input) { if (serializationContext == null) { throw new ArgumentNullException("serializationContext"); } if (string.IsNullOrWhiteSpace(input) || !typeof(ModelBusReference).IsAssignableFrom(typeof(T))) { return(default(T)); } // filter out the schema part input = input.Replace(MelSchema, string.Empty); string[] data = input.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries); if (data.Length != 2) { serializationContext.Result.AddMessage(BuildSerializationMessage(Properties.Resources.InvalidMoniker, input)); return(default(T)); } string[] modelData = data[0].Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries); if (modelData.Length != 3) { serializationContext.Result.AddMessage(BuildSerializationMessage(Properties.Resources.InvalidMoniker, input)); return(default(T)); } string[] locationData = data[1].Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries); if (locationData.Length != 2) { serializationContext.Result.AddMessage(BuildSerializationMessage(Properties.Resources.InvalidMoniker, input)); return(default(T)); } // set full path to model file if (!Path.IsPathRooted(locationData[1])) { locationData[1] = Path.Combine(Path.GetDirectoryName(serializationContext.Location), locationData[1]); } ModelBusReference result = null; IModelBus bus = serializationContext[ModelBusReferencePropertySerializer.ModelBusLoadContextKey] as IModelBus; if (bus != null) { using (ModelBusAdapterManager manager = bus.GetAdapterManager(LogicalAdapterId)) { ModelBusReference reference = null; if (manager.TryCreateReference(out reference, Path.ChangeExtension(locationData[1], FileExtension))) { using (ModelBusAdapter adapter = manager.CreateAdapter(reference)) { IModelingAdapterWithStore storeAdapter = adapter as IModelingAdapterWithStore; if (storeAdapter.Store != null) { foreach (ModelElement mel in FilterElementsByType(storeAdapter.Store, modelData[1])) { if (ValidatorUtility.GetTargetName(mel).Equals(modelData[2], StringComparison.OrdinalIgnoreCase)) { return(adapter.GetElementReference(mel)); } } // If we are still here, we could not find any match so try will all mels foreach (ModelElement mel in FilterElementsByType(storeAdapter.Store, string.Empty)) { if (ValidatorUtility.GetTargetName(mel).Equals(modelData[2], StringComparison.OrdinalIgnoreCase)) { return(adapter.GetElementReference(mel)); } } } } } } } serializationContext.Result.AddMessage(BuildSerializationMessage(Properties.Resources.ReferenceElementNotFound, input)); return(result); }
/// <summary> /// Does the validate. /// </summary> /// <param name="objectToValidate">The object to validate.</param> /// <param name="currentTarget">The current target.</param> /// <param name="key">The key.</param> /// <param name="validationResults">The validation results.</param> protected override void DoValidate(ModelBusReference objectToValidate, object currentTarget, string key, ValidationResults validationResults) { // store default message (in case the error comes from a DC element) and set our new message dcModelMessageTemplate = this.MessageTemplate; this.MessageTemplate = currentMessageTemplate; // Validate cross model references base.DoValidate(objectToValidate, currentTarget, key, validationResults); if (!validationResults.IsValid) { return; } using (ModelBusReferenceResolver resolver = new ModelBusReferenceResolver()) { ModelElement referencedElement = resolver.Resolve(objectToValidate); if (referencedElement != null) { DataContractModel dcm = referencedElement.Store.ElementDirectory.FindElements <DataContractModel>()[0]; if (dcm.ImplementationTechnology == null || String.IsNullOrWhiteSpace(dcm.ProjectMappingTable) || !dcm.ImplementationTechnology.Name.Equals(GetItName(currentTarget), StringComparison.OrdinalIgnoreCase)) { validationResults.AddResult( new ValidationResult(String.Format(CultureInfo.CurrentUICulture, this.dcModelMessageTemplate, ValidatorUtility.GetTargetName(currentTarget)), currentTarget, key, String.Empty, this)); } } } }
private static string GetElementName(ModelElement element) { return(element != null? ValidatorUtility.GetTargetName(element) : Guid.NewGuid().ToString()); }
public IValidatePipelineBuilder Use(Func <JsonDocument, string, ValidateResult <bool> > validateFunc) { var validator = ValidatorUtility.FromDelegate(validateFunc); return(Use(validator)); }