Пример #1
0
 private void AdministrateStorage()
 {
     foreach (Building building in player.Buildings)
     {
         Console.WriteLine($"Almacenamiento: {building.Name}");
         if (building.GetType() == typeof(StorageBuilding))
         {
             StorageBuilding storageBuilding = building as StorageBuilding;
             int             n = 1;
             foreach (FinishedProduct finishedProduct in storageBuilding.Products)
             {
                 Console.WriteLine($"{n} - {finishedProduct.Name}");
                 n++;
             }
             Console.WriteLine($"Seleccione el elemento a vender o 0 para continuar");
             int userOption = Int32.Parse(Console.ReadLine());
             if (userOption != 0 && userOption < storageBuilding.Products.Count)
             {
                 FinishedProduct selectedProduct = storageBuilding.Products[userOption - 1];
                 int             indexOfProduct  = storageBuilding.Products.IndexOf(selectedProduct);
                 player.Money += selectedProduct.Price * selectedProduct.Quality;
                 storageBuilding.Products.RemoveAt(indexOfProduct);
             }
         }
     }
 }
        public List <FinishedProduct> AddFinishedProduct(List <FinishedProduct> finishedProducts)
        {
            try {
                List <FinishedProduct> newItemsList = new List <FinishedProduct> ();
                foreach (var item in finishedProducts)
                {
                    for (var i = 0; i < (int)item.Quantity; i++)
                    {
                        FinishedProduct newItem = new FinishedProduct();

                        newItem.Id          = item.Id;
                        newItem.Quantity    = item.Quantity;
                        newItem.OrderId     = item.OrderId;
                        newItem.SubmittedBy = item.SubmittedBy;
                        newItem.RecievedBy  = item.RecievedBy;

                        newItemsList.Add(newItem);
                        _database.FinishedProduct.AddRange(newItemsList);
                    }
                }
                _database.Save();

                return(newItemsList);
            } catch (Exception e) {
                _logger.LogError(null, e.Message, e);
                return(null);
            }
        }
Пример #3
0
        public FinishedProduct Create(EnsolStockMovement finishedProduct, string ica, string orderType, string orderNumber)
        {
            if (finishedProduct == null)
            {
                throw new ArgumentNullException("role");
            }

            FinishedProduct db = new FinishedProduct();

            db.IdCompany      = finishedProduct.IdCompany;
            db.ProcessOrder   = finishedProduct.ProcessOrder;
            db.Code           = finishedProduct.Code;
            db.Description    = finishedProduct.Description;
            db.Batch          = finishedProduct.Batch;
            db.Quantity       = finishedProduct.Quantity;
            db.ECAStorageCode = finishedProduct.ECAStorageCode;
            db.ICAStorageCode = finishedProduct.ICAStorageCode;
            db.Message        = finishedProduct.Message;
            db.ICA            = ica;
            db.OrderType      = orderType;
            db.OrderNumber    = orderNumber;
            db.Stamp          = DateTime.Now;

            //TODO: buscar forma correcta de vincular errores en la capa de datos hacia la capa de distribución.
            if (Exists(db.ProcessOrder.Value))
            {
                return(null);
            }

            context.FinishedProduct.Add(db);
            context.SaveChanges();

            return(db);
        }
Пример #4
0
        public FinishedProduct FinishedProductForUpdate(UpdatedFinishedProductDto updated)
        {
            FinishedProduct current = new FinishedProduct();

            current.OrderId     = updated.orderId;
            current.SubmittedBy = updated.submitedBy;
            current.RecievedBy  = updated.recievedBy;
            current.Quantity    = updated.quantity;
            return(current);
        }
Пример #5
0
 public void AddFinishedProduct(FinishedProduct aPocket)
 {
     lock (products) {
         if (products.Count < MAX_SIZE) {
             products.Add(aPocket);
         }
         else {
             logger.Warn("Превышено количество максимальных записей в буфере.");
         }
     }
 }
 public bool UpdateFinishedProduct(FinishedProduct finishedProduct)
 {
     try {
         _database.FinishedProduct.Update(finishedProduct);
         _database.Save();
         return(true);
     } catch (Exception e) {
         _logger.LogError(null, e.Message, e);
         return(false);
     }
 }
Пример #7
0
        public async Task <IActionResult> Edit(FinishedProduct fin)
        {
            if (ModelState.IsValid)
            {
                _db.Update(fin);
                await _db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(fin));
        }
Пример #8
0
        public FinishedProduct NewFinishedProduct(ProductionOrderList order, Employee submited, Employee recieved, int quantity)
        {
            var finishedProduct = new FinishedProduct();

            finishedProduct.OrderId     = order.Id;
            finishedProduct.SubmittedBy = submited.Id;
            finishedProduct.RecievedBy  = recieved.Id;
            finishedProduct.Quantity    = quantity;

            return(finishedProduct);
        }
        // GET: /ProductMaster/Delete/5

        public ActionResult Delete(int id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FinishedProduct FinishedProduct = db.FinishedProduct.Find(id);

            if (FinishedProduct == null)
            {
                return(HttpNotFound());
            }
            ReasonViewModel vm = new ReasonViewModel()
            {
                id = id,
            };

            return(PartialView("_Reason", vm));
        }
        // GET: /ProductMaster/Edit/5

        public ActionResult Edit(int id)
        {
            FinishedProduct          pt = _FinishedProductService.Find(id);
            FinishedProductViewModel vm = AutoMapper.Mapper.Map <FinishedProduct, FinishedProductViewModel>(pt);
            var         pstid           = (int)ProductSizeTypeConstants.StandardSize;
            ProductSize tem             = new ProductSizeService(_unitOfWork).FindProductSize(pstid, pt.ProductId);
            ProductType typ             = new ProductTypeService(_unitOfWork).GetTypeForProduct(id);

            vm.ProductTypeId   = typ.ProductTypeId;
            vm.ProductTypeName = typ.ProductTypeName;
            ViewBag.Sample     = vm.IsSample;
            if (tem != null)
            {
                vm.SizeId = tem.SizeId;
            }
            if (pt == null)
            {
                return(HttpNotFound());
            }
            return(View("Create", vm));
        }
