Пример #1
0
        public IActionResult CreateMaterial([FromBody] MaterialCreationRequest materialCreationRequest)
        {
            if (materialCreationRequest == null ||
                string.IsNullOrWhiteSpace(materialCreationRequest.Name) ||
                string.IsNullOrWhiteSpace(materialCreationRequest.Manufacturer) ||
                string.IsNullOrWhiteSpace(materialCreationRequest.ManufacturerId) ||
                string.IsNullOrWhiteSpace(materialCreationRequest.Type))
            {
                return(HandleBadRequest("Incomplete or invalid material data submitted for creation."));
            }

            // Check for material type validity
            Plastic plastic = null;

            try
            {
                plastic = PlasticsService.GetPlastic(materialCreationRequest.Type);
            }
            catch (PlasticNotFoundException exception)
            {
                return(HandleBadRequest(exception.Message));
            }

            // Proceed with creation
            try
            {
                Material material = MaterialsService.CreateMaterial(materialCreationRequest.Name, materialCreationRequest.Manufacturer, materialCreationRequest.ManufacturerId, plastic);
                return(Created(GetNewResourceUri(material.Id), material));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }
Пример #2
0
        /// <summary>
        /// Загрузка списка объектов из базы данных, их отображение в таблице, указание их кол-ва в Label
        /// </summary>
        /// <inheritdoc />
        public void AdditionalInitializeComponent()
        {
            FilterBarCoverLabel.Content = PageLiterals.FilterBarCoverLabel;             // Сообщение-заглушка панели фильтрации
            try
            {
                if (_type == "s")
                {
                    TitleLabel.Content = " Материалы [MsSQL]";
                    _materials         = MaterialsService.GetAllMssql();
                }
                else
                {
                    TitleLabel.Content = " Материалы [FoxPro]";
                    _materials         = MaterialsService.GetAllCenad();
                }

                if (_materials != null && _materials.Count > 0)
                {
                    // Критерии сортировки указаны в реализации интерфейса IComparable класса
                    _materials.Sort();
                }
                PageDataGrid.ItemsSource = _materials;
                ShowCountItemsPageDataGrid();
            }
            catch (StorageException ex)
            {
                Common.ShowDetailExceptionMessage(ex);
            }
        }
Пример #3
0
        private static void OnParsedArguments(Options options)
        {
            Console.WriteLine("Generating items...");
            var materialsService = new MaterialsService(options.FileName);

            materialsService.Execute();
        }
Пример #4
0
        public IActionResult SetCustomFileMaterialProp(int materialId, Guid propId, IFormFile file)
        {
            if (file.Length <= 0)
            {
                return(HandleBadRequest("No file content found."));
            }

            try
            {
                // Get custom prop and validate type
                CustomMaterialProp prop = CustomMaterialPropService.GetCustomMaterialProp(propId);
                if (prop.Type != PropType.File)
                {
                    return(HandleBadRequest("The submitted prop is not of the type `file`."));
                }
                MaterialsService.UpdateCustomFileMaterialProp(materialId, prop, file);

                // Done!
                return(NoContent());
            }
            catch (CustomPropNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (MaterialNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }
Пример #5
0
        public override bool Remove(Category category)
        {
            try {
                category = Get(category.CategoryID);
                if (category != null)
                {
                    foreach (var referencedProp in
                             PropsRepository.Instanse.GetAll(prop => prop.CategoryID == category.CategoryID))
                    {
                        referencedProp.CategoryID = null;
                        PropsService.Instanse.Insert(referencedProp);
                    }
                    foreach (var referencedMaterial in
                             MaterialsRepository.Instanse.GetAll(material => material.CategoryID == category.CategoryID))
                    {
                        referencedMaterial.CategoryID = null;
                        MaterialsService.Insert(referencedMaterial);
                    }

                    LogsService.Instanse.Insert(new Log {
                        HostTable = (short)HostTable.Categories,
                        Details   = Log.CategoryDetailer(category, ActionType.Removed)
                    });
                    CategoriesRepository.Instanse.DeleteAndSubmit(category);
                    return(true);
                }
                return(false);
            } catch (Exception exception) {
                Logger.Write(exception);
                return(false);
            }
        }
Пример #6
0
        public IActionResult DeleteCustomFileMaterialProp(int materialId, Guid propId)
        {
            try
            {
                // Get custom prop and validate type
                CustomMaterialProp prop = CustomMaterialPropService.GetCustomMaterialProp(propId);
                if (prop.Type != PropType.File)
                {
                    return(HandleBadRequest("The submitted prop is not of the type `file`."));
                }

                // Update material - remove prop
                MaterialsService.UpdateCustomFileMaterialProp(materialId, prop, null);

                // Done!
                return(NoContent());
            }
            catch (CustomPropNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (MaterialNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }
 public async Task CreateAlloy_Throws_WhenCompositionNotUnique()
 {
     #region ARRANGE
     var materialsService = new MaterialsService(inMemoryDbContext);
     var composition      = new Dictionary <string, double>()
     {
         { "Ag", 44.6 }, { "Al", 55.4 }
     };
     #endregion
     #region ACT
     var expectedException = new DuplicateObjectException(string.Empty, string.Empty);
     try
     {
         var alloy = await materialsService.CreateAlloyAsync(composition);
     }
     catch (Exception exception)
     {
         expectedException = exception as DuplicateObjectException;
     }
     #endregion
     #region ASSERT
     Assert.IsAssignableFrom <Exception>(expectedException);
     Assert.NotNull(expectedException);
     Assert.IsType <DuplicateObjectException>(expectedException);
     #endregion
 }
        public MaterialsModel[] Retorno([FromQuery(Name = "parametro")] string parametro)
        {
            List <MaterialsModel> listaJson = JsonConvert.DeserializeObject <List <MaterialsModel> >(System.IO.File.ReadAllText("C:/Users/vitor/source/repos/WebApplication3/data/materials.json"));



            return(MaterialsService.ConstrutorArray(listaJson, parametro));
        }
Пример #9
0
 public ItemFactory(CitadelObtainer citadelObtainer, BlueprintService blueprintService, Func<int, string> getItemNameFunc, Func<string, int> getItemIdFunc, MaterialsService materialsService)
 {
     _citadelObtainer = citadelObtainer;
     _blueprintService = blueprintService;
     _getItemNameFunc = getItemNameFunc;
     _getItemIdFunc = getItemIdFunc;
     _materialsService = materialsService;
 }
Пример #10
0
 private void CmbMaterialsSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     InputChanged(null, null);
     if (cmbMaterials.SelectedValue != null)
     {
         var material = MaterialsService.Get((Guid)cmbMaterials.SelectedValue);
         tbAmount.Tag = string.Format(RepositoryMaterialsAndItemsResources.AmountBy, material.StringUnit);
     }
 }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InventoryController"/> class.
 /// </summary>
 /// <param name="loggerFactory">A factory to create loggers from.</param>
 /// <param name="inventoryService">The service providing inventory functionality.</param>
 /// <param name="materialsService">A service providing material data.</param>
 /// <param name="locationsService">A service providing locations data.</param>
 public InventoryController(ILoggerFactory loggerFactory,
                            InventoryService inventoryService,
                            MaterialsService materialsService,
                            LocationsService locationsService)
 {
     Logger           = loggerFactory.CreateLogger <InventoryController>();
     InventoryService = inventoryService;
     MaterialsService = materialsService;
     LocationsService = locationsService;
 }
Пример #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MaterialsController"/> class.
 /// </summary>
 /// <param name="loggerFactory">A factory to create loggers from.</param>
 /// <param name="plasticsService">Grants access to known plastics.</param>
 /// <param name="materialsService">The materials service.</param>
 /// <param name="customMaterialPropService">Grants access to custom material props.</param>
 public MaterialsController(ILoggerFactory loggerFactory,
                            PlasticsService plasticsService,
                            MaterialsService materialsService,
                            CustomMaterialPropService customMaterialPropService)
 {
     Logger                    = loggerFactory.CreateLogger <MaterialsController>();
     PlasticsService           = plasticsService;
     MaterialsService          = materialsService;
     CustomMaterialPropService = customMaterialPropService;
 }
        public async Task ExpendMaterials_DecreasesMaterialReservesCorrectly()
        {
            #region ARRANGE
            var targetMaterial = await inMemoryDbContext.Warehouse
                                 .FirstOrDefaultAsync(m => m.Element == EElement.Ag);

            var    initialReserves   = targetMaterial?.QuantityInKg;
            var    materialsService  = new MaterialsService(inMemoryDbContext);
            double quantityToExpend  = 64;
            var    materialsToExpend = new (string, int, double)[]
Пример #14
0
        private void ChangeProductList(Product product)
        {
            if (product == null)
            {
                return;
            }

            _selectedMaterials = MaterialsService.GetMaterialsByProductIdWhithMeasure(product.Id);
            MaterialFromProductListBox.ItemsSource = null;
            MaterialFromProductListBox.ItemsSource = _selectedMaterials;
        }
 public void CheckAvailability_ReturnsZero_WhenMaterialNotFound()
 {
     #region ARRANGE
     var materialsService = new MaterialsService(inMemoryDbContext);
     #endregion
     #region ACT
     var materialQuantity = materialsService.CheckAvailability(string.Empty, string.Empty);
     #endregion
     #region ASSERT
     Assert.Equal(0, materialQuantity);
     #endregion
 }
Пример #16
0
        public async Task <IActionResult> Upload(MaterialUploadViewModel input)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(input));
            }

            var user = await this.UserManager.GetUserAsync(this.User);

            var result = await MaterialsService.UploadAsync(input, user);

            return(this.RedirectToAction("All"));
        }
Пример #17
0
        protected override void SaveWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (ValidateFields())
            {
                var      initialAmount = 0;
                Material material      = null;
                if (EditMode)
                {
                    material = _current;
                }

                if (material == null)
                {
                    object returnValue;
                    uint   temp;
                    if (InputWindowHelpers.Show(this, x => uint.TryParse(x.ToString(), out temp),
                                                MaterialsResources.InitialAmountDescription,
                                                MaterialsResources.InitialAmount, out returnValue, 0))
                    {
                        initialAmount = int.Parse(returnValue.ToString());
                    }
                    material = new Material();
                }
                material.Name          = cmbNames.Text.Trim();
                material.Unit          = (short)cmbMesureUnit.SelectedIndex;
                material.LowestAmount  = int.Parse(tbLowestAmount.Text);
                material.Formula       = tbFormula.Text;
                material.MolecularMass = tbMolecularMass.Text;
                material.Description   = tbDescription.Text.Trim();
                if (cmbCategories.SelectedValue != null)
                {
                    material.CategoryID = (Guid)cmbCategories.SelectedValue;
                }

                if (MaterialsService.Insert(material, initialAmount))
                {
                    Global.SubmissionSuceeded(this);
                    EditMode             = btnCancelChanges.IsEnabled = ChangesHappened = false;
                    btnDelete.IsEnabled  = cutTextBox.IsEnabled = true;
                    cmbNames.ItemsSource = MaterialsService.Instanse.GetAll();
                    ResetFields();
                    TryToLoad();
                }
                else
                {
                    Global.SubmissionFailed(this);
                }
            }
            aiLoader.Visibility = Visibility.Collapsed;
            OnSaving            = false;
        }
Пример #18
0
 public IActionResult GetMaterial(int id)
 {
     try
     {
         Material material = MaterialsService.GetMaterial(id);
         return(Ok(material));
     }
     catch (MaterialNotFoundException exception)
     {
         return(HandleResourceNotFoundException(exception));
     }
     catch (Exception exception)
     {
         return(HandleUnexpectedException(exception));
     }
 }
Пример #19
0
        public IActionResult GetMaterials(
            [FromQuery] bool getAll         = false,
            [FromQuery] int page            = 1,
            [FromQuery] int elementsPerPage = 10,
            [FromQuery] string search       = null,
            [FromQuery] string manufacturer = null,
            [FromQuery] string type         = null)
        {
            if (!getAll && (page < 1 || elementsPerPage < 1))
            {
                return(HandleBadRequest("Bad pagination parameters."));
            }

            // Check for material type validity
            Plastic plastic = null;

            if (type != null)
            {
                try
                {
                    plastic = PlasticsService.GetPlastic(type);
                }
                catch (PlasticNotFoundException exception)
                {
                    return(HandleBadRequest(exception.Message));
                }
            }

            // Get, filter and paginate materials
            try
            {
                IEnumerable <Material> materials          = MaterialsService.GetMaterials(search, manufacturer, plastic);
                IEnumerable <Material> paginatedMaterials = materials;
                if (!getAll)
                {
                    paginatedMaterials = materials.Skip((page - 1) * elementsPerPage).Take(elementsPerPage);
                }
                return(Ok(new PaginatedResponse(paginatedMaterials, materials.Count())));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }
Пример #20
0
        public void ValidateAmount(Guid materialID, int amount, out int result)
        {
            var material         = MaterialsService.Get(materialID);
            var all              = GetAll(materialID);
            var repositoryAmount = all.Sum(m => m.Amount);

            if (repositoryAmount + amount >= material.LowestAmount)
            {
                result = -2;
            }
            else if (repositoryAmount + amount >= 0)
            {
                result = -1;
            }
            else
            {
                result = repositoryAmount;
            }
        }
Пример #21
0
        /// <summary>
        /// Загрузка списка объектов из базы данных, их отображение в таблице, указание их кол-ва в Label
        /// </summary>
        public void AdditionalInitializeComponent()
        {
            FilterBarCoverLabel.Content = PageLiterals.FilterBarCoverLabel;             // Сообщение-заглушка панели фильтрации
            try
            {
                _materials = MaterialsService.GetAllCenad();
                if (_materials != null && _materials.Count > 0)
                {
                    // Критерии сортировки указаны в реализации интерфейса IComparable класса
                    _materials.Sort();
                }

                WindowDataGrid.ItemsSource = _materials;
                ShowCountItemsWindowDataGrid();
            }
            catch (StorageException ex)
            {
                Common.ShowDetailExceptionMessage(ex);
            }
        }
        public async Task CreateAlloy_RetunrsNewAlloy_WithCorrectProperties_WhenCompositionIsUnique()
        {
            #region ARRANGE
            var materialsService = new MaterialsService(inMemoryDbContext);
            var composition      = new Dictionary <string, double>()
            {
                { "Fe", 74.5 }, { "Ti", 25.5 }
            };
            decimal researchCost = 2345.6M;
            #endregion
            #region ACT
            var alloy = await materialsService.CreateAlloyAsync(composition, researchCost);

            #endregion
            #region ASSERT
            Assert.NotNull(alloy);
            Assert.Equal("Fe74.5Ti25.5", alloy.Composition);
            Assert.Equal(researchCost, alloy.ResearchCost);
            #endregion
        }
Пример #23
0
        private void ChangeProductList(Product product)
        {
            if (product == null)
            {
                return;
            }

            _materials = MaterialsService.GetMaterialsByProductId(product.Id);
            MaterialDataGrid.ItemsSource = null;
            MaterialDataGrid.ItemsSource = _materials;

            IdLabel.Content              = product.CodeProduct;
            IdLabel.ToolTip              = product.CodeProduct;
            NameLabel.Content            = product.Name;
            NameLabel.ToolTip            = product.Name;
            DesignationLabel.Content     = product.Mark;
            DesignationLabel.ToolTip     = product.Mark;
            CopyMaterialButton.IsEnabled = true;
            AddMaterialButton.IsEnabled  = true;
        }
Пример #24
0
        private bool ValidateFields()
        {
            if (string.IsNullOrWhiteSpace(cmbNames.Text))
            {
                cmbNames.Focus();
                return(false);
            }

            if (!EditMode)
            {
                if (MaterialsService.Exist(cmbNames.Text))
                {
                    Global.ValidationFailed(this, MaterialsResources.NameDuplicate);
                    cmbNames.Focus();
                    return(false);
                }
            }
            else if (MaterialsService.Exist(cmbNames.Text, _current))
            {
                Global.ValidationFailed(this, MaterialsResources.NameDuplicate);
                cmbNames.Focus();
                return(false);
            }

            if (cmbMesureUnit.SelectedIndex == -1)
            {
                cmbMesureUnit.Focus();
                return(false);
            }

            int temp;

            if (!int.TryParse(tbLowestAmount.Text, out temp))
            {
                Global.ValidationFailed(this, InputResources.Invalid);
                tbLowestAmount.FocusAndSelect();
                return(false);
            }

            return(true);
        }
Пример #25
0
 public static bool ChangeNotifiable(Notification notification)
 {
     try {
         if (notification.NotifyType == NotifyType.Prop)
         {
             return(PropsService.ChangeNotifiable(((Prop)notification.OriginalObject).PropID, false));
         }
         if (notification.NotifyType == NotifyType.Item)
         {
             return(ItemsService.ChangeNotifiable(((Item)notification.OriginalObject), false));
         }
         if (notification.NotifyType == NotifyType.Material)
         {
             return(MaterialsService.ChangeNotifiable(((Material)notification.OriginalObject).MaterialID, false));
         }
         return(false);
     } catch (Exception exception) {
         Logger.Write(exception);
         return(false);
     }
 }
Пример #26
0
        public static string RepositoryMaterialDetailer(RepositoryMaterial repositoryMaterial, ActionType actionType)
        {
            var material = MaterialsService.Get(repositoryMaterial.MaterialID);

            if (material == null)
            {
                return(null);
            }
            switch (actionType)
            {
            case ActionType.Created:
                return(string.Format("به موجودی ماده‌ای با نام {0} {1} {2} اضافه شد.", material.Name,
                                     repositoryMaterial.Amount, material.StringUnit));

            case ActionType.Removed:
                return(string.Format("از موجودی ماده‌ای با نام {0} {1} {2} کم شد.", material.Name,
                                     repositoryMaterial.Amount, material.StringUnit));

            default:
                return(null);
            }
        }
Пример #27
0
        public IActionResult UpdateMaterialMasterData(int id, [FromBody] MaterialUpdateRequest materialUpdateRequest)
        {
            if (materialUpdateRequest == null ||
                string.IsNullOrWhiteSpace(materialUpdateRequest.Name) ||
                string.IsNullOrWhiteSpace(materialUpdateRequest.Manufacturer) ||
                string.IsNullOrWhiteSpace(materialUpdateRequest.ManufacturerId) ||
                string.IsNullOrWhiteSpace(materialUpdateRequest.Type))
            {
                return(HandleBadRequest("Incomplete or invalid material data submitted for update."));
            }

            // Check for material type validity
            Plastic plastic = null;

            try
            {
                plastic = PlasticsService.GetPlastic(materialUpdateRequest.Type);
            }
            catch (PlasticNotFoundException exception)
            {
                return(HandleBadRequest(exception.Message));
            }

            // Proceed with updating
            try
            {
                Material material = MaterialsService.UpdateMaterial(id, materialUpdateRequest.Name, materialUpdateRequest.Manufacturer, materialUpdateRequest.ManufacturerId, plastic);
                return(Ok(material));
            }
            catch (MaterialNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }
Пример #28
0
        public IActionResult DownloadCustomPropFile(int materialId, Guid propId)
        {
            try
            {
                // Get custom prop and validate type
                CustomMaterialProp prop = CustomMaterialPropService.GetCustomMaterialProp(propId);
                if (prop.Type != PropType.File)
                {
                    return(HandleBadRequest("The submitted prop is not of the type `file`."));
                }

                // Get and validate file path
                string path = MaterialsService.GetCustomPropFilePath(materialId, prop);
                if (string.IsNullOrWhiteSpace(path))
                {
                    return(NotFound(new ClientErrorResponse("File could not be found!")));
                }

                string fileName    = Path.GetFileName(path);
                byte[] fileBytes   = System.IO.File.ReadAllBytes(path);
                string contentType = "application/octet-stream";
                new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);
                return(File(fileBytes, contentType, fileName));
            }
            catch (CustomPropNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (MaterialNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }
Пример #29
0
 protected override void SaveWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (Global.ShowQuestion(this))
     {
         var count          = PropsService.CountOfNotNotifiable() + MaterialsService.CountOfNotNotifiable();
         var progressWindow = new ProgressWindow(count);
         progressWindow.Show(this);
         foreach (var propID in PropsService.GetAllNotNotifiables())
         {
             PropsService.ChangeNotifiable(propID, true);
             progressWindow.IncreaseProgress();
         }
         foreach (var materialID in MaterialsService.GetAllNotNotifiables())
         {
             MaterialsService.ChangeNotifiable(materialID, true);
             progressWindow.IncreaseProgress();
         }
         progressWindow.Close();
         Global.ShowSuceeded(this);
         TryToLoad();
     }
     aiLoader.Visibility = Visibility.Collapsed;
     OnSaving            = false;
 }
Пример #30
0
        public IActionResult SetCustomTextMaterialProp(int materialId, Guid propId, [FromBody] SetCustomTextMaterialPropRequest setCustomTextMaterialPropRequest)
        {
            if (setCustomTextMaterialPropRequest == null ||
                string.IsNullOrWhiteSpace(setCustomTextMaterialPropRequest.Text))
            {
                return(HandleBadRequest("A text to set for the custom material prop has to be provided."));
            }

            try
            {
                // Get custom prop and validate type
                CustomMaterialProp prop = CustomMaterialPropService.GetCustomMaterialProp(propId);
                if (prop.Type != PropType.Text)
                {
                    return(HandleBadRequest("The submitted prop is not of the type `text`."));
                }

                // Update material - set prop
                MaterialsService.UpdateCustomTextMaterialProp(materialId, prop, setCustomTextMaterialPropRequest.Text);

                // Done!
                return(NoContent());
            }
            catch (CustomPropNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (MaterialNotFoundException exception)
            {
                return(HandleResourceNotFoundException(exception));
            }
            catch (Exception exception)
            {
                return(HandleUnexpectedException(exception));
            }
        }