Ejemplo n.º 1
0
        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));
            }
        }
        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));
            }
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        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);
            }
        }
Ejemplo n.º 6
0
        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"));
            }
        }
Ejemplo n.º 7
0
        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 }));
            }
        }
        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();
            }
        }