Пример #11
0
        public Order ConsumeOrder(int IdCompany, EnsolStockMovement finishedProduct, List <EnsolStockMovement> rawMaterials)
        {
            List <Order> ot = new List <Order>();

            if (finishedProductDal.Exists(finishedProduct.ProcessOrder))
            {
                Order           order = new Order();
                FinishedProduct prod  = finishedProductDal.Get(finishedProduct.ProcessOrder).First();
                order.FinishedProduct = finishedProduct;
                order.Type            = prod.OrderType;
                order.Number          = prod.OrderNumber;
                ot.Add(order);
            }
            else
            {
                ot = orderDal.SPECreaOT((CompanyEnum)IdCompany, finishedProduct.Code, finishedProduct.Quantity, finishedProduct.ICAStorageCode, "usuario", -1, "terminal");
                ot.First().FinishedProduct = orderDal.SPECreaICA((CompanyEnum)IdCompany, ot.First().Type, ot.First().Number, finishedProduct.Batch, finishedProduct.ProcessOrder, finishedProduct.Code, finishedProduct.Description, finishedProduct.Quantity, finishedProduct.ICAStorageCode, "usuario", -1, "terminal").First();

                finishedProductDal.Create(finishedProduct, ot.First().FinishedProduct.ECA, ot.First().Type, ot.First().Number);
            }

            ot.First().RawMaterials = orderDal.SPECreaECA((CompanyEnum)IdCompany, ot.First().Type, ot.First().Number, rawMaterials, "usuario", -1, "terminal");
            foreach (EnsolStockMovement item in ot.First().RawMaterials)
            {
                if (!string.IsNullOrEmpty(item.ECA))
                {
                    rawMaterialsDal.Create(item, ot.First().Type, ot.First().Number);
                }
            }

            if (!ot.First().RawMaterials.Where(w => string.IsNullOrEmpty(w.ECA)).Any())
            {
                orderDal.SPECierreOT((CompanyEnum)IdCompany, ot.First().Type, ot.First().Number, "usuario", -1, "terminal");
            }

            return(ot.First());
        }
        public ActionResult CopyFromExisting(CopyFromExistingDesignConsumptionViewModel vm)
        {
            if (ModelState.IsValid)
            {
                Product OldProduct = _ProductService.Find(vm.ProductId);

                FinishedProduct NewProduct   = new FinishedProduct();
                ProductGroup    productgroup = new ProductGroupService(_unitOfWork).Find(vm.ProductGroupId);

                if (productgroup.ProductGroupName.Length > 20)
                {
                    NewProduct.ProductCode = productgroup.ProductGroupName.ToString().Substring(0, 20);
                }
                else
                {
                    NewProduct.ProductCode = productgroup.ProductGroupName.ToString().Substring(0, productgroup.ProductGroupName.Length);
                }

                NewProduct.ProductName        = productgroup.ProductGroupName;
                NewProduct.ProductGroupId     = new ProductGroupService(_unitOfWork).Find(ProductGroupConstants.Bom).ProductGroupId;
                NewProduct.DivisionId         = (int)System.Web.HttpContext.Current.Session["DivisionId"];
                NewProduct.IsActive           = true;
                NewProduct.CreatedDate        = DateTime.Now;
                NewProduct.ModifiedDate       = DateTime.Now;
                NewProduct.CreatedBy          = User.Identity.Name;
                NewProduct.ModifiedBy         = User.Identity.Name;
                NewProduct.ReferenceDocTypeId = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.ProductGroup).DocumentTypeId;
                NewProduct.ReferenceDocId     = productgroup.ProductGroupId;
                NewProduct.IsSample           = false;
                NewProduct.ObjectState        = Model.ObjectState.Added;
                _ProductService.Create(NewProduct);



                var ProductList = (from p in db.Product
                                   where p.ProductGroupId == productgroup.ProductGroupId
                                   select new
                {
                    ProductId = p.ProductId
                }).ToList();

                foreach (var item in ProductList)
                {
                    BomDetail bomdetail = new BomDetail();

                    bomdetail.BaseProductId  = item.ProductId;
                    bomdetail.BatchQty       = 1;
                    bomdetail.ConsumptionPer = 100;
                    bomdetail.ProcessId      = new ProcessService(_unitOfWork).Find(ProcessConstants.Weaving).ProcessId;
                    bomdetail.ProductId      = NewProduct.ProductId;
                    bomdetail.Qty            = 1;

                    bomdetail.CreatedDate  = DateTime.Now;
                    bomdetail.ModifiedDate = DateTime.Now;
                    bomdetail.CreatedBy    = User.Identity.Name;
                    bomdetail.ModifiedBy   = User.Identity.Name;
                    bomdetail.ObjectState  = Model.ObjectState.Added;
                    _BomDetailService.Create(bomdetail);
                }


                IEnumerable <BomDetail> BomDetailList = new BomDetailService(_unitOfWork).GetBomDetailList(OldProduct.ProductId);

                foreach (BomDetail item in BomDetailList)
                {
                    BomDetail bomdetail = new BomDetail();
                    bomdetail.BaseProductId  = NewProduct.ProductId;
                    bomdetail.BatchQty       = item.BatchQty;
                    bomdetail.ConsumptionPer = item.ConsumptionPer;
                    bomdetail.Dimension1Id   = item.Dimension1Id;
                    bomdetail.ProcessId      = item.ProcessId;
                    bomdetail.ProductId      = item.ProductId;
                    bomdetail.Qty            = item.Qty;
                    bomdetail.CreatedDate    = DateTime.Now;
                    bomdetail.ModifiedDate   = DateTime.Now;
                    bomdetail.CreatedBy      = User.Identity.Name;
                    bomdetail.ModifiedBy     = User.Identity.Name;
                    bomdetail.ObjectState    = Model.ObjectState.Added;
                    _BomDetailService.Create(bomdetail);
                }


                try
                {
                    _unitOfWork.Save();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    ModelState.AddModelError("", message);
                    return(PartialView("CopyFromExisting", vm));
                }

                return(Json(new { success = true, Url = "/DesignConsumptionHeader/Edit/" + NewProduct.ProductId }));
            }

            return(PartialView("CopyFromExisting", vm));
        }
        public ActionResult Create(DesignConsumptionHeaderViewModel svm)
        {
            if (ModelState.IsValid)
            {
                if (svm.BaseProductId == 0)
                {
                    FinishedProduct product = new FinishedProduct();

                    if (svm.ProductGroupName.Length > 20)
                    {
                        product.ProductCode = svm.ProductGroupName.ToString().Substring(0, 20);
                    }
                    else
                    {
                        product.ProductCode = svm.ProductGroupName.ToString().Substring(0, svm.ProductGroupName.Length);
                    }

                    product.ProductName        = svm.ProductGroupName;
                    product.ProductGroupId     = new ProductGroupService(_unitOfWork).Find(ProductGroupConstants.Bom).ProductGroupId;
                    product.DivisionId         = (int)System.Web.HttpContext.Current.Session["DivisionId"];
                    product.IsActive           = true;
                    product.ReferenceDocTypeId = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.ProductGroup).DocumentTypeId;
                    product.ReferenceDocId     = svm.ProductGroupId;


                    product.IsSample = false;

                    product.CreatedDate  = DateTime.Now;
                    product.ModifiedDate = DateTime.Now;
                    product.CreatedBy    = User.Identity.Name;
                    product.ModifiedBy   = User.Identity.Name;
                    product.ObjectState  = Model.ObjectState.Added;
                    _ProductService.Create(product);


                    ProductGroup ProductGroup = new ProductGroupService(_unitOfWork).Find(svm.ProductGroupName);
                    if (ProductGroup != null)
                    {
                        var ProductList = (from p in db.Product
                                           where p.ProductGroupId == ProductGroup.ProductGroupId
                                           select new
                        {
                            ProductId = p.ProductId
                        }).ToList();

                        foreach (var item in ProductList)
                        {
                            BomDetail bomdetail = new BomDetail();

                            bomdetail.BaseProductId  = item.ProductId;
                            bomdetail.BatchQty       = 1;
                            bomdetail.ConsumptionPer = 100;
                            bomdetail.ProcessId      = new ProcessService(_unitOfWork).Find(ProcessConstants.Weaving).ProcessId;
                            bomdetail.ProductId      = product.ProductId;
                            bomdetail.Qty            = 1;

                            bomdetail.CreatedDate  = DateTime.Now;
                            bomdetail.ModifiedDate = DateTime.Now;
                            bomdetail.CreatedBy    = User.Identity.Name;
                            bomdetail.ModifiedBy   = User.Identity.Name;
                            bomdetail.ObjectState  = Model.ObjectState.Added;
                            _BomDetailService.Create(bomdetail);
                        }
                    }


                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View(svm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = new DocumentTypeService(_unitOfWork).Find(MasterDocTypeConstants.DesignConsumption).DocumentTypeId,
                        DocId        = product.ProductId,
                        ActivityType = (int)ActivityTypeContants.Added,
                    }));

                    //return RedirectToAction("Create").Success("Data saved successfully");
                    return(RedirectToAction("Edit", new { id = product.ProductId }).Success("Data saved Successfully"));
                }
                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                    Product product = _ProductService.Find(svm.BaseProductId);

                    Product ExRec = Mapper.Map <Product>(product);

                    if (svm.ProductGroupName.Length > 20)
                    {
                        product.ProductCode = svm.ProductGroupName.ToString().Substring(0, 20);
                    }
                    else
                    {
                        product.ProductCode = svm.ProductGroupName.ToString().Substring(0, svm.ProductGroupName.Length);
                    }


                    product.ProductName        = svm.ProductGroupName;
                    product.ReferenceDocTypeId = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.ProductGroup).DocumentTypeId;
                    product.ReferenceDocId     = svm.ProductGroupId;
                    product.ModifiedBy         = User.Identity.Name;
                    product.ModifiedDate       = DateTime.Now;

                    StringBuilder logstring = new StringBuilder();

                    _ProductService.Update(product);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = product,
                    });
                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", svm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = new DocumentTypeService(_unitOfWork).Find(MasterDocTypeConstants.DesignConsumption).DocumentTypeId,
                        DocId           = product.ProductId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        xEModifications = Modifications,
                    }));

                    return(RedirectToAction("Index").Success("Data saved successfully"));
                }
            }
            PrepareViewBag();
            return(View(svm));
        }
