public async void AssetValidator_FailsIfRackDoesNotExist() { var mockAssetRepo = new Mock <IAssetRepository>(); mockAssetRepo.Setup(o => o.AssetIsUniqueAsync(It.IsAny <string>(), It.IsAny <Guid>())) .ReturnsAsync(true); var mockRackRepo = new Mock <IRackRepository>(); mockRackRepo.Setup(o => o.AddressExistsAsync(It.IsAny <string>(), It.IsAny <int>(), Guid.NewGuid())) .ReturnsAsync(true); var mockModelRepo = new Mock <IModelRepository>(); mockModelRepo.Setup(o => o.ModelExistsAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Guid>())) .ReturnsAsync(true); var mockIdentityRepo = new Mock <IIdentityRepository>(); mockIdentityRepo.Setup(o => o.GetUserAsync(It.IsAny <Guid>())) .ReturnsAsync(new User()); // not null var sut = new AssetValidator(mockAssetRepo.Object, mockRackRepo.Object, mockModelRepo.Object, mockIdentityRepo.Object); var asset = GetValidAsset(); var result = await sut.ValidateAsync(asset); Assert.False(result.IsValid); }
public async Task <ActionResult> Post([FromBody] Asset model) { var validator = new AssetValidator(); var validatrionResult = validator.Validate(model); if (validatrionResult.IsValid) { try { model.CountryOfDepartment = await _CountryRepository.GetCountryName(model.CountryOfDepartment); } catch (Exception ex) { var errors = new List <ValidationFailure>() { new ValidationFailure("CountryOfDepartment", ex.Message) }; return(new BadRequestObjectResult(errors)); } _Repository.InsertAsset(model); _Repository.Save(); return(Ok()); } else { return(new BadRequestObjectResult(validatrionResult.Errors)); } }
private void OnValidate() { AssetValidator.ValidateAssets(this); //Indirect validation on specified gameobject AssetValidator.ValidateAssets(DemoUIRectTransform.gameObject, typeof(ExampleUIValidator)); }
public IActionResult EditAsset(int id, [FromBody] SaveAssetDto asset) { var validator = new AssetValidator(); var result = validator.Validate(asset); if (result.IsValid) { try { var editedData = _assetProvider.UpdateAsset(id, asset); var absoluteUri = string.Concat( Request.Scheme, "://", Request.Host.ToUriComponent(), Request.PathBase.ToUriComponent(), $"/api/Asset/GetAssetById/{id}"); return(Created(new Uri(absoluteUri), absoluteUri)); } catch (Exception exc) { return(BadRequest(exc.Message)); } } else { List <string> errorMessages = new List <string>(); foreach (var item in result.Errors) { errorMessages.Add(item.ErrorMessage); } return(BadRequest(errorMessages)); } }
public IActionResult AddAsset(SaveAssetDto asset) { var validator = new AssetValidator(); var result = validator.Validate(asset); if (result.IsValid) { var data = _assetProvider.SaveAsset(asset); var absoluteUri = string.Concat( Request.Scheme, "://", Request.Host.ToUriComponent(), Request.PathBase.ToUriComponent(), $"/api/Asset/GetAssetById/{data.Id}"); return(Created(new Uri(absoluteUri), absoluteUri)); } else { List <string> errorMessages = new List <string>(); foreach (var item in result.Errors) { errorMessages.Add(item.ErrorMessage); } return(BadRequest(errorMessages)); } }
public static bool IsValid(this AssetDto assetDto, ICountrySearch search, out IEnumerable <string> errors) { var validator = new AssetValidator(search); var validationResult = validator.Validate(assetDto); errors = AggregateErrors(validationResult); return(validationResult.IsValid); }
public (bool flag, string errors) validateAsset(Asset dto) { var validator = new AssetValidator(); var res = validator.Validate(dto, options => options.IncludeRuleSets("all")); if (!res.IsValid) { return(false, res.ToString("~")); } else { return(true, string.Empty); } }
/// <summary> /// Validates all properties of properties of an AssetDto object. /// </summary> /// <param name="dto">The <see cref="AssetDto"/>.</param> protected override async Task ValidateAsync(AssetDto dto) { if (IsNull(dto)) { return; } var url = $"https://restcountries.eu/rest/v2/name/{dto.CountryOfDepartment}?fullText=true"; var assetValidator = new AssetValidator(HttpDataAccess.SendRequestAsync(url)); var results = await assetValidator.ValidateAsync(new ValidationContext <Asset>(Adapt(dto))); foreach (var e in results.Errors) { ModelState.AddModelError(e.PropertyName, Localizer[e.ErrorCode ?? e.ErrorMessage]); } }
public async Task <ActionResult <Asset> > CreateAsset(Asset Asset) { try { if (Asset == null) { return(BadRequest()); } _logger.LogInformation("Checking if the email is associated with any record."); var emp = AssetRepository.GetAssetByEmail(Asset.EMailAdressOfDepartment); if (emp != null) { ModelState.AddModelError("email", "Asset email already in use"); return(BadRequest(ModelState)); } AssetValidator validator = new AssetValidator(); ValidationResult results = validator.Validate(Asset); if (!results.IsValid) { foreach (var failure in results.Errors) { Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage); } _logger.LogInformation("Some validation errors have been generated. " + string.Join("", results.Errors)); return(BadRequest(string.Join("", results.Errors))); } else { _logger.LogInformation("Creating new Asset."); var createdAsset = await AssetRepository.AddAsset(Asset); return(CreatedAtAction(nameof(GetAsset), new { id = createdAsset.Id }, createdAsset)); } } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the database")); } }
public async Task <ActionResult <Asset> > UpdateAsset(int id, Asset Asset) { try { _logger.LogInformation("Error Updating Asset. -> Asset ID mismatch"); if (id != Asset.Id) { return(BadRequest("Asset ID mismatch")); } var AssetToUpdate = await AssetRepository.GetAssetById(id); if (AssetToUpdate == null) { _logger.LogInformation($"Error Updating Asset. -> Asset with Id = {id} not found"); return(NotFound($"Asset with Id = {id} not found")); } AssetValidator validator = new AssetValidator(); ValidationResult results = validator.Validate(Asset); if (!results.IsValid) { foreach (var failure in results.Errors) { Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage); } return(BadRequest(string.Join("", results.Errors))); } else { _logger.LogInformation($"Updating Asset..."); return(await AssetRepository.UpdateAsset(Asset)); } } catch (Exception) { return(StatusCode(StatusCodes.Status500InternalServerError, "Error updating data")); } }
public async Task <IActionResult> Put(AssetViewModel model) { try { Asset asset = _unitOfWork.AssetService.GetAssetbyId(model.Id); if (asset != null) { asset.AssetName = model.AssetName; asset.Broken = model.Broken; asset.CountryOfDepartment = model.CountryOfDepartment; asset.Department = (Department)model.Department; asset.EMailAdressOfDepartment = model.EMailAdressOfDepartment; asset.PurchaseDate = Convert.ToDateTime(model.PurchaseDate); AssetValidator validator = new AssetValidator(); ValidationResult results = validator.Validate(asset); if (results.IsValid) { List <CountryDTO> countryDtos = await _externalService.GetCountryAsync(model.CountryOfDepartment); if (countryDtos.Count > 0) { _unitOfWork.AssetService.UpdateAsset(asset); _unitOfWork.SaveChanges(); _logger.LogInformation($"Asset with Id {asset.Id} have beeen update Successufully."); return(Created("", asset)); } return(BadRequest(new { message = "Invilid country Name. Please enter a valid county name.", succeed = false })); } return(BadRequest(new { message = results.ToString(), succeed = false })); } else { _logger.LogInformation("Asset Id was not found in Put method."); return(NotFound(new { message = "Asset does not exist.", succeed = false })); } } catch (Exception ex) { _logger.LogWarning(ex, ex.Message); return(BadRequest(new { message = "Unknow server error", succeed = false })); } }
public async Task <IActionResult> Post(AssetViewModel model) { try { Asset asset = new Asset() { AssetName = model.AssetName, Broken = model.Broken, CountryOfDepartment = model.CountryOfDepartment, Department = (Department)model.Department, EMailAdressOfDepartment = model.EMailAdressOfDepartment, PurchaseDate = Convert.ToDateTime(model.PurchaseDate) }; AssetValidator validator = new AssetValidator(); ValidationResult results = validator.Validate(asset); if (results.IsValid) { List <CountryDTO> countryDtos = await _externalService.GetCountryAsync(model.CountryOfDepartment); if (countryDtos != null && countryDtos.Count > 0) { _unitOfWork.AssetService.AddAsset(asset); _unitOfWork.SaveChanges(); _logger.LogInformation($"Asset with Id {asset.Id} have beeen created Successufully."); return(Created("", asset)); } return(BadRequest(new { message = "Invilid country Name. Please enter a valid county name." })); } return(BadRequest(new { message = results.ToString() })); } catch (Exception ex) { _logger.LogWarning(ex, ex.Message); return(BadRequest(new { message = "Unknow server error.", succeed = false })); } }
string GetLocalizedString(string str_id) { return(AssetValidator.GetLocalizedString(str_id, _config)); }
private void SaveAsset() { AssetValidator validator = new AssetValidator(); ValidationResult results = validator.Validate(_currentAsset); if (!results.IsValid) { foreach (var failure in results.Errors) { Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage); } } else { MessengerInstance.Send(new LoadingMessage("Saving asset...")); Exception exceptionResult = null; BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (object sender, DoWorkEventArgs e) => { if (_currentAsset.ID == 0) { _currentAsset.CreatedBy = StateManager.CurrentUser.ID; _currentAsset.ModifiedBy = null; } else _currentAsset.ModifiedBy = StateManager.CurrentUser.ID; if (FilterRoom != null) _currentAsset.RoomID = FilterRoom.ID; else _currentAsset.RoomID = null; _assetService.Save(_currentAsset); }; worker.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) => { RaisePropertyChanged("CurrentAsset"); MessengerInstance.Send(new NotificationMessage("AssetSaved")); MessengerInstance.Send(new LoadingMessage(false)); Cancel(); }; worker.RunWorkerAsync(); } }
public void BuildInfraSetupScript(string manifestFile, string outputFolder) { IEnumerable <IAsset> unresolvedAssets = null; var assets = AssetReader.Read(manifestFile); if (assets?.Any() == true) { foreach (var asset in assets) { _assetManager.Add(asset); unresolvedAssets = _assetManager.EvaluateUnfulfilledComponents(asset); } } if (unresolvedAssets?.Any() == true) { foreach (var asset in unresolvedAssets) { _logger.LogWarning($"Unable to resolve {asset.Type}"); var missingDependencyTypes = asset.Dependencies.Where(d => string.IsNullOrEmpty(d.Key)) .Select(d => d.Type); _logger.LogWarning($"Unresolved components: {string.Join(",", missingDependencyTypes)}"); } } var sortedComponents = _assetManager.GetAllAssetsWithObjPath() .Where(c => c.Kind == AssetKind.Infra || c.Kind == AssetKind.Shared) .OrderBy(c => c.SortOrder) .ToList(); var validator = new AssetValidator(_assetManager, _loggerFactory); validator.TryToValidateAssets(sortedComponents); var envName = "dev"; var spaceName = Environment.UserName; if (sortedComponents.FirstOrDefault(c => c.Type == AssetType.Global) is Global global) { envName = global.EnvName; spaceName = global.SpaceName; } if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } var envFolder = Path.Join(outputFolder, "env", envName); if (!Directory.Exists(envFolder)) { Directory.CreateDirectory(envFolder); } var spaceFolder = envFolder; if (!string.IsNullOrEmpty(spaceName)) { spaceFolder = Path.Join(envFolder, spaceName); } if (!Directory.Exists(spaceFolder)) { Directory.CreateDirectory(spaceFolder); } var zipFilePath = Path.Join("Evidence", "scripts.zip"); if (!File.Exists(zipFilePath)) { throw new Exception($"Unable to find script bundle: {new FileInfo(zipFilePath).FullName}"); } ZipFile.ExtractToDirectory(zipFilePath, outputFolder, true); var valueYamlFile = Path.Combine(spaceFolder, "values.yaml"); _logger.LogInformation($"Set values yaml file to '{new FileInfo(valueYamlFile).FullName}'"); if (File.Exists(valueYamlFile)) { File.Delete(valueYamlFile); } using (var writer = new StreamWriter(File.OpenWrite(valueYamlFile))) { foreach (var asset in sortedComponents) { asset.WriteYaml(writer, _assetManager, _loggerFactory); } } // replace "True" and "False" var yamlContent = File.ReadAllText(valueYamlFile); var trueRegex = new Regex("\\bTrue\\b"); yamlContent = trueRegex.Replace(yamlContent, "true"); var falseRegex = new Regex("\\bFalse\\b"); yamlContent = falseRegex.Replace(yamlContent, "false"); File.WriteAllText(valueYamlFile, yamlContent); }
public void GenerateCode(string manifestFile, string solutionFolder) { IEnumerable <IAsset> unresolvedAssets = null; var assets = AssetReader.Read(manifestFile); if (assets?.Any() == true) { foreach (var asset in assets) { _assetManager.Add(asset); unresolvedAssets = _assetManager.EvaluateUnfulfilledComponents(asset); } } if (unresolvedAssets?.Any() == true) { foreach (var asset in unresolvedAssets) { _logger.LogWarning($"Unable to resolve {asset.Type}"); var missingDependencyTypes = asset.Dependencies.Where(d => string.IsNullOrEmpty(d.Key)) .Select(d => d.Type); _logger.LogWarning($"Unresolved components: {string.Join(",", missingDependencyTypes)}"); } } var sortedComponents = _assetManager.GetAllAssetsWithObjPath() .Where(c => c.Kind == AssetKind.Code || c.Kind == AssetKind.Shared) .OrderBy(c => c.SortOrder) .ToList(); var validator = new AssetValidator(_assetManager, _loggerFactory); validator.TryToValidateAssets(sortedComponents); // update solution file var product = _assetManager.Get(AssetType.Prodct) as Product; if (product == null) { throw new Exception("Missing dependency [Product]"); } var defaultSolutionFile = Path.Join(solutionFolder, $"{product.Name}.sln"); if (sortedComponents.FirstOrDefault(c => c.Type == AssetType.Service) is Services services) { foreach (var service in services.Items.OfType <Service>()) { service.SolutionFile = service.SolutionFile ?? defaultSolutionFile; } } if (!Directory.Exists(solutionFolder)) { Directory.CreateDirectory(solutionFolder); } var zipFilePath = Path.Join("Evidence", "solution.zip"); if (!File.Exists(zipFilePath)) { throw new Exception($"Unable to find solution bundle: {new FileInfo(zipFilePath).FullName}"); } ZipFile.ExtractToDirectory(zipFilePath, solutionFolder, true); var solutionFile = Directory.GetFiles(solutionFolder, "*.sln", SearchOption.TopDirectoryOnly) .FirstOrDefault(); if (!string.IsNullOrEmpty(solutionFile)) { File.Copy(solutionFile, defaultSolutionFile, true); File.Delete(solutionFile); } var manifestYamlFile = Path.Combine(solutionFolder, "services.yaml"); _logger.LogInformation($"Set manifest file to '{new FileInfo(manifestYamlFile).FullName}'"); if (File.Exists(manifestYamlFile)) { File.Delete(manifestYamlFile); } using (var writer = new StreamWriter(File.OpenWrite(manifestYamlFile))) { foreach (var asset in sortedComponents) { asset.WriteYaml(writer, _assetManager, _loggerFactory); } } // replace "True" and "False" var yamlContent = File.ReadAllText(manifestYamlFile); var trueRegex = new Regex("\\bTrue\\b"); yamlContent = trueRegex.Replace(yamlContent, "true"); var falseRegex = new Regex("\\bFalse\\b"); yamlContent = falseRegex.Replace(yamlContent, "false"); File.WriteAllText(manifestYamlFile, yamlContent); }