Пример #14
0
        /// <summary>
        /// Receive tag information function
        /// </summary>
        /// <param name="receivedAntennaDetails">Struct for storing tag information</param>
        /// <returns></returns>
        public int receivedTagInfo(ref AntennaDetails revMsg)
        {
            byte sLength = 255;     //
            string sData = "";
            byte[] btData = new byte[255];
            int bResult = 0;

            try
            {
                switch (SAAT_CODE_TYPE)
                {
                    case 0:
                        bResult = RFIDAPI.SAAT_6CRevEPCMsg(pHandle, out sAntenna, btData, out sLength);
                        break;
                    case 1:
                        bResult = RFIDAPI.SAAT_6CRevTIDMsg(pHandle, out sAntenna, btData, out sLength);
                        break;
                    case 2:
                        bResult = RFIDAPI.SAAT_6BRevUIDMsg(pHandle, out sAntenna, btData, out sLength);
                        break;
                }
            }
            catch
            {

            }

            if (bResult == 1 && sLength != 255)
            {
                //MessageBox.Show("" + sAntenna);
                revMsg.antennaNo = (int)sAntenna;
                for (byte bytei = 0; bytei < sLength; bytei++)
                    sData += btData[bytei].ToString("X2");
                revMsg.epcCode = sData;
                revMsg.nRepeatTime = 1;
                // MessageBox.Show("" + revMsg.nRepeatTime);
            }

            if (revMsg.antennaNo == 1 && revMsg.nRepeatTime == 1)
            {
                revMsg.nRepeatTime = revMsg.nRepeatTime - 1;

                WMScontext wms1 = new WMScontext();

                var epcCount = (from epc in wms1.FinishedProducts where epc.EPC == sData select epc).Count();
                if (epcCount == 0)
                {
                    FinishedProduct fp1 = new FinishedProduct
                    {

                        DateManufactured = DateTime.Now,
                        Status = (Status)Enum.Parse(typeof(Status), "OntheMove"),
                        EPC = sData
                    };

                    wms1.FinishedProducts.Add(fp1);
                    wms1.SaveChanges();
                }
            }
            if (revMsg.antennaNo == 2 && revMsg.nRepeatTime == 1)
            {
                revMsg.nRepeatTime = revMsg.nRepeatTime - 1;

                WMScontext wms = new WMScontext();
                var epcCount = (from epc in wms.FinishedProducts where epc.EPC == sData select epc).Count();
                if (epcCount == 0)
                {
                    FinishedProduct fp = new FinishedProduct
                    {

                        DateManufactured = DateTime.Now,
                        Status = (Status)Enum.Parse(typeof(Status), "Stored"),
                        EPC = sData
                    };

                    wms.FinishedProducts.Add(fp);
                    wms.SaveChanges();
                }
            }
            return bResult;
        }
        public ActionResult _CreatePost(DesignConsumptionLineViewModel svm)
        {
            if (ModelState.IsValid)
            {
                FinishedProduct product = new FinishedProduct();
                if (svm.BaseProductId == 0)
                {
                    ProductQuality Quality = new ProductQualityService(_unitOfWork).Find(svm.QualityName);

                    string ConsumptionProductName = "";
                    if (svm.ColourName != "" && svm.ColourName != null)
                    {
                        ConsumptionProductName = svm.DesignName.ToString().Trim() + "-" + svm.ColourName.ToString().Trim() + "-Bom";
                    }
                    else
                    {
                        ConsumptionProductName = svm.DesignName.ToString().Trim() + "-Bom";
                    }


                    int ProductGroupId = new ProductGroupService(_unitOfWork).Find(svm.DesignName).ProductGroupId;

                    product.ProductCode        = ConsumptionProductName;
                    product.ProductName        = ConsumptionProductName;
                    product.ProductGroupId     = new ProductGroupService(_unitOfWork).Find(ProductGroupConstants.Bom).ProductGroupId;
                    product.DivisionId         = (int)System.Web.HttpContext.Current.Session["DivisionId"];
                    product.IsActive           = true;
                    product.ReferenceDocTypeId = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.ProductGroup).DocumentTypeId;
                    product.ReferenceDocId     = ProductGroupId;
                    product.StandardWeight     = svm.Weight;
                    product.CreatedDate        = DateTime.Now;
                    product.ModifiedDate       = DateTime.Now;
                    product.CreatedBy          = User.Identity.Name;
                    product.ModifiedBy         = User.Identity.Name;
                    product.ObjectState        = Model.ObjectState.Added;

                    product.IsSample         = false;
                    product.ProductQualityId = Quality.ProductQualityId;
                    new ProductService(_unitOfWork).Create(product);


                    ProductGroup ProductGroup = new ProductGroupService(_unitOfWork).Find(svm.DesignName);
                    Colour       Colour       = new ColourService(_unitOfWork).Find(svm.ColourName);
                    if (ProductGroup != null && Colour != null)
                    {
                        var ProductList = (from p in db.FinishedProduct
                                           where p.ProductGroupId == ProductGroup.ProductGroupId && p.ColourId == Colour.ColourId
                                           select new
                        {
                            ProductId = p.ProductId
                        }).ToList();

                        foreach (var item in ProductList)
                        {
                            BomDetail bomdetail = new BomDetail();

                            bomdetail.BaseProductId  = item.ProductId;
                            bomdetail.BatchQty       = 1;
                            bomdetail.ConsumptionPer = 100;
                            bomdetail.ProcessId      = new ProcessService(_unitOfWork).Find(ProcessConstants.Weaving).ProcessId;
                            bomdetail.BaseProcessId  = svm.BaseProcessId;
                            bomdetail.ProductId      = product.ProductId;
                            bomdetail.Qty            = 1;

                            bomdetail.CreatedDate  = DateTime.Now;
                            bomdetail.ModifiedDate = DateTime.Now;
                            bomdetail.CreatedBy    = User.Identity.Name;
                            bomdetail.ModifiedBy   = User.Identity.Name;
                            bomdetail.ObjectState  = Model.ObjectState.Added;
                            _BomDetailService.Create(bomdetail);
                        }
                    }


                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = new DocumentTypeService(_unitOfWork).Find(MasterDocTypeConstants.DesignColourConsumption).DocumentTypeId,
                        DocId        = product.ProductId,
                        ActivityType = (int)ActivityTypeContants.Added,
                    }));
                }
                else
                {
                    //product = new FinishedProductService(_unitOfWork).Find(svm.BaseProductId);
                    product.ProductId = svm.BaseProductId;
                }

                if (svm.BomDetailId == 0)
                {
                    BomDetail bomdetail = new BomDetail();

                    bomdetail.BaseProductId  = svm.BaseProductId;
                    bomdetail.BatchQty       = 1;
                    bomdetail.ConsumptionPer = svm.ConsumptionPer;
                    bomdetail.Dimension1Id   = svm.Dimension1Id;
                    bomdetail.ProcessId      = new ProcessService(_unitOfWork).Find(ProcessConstants.Weaving).ProcessId;
                    bomdetail.BaseProcessId  = svm.BaseProcessId;
                    bomdetail.ProductId      = svm.ProductId;
                    bomdetail.Qty            = svm.Qty;

                    bomdetail.CreatedDate  = DateTime.Now;
                    bomdetail.ModifiedDate = DateTime.Now;
                    bomdetail.CreatedBy    = User.Identity.Name;
                    bomdetail.ModifiedBy   = User.Identity.Name;
                    bomdetail.ObjectState  = Model.ObjectState.Added;
                    _BomDetailService.Create(bomdetail);


                    if (bomdetail.BaseProductId == bomdetail.ProductId)
                    {
                        PrepareViewBag(svm);
                        //return View(svm).Danger(DataValidationMsg);
                        ModelState.AddModelError("", "Invalid Product is Selected!");
                        return(PartialView("_Create", svm));
                    }
                    try
                    {
                        _unitOfWork.Save();
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(PartialView("_Create", svm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.DesignConsumption).DocumentTypeId,
                        DocId        = bomdetail.BomDetailId,
                        ActivityType = (int)ActivityTypeContants.Added,
                    }));



                    if (svm.ContentType == "Main Contents")
                    {
                        return(RedirectToAction("_CreateMainContentForBaseProduct", new { id = product.ProductId }));
                    }
                    else if (svm.ContentType == "OverTuft Contents")
                    {
                        return(RedirectToAction("_CreateOverTuftContentForBaseProduct", new { id = product.ProductId }));
                    }
                    else
                    {
                        return(RedirectToAction("_CreateOtherContentForBaseProduct", new { id = product.ProductId }));
                    }
                }
                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                    BomDetail bomdetail = _BomDetailService.Find(svm.BomDetailId);

                    BomDetail ExRec = Mapper.Map <BomDetail>(bomdetail);

                    bomdetail.BaseProductId  = svm.BaseProductId;
                    bomdetail.BatchQty       = 1;
                    bomdetail.ConsumptionPer = svm.ConsumptionPer;
                    bomdetail.Dimension1Id   = svm.Dimension1Id;
                    bomdetail.ProductId      = svm.ProductId;
                    bomdetail.Qty            = svm.Qty;


                    bomdetail.ModifiedDate = DateTime.Now;
                    bomdetail.ModifiedBy   = User.Identity.Name;
                    bomdetail.ObjectState  = Model.ObjectState.Modified;
                    _BomDetailService.Update(bomdetail);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = bomdetail,
                    });
                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);
                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(PartialView("_Create", svm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.DesignConsumption).DocumentTypeId,
                        DocId           = bomdetail.BomDetailId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        xEModifications = Modifications,
                    }));

                    return(Json(new { success = true }));
                }
            }

            PrepareViewBag(svm);
            return(PartialView("_Create", svm));
        }
Пример #16
0
        private void GetFinishedProduct()
        {
            List <Building>        finishedBuildings = new List <Building>();
            List <StorageBuilding> storageBuildings  = new List <StorageBuilding>();

            foreach (Building building in player.buildings)
            {
                if (building.GetType() == typeof(Plantation))
                {
                    Plantation plantationBuilding = building as Plantation;
                    if (plantationBuilding.Maturity >= plantationBuilding.Seed.ProductionTime)
                    {
                        finishedBuildings.Add(plantationBuilding);
                    }
                }
                else if (building.GetType() == typeof(Livestock))
                {
                    Livestock livestockBuilding = building as Livestock;

                    if (livestockBuilding.Maturity >= livestockBuilding.Animal.ProductionTime)
                    {
                        finishedBuildings.Add(livestockBuilding);
                    }
                }
                else if (building.GetType() == typeof(StorageBuilding))
                {
                    StorageBuilding storageBuilding = building as StorageBuilding;
                    if (!storageBuilding.IsFull())
                    {
                        storageBuildings.Add(storageBuilding);
                    }
                }
            }

            if (finishedBuildings.Count == 0)
            {
                Console.WriteLine("No tienes ningun producto terminado.");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Elige uno de los productos disponibles:");
                for (int i = 0; i < finishedBuildings.Count; i++)
                {
                    Console.WriteLine($"({i + 1}) - {finishedBuildings[i].Name}");
                }

                Console.ResetColor();

                int userOption = Int32.Parse(Console.ReadLine());

                if (userOption < 1 || userOption > finishedBuildings.Count)
                {
                    Console.WriteLine("Opción no valida...");
                    return;
                }

                Building finishedBuilding = finishedBuildings[userOption - 1];


                if (finishedBuilding.GetType() == typeof(Plantation))
                {
                    Plantation plantationBuilding = finishedBuilding as Plantation;
                    double     terrainQuality     = 0;
                    int        fieldBlocks        = 0;
                    foreach (Terrain terrain in map.Terrains)
                    {
                        if (terrain.Building == plantationBuilding)
                        {
                            foreach (Block block in terrain.Blocks)
                            {
                                if (block.GetType() == typeof(FieldBlock))
                                {
                                    FieldBlock fieldBlock = block as FieldBlock;
                                    fieldBlocks    += 1;
                                    terrainQuality += fieldBlock.Quality;
                                }
                            }
                            break;
                        }
                    }

                    int seedPrice = market.GetPriceOfSeed(plantationBuilding.Seed);

                    terrainQuality = terrainQuality / fieldBlocks;
                    double terrainProportion = fieldBlocks / 100;

                    double price      = plantationBuilding.Health * terrainQuality * terrainProportion;
                    int    finalPrice = Convert.ToInt32(price) * seedPrice;

                    if (storageBuildings.Count == 0)
                    {
                        player.Money += finalPrice;
                        Console.WriteLine($"Plantación vendida a {finalPrice}");
                    }
                    else
                    {
                        Console.WriteLine("Elige uno de las bodegas disponibles:");
                        for (int i = 0; i < storageBuildings.Count; i++)
                        {
                            Console.WriteLine($"({i + 1}) - {storageBuildings[i].Name}");
                        }

                        int storageUserOption = Int32.Parse(Console.ReadLine());

                        if (storageUserOption < 1 || storageUserOption > storageBuildings.Count)
                        {
                            Console.WriteLine("Opción no valida...");
                            return;
                        }

                        Building        storageBuilding      = storageBuildings[userOption - 1];
                        int             storageBuildingIndex = player.Buildings.IndexOf(storageBuilding);
                        StorageBuilding userStorageBuilding  = player.Buildings[storageBuildingIndex] as StorageBuilding;
                        FinishedProduct finishedProduct      = new FinishedProduct(plantationBuilding.Seed.Name, finalPrice, seedPrice, plantationBuilding.Seed.WaterConsume, plantationBuilding.Seed.MinimumWaterLevel, plantationBuilding.Seed.PenaltyForLackOfWater, plantationBuilding.Seed.ProductionTime, plantationBuilding.Seed.ProbabilityOfIllness, plantationBuilding.Seed.PenaltyForIllness, Convert.ToInt32(terrainQuality));

                        userStorageBuilding.AddFinishedProduct(finishedProduct);
                        Console.WriteLine($"Plantación guardada en bodega {userStorageBuilding.Name}");
                    }

                    int plantationBuildingIndex = player.Buildings.IndexOf(plantationBuilding);
                    player.Buildings.RemoveAt(plantationBuildingIndex);
                }
                else if (finishedBuilding.GetType() == typeof(Livestock))
                {
                    Livestock livestockBuilding = finishedBuilding as Livestock;

                    int    fieldBlocks    = 0;
                    double terrainQuality = 0;
                    foreach (Terrain terrain in map.Terrains)
                    {
                        if (terrain.Building == livestockBuilding)
                        {
                            foreach (Block block in terrain.Blocks)
                            {
                                if (block.GetType() == typeof(FieldBlock))
                                {
                                    FieldBlock fieldBlock = block as FieldBlock;
                                    fieldBlocks    += 1;
                                    terrainQuality += fieldBlock.Quality;
                                }
                            }
                            break;
                        }
                    }

                    terrainQuality = terrainQuality / fieldBlocks;

                    int    animalPrice       = market.GetPriceOfAnimal(livestockBuilding.Animal);
                    double terrainProportion = fieldBlocks / 100;
                    double originalUnits     = 10 * terrainProportion;

                    double price      = (livestockBuilding.Health * livestockBuilding.Units) / originalUnits;
                    int    finalPrice = Convert.ToInt32(price) * animalPrice;

                    if (storageBuildings.Count == 0)
                    {
                        player.Money += finalPrice;
                        Console.WriteLine($"Ganado vendido a {finalPrice}");
                    }
                    else
                    {
                        Console.WriteLine("Elige uno de las bodegas disponibles:");
                        for (int i = 0; i < storageBuildings.Count; i++)
                        {
                            Console.WriteLine($"({i + 1}) - {storageBuildings[i].Name}");
                        }

                        int storageUserOption = Int32.Parse(Console.ReadLine());

                        if (storageUserOption < 1 || storageUserOption > storageBuildings.Count)
                        {
                            Console.WriteLine("Opción no valida...");
                            return;
                        }

                        Building        storageBuilding      = storageBuildings[userOption - 1];
                        int             storageBuildingIndex = player.Buildings.IndexOf(storageBuilding);
                        StorageBuilding userStorageBuilding  = player.Buildings[storageBuildingIndex] as StorageBuilding;
                        FinishedProduct finishedProduct      = new FinishedProduct(livestockBuilding.Animal.Name, finalPrice, animalPrice, livestockBuilding.Animal.WaterConsume, livestockBuilding.Animal.MinimumWaterLevel, livestockBuilding.Animal.PenaltyForLackOfWater, livestockBuilding.Animal.ProductionTime, livestockBuilding.Animal.ProbabilityOfIllness, livestockBuilding.Animal.PenaltyForIllness, Convert.ToInt32(terrainQuality));

                        userStorageBuilding.AddFinishedProduct(finishedProduct);
                        Console.WriteLine($"Ganado guardado en bodega {userStorageBuilding.Name}");
                    }

                    int liveStockBuildingIndex = player.Buildings.IndexOf(livestockBuilding);
                    player.Buildings.RemoveAt(liveStockBuildingIndex);
                }
                else
                {
                    return;
                }
            }
        }
Пример #17
0
 public FinishedProduct Add(FinishedProduct p)
 {
     _unitOfWork.Repository <FinishedProduct>().Add(p);
     return(p);
 }
        public ActionResult Post(FinishedProductViewModel vm)
        {
            if (ModelState.IsValid)
            {
                if (vm.ProductId <= 0)
                {
                    FinishedProduct pt = AutoMapper.Mapper.Map <FinishedProductViewModel, FinishedProduct>(vm);
                    pt.CreatedDate  = DateTime.Now;
                    pt.ModifiedDate = DateTime.Now;
                    pt.CreatedBy    = User.Identity.Name;
                    pt.ModifiedBy   = User.Identity.Name;
                    pt.UnitId       = UnitConstants.Pieces;
                    pt.ObjectState  = Model.ObjectState.Added;
                    _FinishedProductService.Create(pt);

                    if (!(vm.SizeId <= 0))
                    {
                        ProductSize ps    = new ProductSize();
                        var         pstid = (int)ProductSizeTypeConstants.StandardSize;
                        ps.SizeId            = vm.SizeId;
                        ps.ProductId         = vm.ProductId;
                        ps.ProductSizeTypeId = pstid;
                        ps.CreatedBy         = User.Identity.Name;
                        ps.ModifiedBy        = User.Identity.Name;
                        ps.CreatedDate       = DateTime.Now;
                        ps.ModifiedDate      = DateTime.Now;
                        new ProductSizeService(_unitOfWork).Create(ps);
                    }
                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", vm));
                    }



                    #region

                    //Saving Images if any uploaded after UnitOfWorkSave

                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        //For checking the first time if the folder exists or not-----------------------------
                        string uploadfolder;
                        int    MaxLimit;
                        int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit);
                        var x = (from iid in db.Counter
                                 select iid).FirstOrDefault();
                        if (x == null)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            Counter img = new Counter();
                            img.ImageFolderName = uploadfolder;
                            img.ModifiedBy      = User.Identity.Name;
                            img.CreatedBy       = User.Identity.Name;
                            img.ModifiedDate    = DateTime.Now;
                            img.CreatedDate     = DateTime.Now;
                            new CounterService(_unitOfWork).Create(img);
                            _unitOfWork.Save();
                        }

                        else
                        {
                            uploadfolder = x.ImageFolderName;
                        }


                        //For checking if the image contents length is greater than 100 then create a new folder------------------------------------

                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder));
                        }

                        int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length;

                        if (count >= MaxLimit)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            var u = new CounterService(_unitOfWork).Find(x.CounterId);
                            u.ImageFolderName = uploadfolder;
                            new CounterService(_unitOfWork).Update(u);
                            _unitOfWork.Save();
                        }


                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, vm.ProductName + "_" + filename);

                            //pfile.SaveAs(filecontent);
                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));


                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, vm.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, vm.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }

                            //var tempsave = _FinishedProductService.Find(pt.ProductId);

                            pt.ImageFileName   = pt.ProductName + "_" + filename + temp2;
                            pt.ImageFolderName = uploadfolder;
                            pt.ObjectState     = Model.ObjectState.Modified;
                            _FinishedProductService.Update(pt);
                            _unitOfWork.Save();
                        }
                    }

                    #endregion



                    return(RedirectToAction("Create", new { id = vm.ProductTypeId, sample = vm.IsSample }).Success("Data saved successfully"));
                }
                else
                {
                    FinishedProduct temp = _FinishedProductService.Find(vm.ProductId);
                    temp.ProductName             = vm.ProductName;
                    temp.ProductCode             = vm.ProductCode;
                    temp.ProductGroupId          = vm.ProductGroupId;
                    temp.ProductCategoryId       = vm.ProductCategoryId;
                    temp.ProductCollectionId     = vm.ProductCollectionId;
                    temp.SampleId                = vm.SampleId;
                    temp.CounterNo               = vm.CounterNo;
                    temp.ProductQualityId        = vm.ProductQualityId;
                    temp.OriginCountryId         = vm.OriginCountryId;
                    temp.ProductDesignId         = vm.ProductDesignId;
                    temp.ProductInvoiceGroupId   = vm.ProductInvoiceGroupId;
                    temp.ProductDesignPatternId  = vm.ProductDesignPatternId;
                    temp.DrawBackTariffHeadId    = vm.DrawBackTariffHeadId;
                    temp.ProductStyleId          = vm.ProductStyleId;
                    temp.DescriptionOfGoodsId    = vm.DescriptionOfGoodsId;
                    temp.ColourId                = vm.ColourId;
                    temp.StandardCost            = vm.StandardCost;
                    temp.ProductManufacturerId   = vm.ProductManufacturerId;
                    temp.StandardWeight          = vm.StandardWeight;
                    temp.ProcessSequenceHeaderId = vm.ProcessSequenceHeaderId;
                    temp.CBM                  = vm.CBM;
                    temp.ContentId            = vm.ContentId;
                    temp.Tags                 = vm.Tags;
                    temp.FaceContentId        = vm.FaceContentId;
                    temp.ProductSpecification = vm.ProductSpecification;
                    temp.IsActive             = vm.IsActive;

                    temp.ModifiedDate = DateTime.Now;
                    temp.ModifiedBy   = User.Identity.Name;
                    temp.ObjectState  = Model.ObjectState.Modified;
                    _FinishedProductService.Update(temp);

                    if (!(vm.SizeId <= 0))
                    {
                        var         pstid = (int)ProductSizeTypeConstants.StandardSize;;
                        ProductSize ps    = new ProductSizeService(_unitOfWork).FindProductSize(pstid, vm.ProductId);
                        if (ps != null)
                        {
                            ps.SizeId       = vm.SizeId;
                            ps.ProductId    = vm.ProductId;
                            ps.ModifiedDate = DateTime.Now;
                            ps.ModifiedBy   = User.Identity.Name;
                            ps.ObjectState  = Model.ObjectState.Modified;
                            new ProductSizeService(_unitOfWork).Update(ps);
                        }
                        else
                        {
                            ProductSize pss  = new ProductSize();
                            var         psid = (int)ProductSizeTypeConstants.StandardSize;
                            pss.ProductId         = vm.ProductId;
                            pss.SizeId            = vm.SizeId;
                            pss.ProductSizeTypeId = psid;
                            pss.CreatedBy         = User.Identity.Name;
                            pss.ModifiedBy        = User.Identity.Name;
                            pss.CreatedDate       = DateTime.Now;
                            pss.ModifiedDate      = DateTime.Now;
                            new ProductSizeService(_unitOfWork).Create(pss);
                        }
                    }
                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", vm));
                    }


                    #region

                    //Saving Image if file is uploaded
                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        string uploadfolder = temp.ImageFolderName;
                        string tempfilename = temp.ImageFileName;
                        if (uploadfolder == null)
                        {
                            var x = (from iid in db.Counter
                                     select iid).FirstOrDefault();
                            if (x == null)
                            {
                                uploadfolder = System.Guid.NewGuid().ToString();
                                Counter img = new Counter();
                                img.ImageFolderName = uploadfolder;
                                img.ModifiedBy      = User.Identity.Name;
                                img.CreatedBy       = User.Identity.Name;
                                img.ModifiedDate    = DateTime.Now;
                                img.CreatedDate     = DateTime.Now;
                                new CounterService(_unitOfWork).Create(img);
                                _unitOfWork.Save();
                            }
                            else
                            {
                                uploadfolder = x.ImageFolderName;
                            }
                        }
                        //Deleting Existing Images

                        var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename);
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename));
                        }

                        //Deleting Thumbnail Image:

                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename));
                        }

                        //Deleting Medium Image:
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename));
                        }

                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, temp.ProductName + "_" + filename);

                            //pfile.SaveAs(filecontent);

                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));

                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, temp.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, temp.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }
                        }
                        var temsave = _FinishedProductService.Find(temp.ProductId);
                        temsave.ImageFileName   = temsave.ProductName + "_" + filename + temp2;
                        temsave.ImageFolderName = uploadfolder;
                        _FinishedProductService.Update(temsave);
                        _unitOfWork.Save();
                    }

                    #endregion



                    return(RedirectToAction("Index", new { id = vm.ProductTypeId, sample = vm.IsSample }).Success("Data saved successfully"));
                }
            }
            return(View("Create", vm));
        }
Пример #19
0
        public bool TryAddFinishedProducts(FinishedProduct[] aPockets)
        {
            logger.Info("Добавление информации о ЕГП.");
            try {
                var connection = connectionHolder.WaitConnection();

                var properties = OracleCommands.Default;
                using (var transaction = connection.BeginTransaction())
                using (var command = new OracleCommand(properties.InsertFinishedProductCommand)) {
                    command.Connection = connection;
                    command.Transaction = transaction;
                    command.Parameters.Add(properties.pMeltId, OracleDbType.Int32);
                    command.Parameters.Add(properties.pFurnaceNumber, OracleDbType.Int32);
                    command.Parameters.Add(properties.pMeltNumber, OracleDbType.Int32);
                    command.Parameters.Add(properties.pStackNumber, OracleDbType.Int32);
                    command.Parameters.Add(properties.pWeight, OracleDbType.Int32);
                    command.Parameters.Add(properties.pReceiptTime, OracleDbType.Date);

                    foreach (var aPocket in aPockets) {
                        command.Parameters[properties.pMeltId].Value = aPocket.MeltId;
                        command.Parameters[properties.pFurnaceNumber].Value = aPocket.FurnaceNumber;
                        command.Parameters[properties.pMeltNumber].Value = aPocket.CastNumber;
                        command.Parameters[properties.pStackNumber].Value = aPocket.StackNumber;
                        command.Parameters[properties.pWeight].Value = aPocket.Weight;
                        command.Parameters[properties.pReceiptTime].Value = aPocket.ReceiveTime;
                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }

                return true;
            }
            catch (Exception ex) {
                logger.Error("Ошибка при добавлении ЕГП: " + ex.Message);
                return false;
            }
            finally {
                connectionHolder.ReleaseConnection();
            }
        }
Пример #20
0
        /// <summary>
        /// Пытается получить информацию о ЕГП.
        /// </summary>
        /// <param name="aPocket">ЕГП.</param>
        /// <returns>True - если получение успешно, false - иначе.</returns>
        private bool TryGetFinishedProduct(out FinishedProduct aPocket)
        {
            try {
                aPocket = new FinishedProduct();
                aPocket.FurnaceNumber = Convert.ToInt32(tag[DB620_FURNACE_NUM].ReadCurrentValue());
                aPocket.CastNumber = Convert.ToInt32(tag[DB620_CAST_NUM].ReadCurrentValue());
                aPocket.MeltId = Convert.ToInt32(tag[DB620_MELT_ID].ReadCurrentValue());
                aPocket.StackNumber = Convert.ToInt32(tag[DB620_ITEM_NO].ReadCurrentValue());
                aPocket.Weight = Convert.ToInt32(tag[DB620_WEIGHT].ReadCurrentValue());
                aPocket.ReceiveTime = DateTime.Now;

                return true;
            }
            catch (Exception ex) {
                aPocket = null;
                logger.Error("Ошибка во время получения данных ЕГП: " + ex.Message);
                return false;
            }
        }
Пример #21
0
 public void Update(FinishedProduct p)
 {
     p.ObjectState = ObjectState.Modified;
     _unitOfWork.Repository <FinishedProduct>().Update(p);
 }
Пример #22
0
 public void Delete(FinishedProduct p)
 {
     _unitOfWork.Repository <FinishedProduct>().Delete(p);
 }
Пример #23
0
 public FinishedProduct Create(FinishedProduct p)
 {
     p.ObjectState = ObjectState.Added;
     _unitOfWork.Repository <FinishedProduct>().Insert(p);
     return(p);
 }
Пример #24
0
        /// <summary>
        /// Receive tag information function
        /// </summary>
        /// <param name="receivedAntennaDetails">Struct for storing tag information</param>
        /// <returns></returns>
        public int receivedTagInfo(ref AntennaDetails revMsg)
        {
            byte sLength = 255;     //
            string sData = "";
            byte[] btData = new byte[255];
            int bResult = 0;

            try
            {
                switch (SAAT_CODE_TYPE)
                {
                    case 0:
                        bResult = RFIDAPI.SAAT_6CRevEPCMsg(pHandle, out sAntenna, btData, out sLength);
                        break;
                    case 1:
                        bResult = RFIDAPI.SAAT_6CRevTIDMsg(pHandle, out sAntenna, btData, out sLength);
                        break;
                    case 2:
                        bResult = RFIDAPI.SAAT_6BRevUIDMsg(pHandle, out sAntenna, btData, out sLength);
                        break;
                }
            }
            catch
            {

            }

            if (bResult == 1 && sLength != 255)
            {
                //MessageBox.Show("" + sAntenna);
                revMsg.antennaNo = (int)sAntenna;
                for (byte bytei = 0; bytei < sLength; bytei++)
                    sData += btData[bytei].ToString("X2");
                revMsg.epcCode = sData;
                revMsg.nRepeatTime = 1;
               // MessageBox.Show("" + revMsg.nRepeatTime);
            }

            if (revMsg.antennaNo == 1 && revMsg.nRepeatTime == 1)
            {
                revMsg.nRepeatTime = revMsg.nRepeatTime - 1;

                WMScontext wms = new WMScontext();
                FinishedProduct fp = new FinishedProduct
                     {
                         DateManufactured = DateTime.Now,
                         Status = (Status)Enum.Parse(typeof(Status),"Stored"),
                         EPC = sData
                     };

                wms.FinishedProducts.Add(fp);
                wms.SaveChanges();

                //try
                //{
                //    string MyConnectionString = "Server=localhost;Database=rfid_warehouse_management_system;uid=root;password=;";
                //    MySqlConnection connection = new MySqlConnection(MyConnectionString);
                //    connection.Open();

                //    MySqlCommand logincmd = connection.CreateCommand();
                //    logincmd.CommandText = "SELECT count(epc) from `finished_product` where epc=@epc";
                //    logincmd.Parameters.AddWithValue("@epc", sData);
                //    int logincount = Convert.ToInt32(logincmd.ExecuteScalar());

                //    DateTime dT = new DateTime();
                //    dT = DateTime.Now;

                //    string status = "stored";

                //    if (logincount == 0)
                //    {

                //        MySqlCommand insertcmd = connection.CreateCommand();
                //        insertcmd.CommandText = "INSERT INTO `finished_product` (epc, date_manufactured, status, id_manufacturer_has_production_line) values(@epc, @date_manufactured, @status, @id_manufacturer_has_production_line);";
                //        insertcmd.Parameters.AddWithValue("@epc", sData);
                //        insertcmd.Parameters.AddWithValue("@date_manufactured", dT);
                //        insertcmd.Parameters.AddWithValue("@status", status);
                //        insertcmd.Parameters.AddWithValue("@id_manufacturer_has_production_line", 18);
                //        insertcmd.ExecuteNonQuery();

                //        MySqlCommand displaycmd = connection.CreateCommand();
                //        displaycmd.CommandText = "SELECT finished_product.epc AS `RFID`, finished_product.date_manufactured AS `Manufactured`, finished_product.status AS `Status`, manufacturer_has_production_line.production_line_no AS `Production Line No.`, manufacturer_has_production_line.id_product FROM finished_product INNER JOIN manufacturer_has_production_line ON finished_product.id_manufacturer_has_production_line = manufacturer_has_production_line.id_manufacturer_has_production_line;";

                //        MySqlDataAdapter rfidadap = new MySqlDataAdapter(displaycmd);

                //        DataSet rfidds = new DataSet();

                //        rfidadap.Fill(rfidds);
                //        //dataGridRFID.DataSource = rfidds.Tables[0].DefaultView;
                //        connection.Close();

                //    }
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message);
                //}
            }
            if (revMsg.antennaNo == 2 && revMsg.nRepeatTime == 1)
            {
                revMsg.nRepeatTime = revMsg.nRepeatTime - 1;

                WMScontext wms = new WMScontext();
                FinishedProduct fp = new FinishedProduct
                {
                    DateManufactured = DateTime.Now,
                    Status = (Status)Enum.Parse(typeof(Status), "OntheMove"),
                    EPC = sData
                };

                wms.FinishedProducts.Add(fp);
                wms.SaveChanges();
                //try
                //{
                //    string MyConnectionString = "Server=localhost;Database=rfid_warehouse_management_system;uid=root;password=;";
                //    MySqlConnection connection = new MySqlConnection(MyConnectionString);
                //    connection.Open();

                //    MySqlCommand logincmd = connection.CreateCommand();
                //    logincmd.CommandText = "SELECT count(epc) from `finished_product` where epc=@epc";
                //    logincmd.Parameters.AddWithValue("@epc", sData);
                //    int logincount = Convert.ToInt32(logincmd.ExecuteScalar());

                //    DateTime dT = new DateTime();
                //    dT = DateTime.Now;

                //    string status = "stored";

                //    if (logincount == 0)
                //    {

                //        MySqlCommand insertcmd = connection.CreateCommand();
                //        insertcmd.CommandText = "INSERT INTO `finished_product` (epc, date_manufactured, status, id_manufacturer_has_production_line) values(@epc, @date_manufactured, @status, @id_manufacturer_has_production_line);";
                //        insertcmd.Parameters.AddWithValue("@epc", sData);
                //        insertcmd.Parameters.AddWithValue("@date_manufactured", dT);
                //        insertcmd.Parameters.AddWithValue("@status", status);
                //        insertcmd.Parameters.AddWithValue("@id_manufacturer_has_production_line", 19);
                //        insertcmd.ExecuteNonQuery();

                //        MySqlCommand displaycmd = connection.CreateCommand();
                //        displaycmd.CommandText = "SELECT finished_product.epc AS `RFID`, finished_product.date_manufactured AS `Manufactured`, finished_product.status AS `Status`, manufacturer_has_production_line.production_line_no AS `Production Line No.`, manufacturer_has_production_line.id_product FROM finished_product INNER JOIN manufacturer_has_production_line ON finished_product.id_manufacturer_has_production_line = manufacturer_has_production_line.id_manufacturer_has_production_line;";

                //        MySqlDataAdapter rfidadap = new MySqlDataAdapter(displaycmd);

                //        DataSet rfidds = new DataSet();

                //        rfidadap.Fill(rfidds);
                //        //dataGridRFID.DataSource = rfidds.Tables[0].DefaultView;
                //        connection.Close();

                //    }
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message);
                //}
            }
            return bResult;
        }
Пример #25
0
        /// <summary>
        /// Проверяет записаны ли данные о новой ЕГП.
        /// </summary>
        /// <returns>True - если данные обновлены, false - иначе.</returns>
        private bool IsNewPacketAvailable()
        {
            logger.Info("Проверка новых данных ЕГП...");
            var isDataReady = Convert.ToBoolean(tag[DB620_DATA_READY].ReadCurrentValue());
            if (isDataReady) {
                FinishedProduct currentPacket = null;
                if (TryGetFinishedProduct(out currentPacket)) {
                    // Если записанные в контроллере данные не соответствуют последнему ЕГП.
                    if (currentPacket.Equals(lastReceivedPacket) == false) {
                        lastReceivedPacket = currentPacket;
                        return true;
                    }
                }
            }

            logger.Info("Данные ЕГП не обновлены в контроллере.");
            return false;
        }
Пример #26
0
        public FinishedProduct Find(string ProductName)
        {
            FinishedProduct p = _unitOfWork.Repository <FinishedProduct>().Query().Get().Where(i => i.ProductName == ProductName).FirstOrDefault();

            return(p);
        }
Пример #27
0
 public FinishedProductsViewModel FinishedProductForView(FinishedProduct finishedProduct)
 {
     throw new NotImplementedException();
 }
Пример #28
0
 public bool TryAddFinishedProduct(FinishedProduct aPocket)
 {
     return TryAddFinishedProducts(new[] {aPocket});
 }