/*===UPDATE CONTROLLER===*/
 public bool updatePriceHistory(string productCode, float price, DateTime effectiveDate)
 {
     if (!checkExistPriceHistory(productCode, price, effectiveDate))
     {
         try
         {
             using (var db = new CMART2Entities1())
             {
                 var priceHistory = new PriceHistory
                 {
                     ProductCode   = productCode,
                     Price         = price,
                     EffectiveDate = effectiveDate
                 };
                 db.PriceHistories.Add(priceHistory);
                 //var priceHistory = db.PriceHistories.Single(s => s.ProductCode == productCode);
                 //priceHistory.Price = price;
                 //priceHistory.EffectiveDate = effectiveDate;
                 //db.Entry(priceHistory).State = EntityState.Modified;
                 db.SaveChanges();
                 return(true);
             }
         }
         catch (Exception)
         {
             return(false);
         }
     }
     return(false);
 }
 public bool insertNewPriceHistory(string productCode, float price, DateTime effectiveDate)
 {
     if (!checkExistPriceHistory(productCode, price, effectiveDate))
     {
         try
         {
             using (var db = new CMART2Entities1())
             {
                 var priceHistory = new PriceHistory
                 {
                     ProductCode   = productCode,
                     Price         = price,
                     EffectiveDate = effectiveDate
                 };
                 db.PriceHistories.Add(priceHistory);
                 db.SaveChanges();
                 return(true);
             }
         }
         catch (Exception)
         {
             return(false);
         }
     }
     return(false);
 }
        private void WaitingForPriceAndVolume()
        {
            Receive <PriceAndVolumeSnapshot>(s =>
            {
                if (s.PriceUpdates.Length == 0) // empty set - no price data yet
                {
                    _history = new PriceHistory(_tickerSymbol, ImmutableSortedSet <IPriceUpdate> .Empty);
                    _log.Info("Received empty price history for [{0}]", _history.StockId);
                }
                else
                {
                    _history = new PriceHistory(_tickerSymbol, s.PriceUpdates.ToImmutableSortedSet());
                    _log.Info("Received recent price history for [{0}] - current price is [{1}] as of [{2}]", _history.StockId, _history.CurrentPrice, _history.Until);
                }

                _tickerEntity = Sender;
                _mediator.Tell(new Subscribe(_priceTopic, Self));
            });

            Receive <SubscribeAck>(ack =>
            {
                _log.Info("Subscribed to {0} - ready for real-time processing.", _priceTopic);
                Become(Processing);
                Context.Watch(_tickerEntity);
                Context.SetReceiveTimeout(null);
            });

            Receive <ReceiveTimeout>(_ =>
            {
                _log.Warning("Received no initial price values for [{0}] from source of truth after 5s. Retrying..", _tickerSymbol);
                _priceActorGateway.Tell(new FetchPriceAndVolume(_tickerSymbol));
            });
        }
Esempio n. 4
0
        public static void VerifyPricesFinish(IRepositoryWrapper _repositoryWrapper, Finish finish)
        {
            PriceHistory mostUpToDate = null;

            foreach (var item in finish.PricePSM.PriceHistoryFuture)
            {
                if (mostUpToDate == null &&
                    item.Timestamp < DateTime.Now ||
                    mostUpToDate != null &&
                    item.Timestamp < DateTime.Now &&
                    mostUpToDate.Timestamp < item.Timestamp)
                {
                    mostUpToDate = item;
                }
            }

            if (mostUpToDate == null)
            {
                return;
            }
            if (!finish.PricePSM.EditPrice(mostUpToDate.Price, mostUpToDate.Timestamp))
            {
                return;
            }
            finish.PricePSM.PriceHistoryFuture.Remove(mostUpToDate);
            _repositoryWrapper.Finish.UpdateFinish(finish);
        }
        private void Processing()
        {
            Receive <IPriceUpdate>(p =>
            {
                _history = _history.WithPrice(p);
                _log.Info("[{0}] - current price is [{1}] as of [{2}]", _history.StockId, p.CurrentAvgPrice, p.Timestamp);
            });

            Receive <GetPriceHistory>(h =>
            {
                Sender.Tell(_history);
            });

            Receive <GetLatestPrice>(_ =>
            {
                Sender.Tell(_history.CurrentPriceUpdate);
            });

            Receive <PriceAndVolumeSnapshot>(_ => { }); // ignore

            // purge older price update entries.
            Receive <Prune>(_ => { _history = _history.Prune(DateTimeOffset.UtcNow.AddMinutes(-5)); });

            Receive <Terminated>(t =>
            {
                if (t.ActorRef.Equals(_tickerEntity))
                {
                    _log.Info("Source of truth entity terminated. Re-acquiring...");
                    Context.SetReceiveTimeout(TimeSpan.FromSeconds(5));
                    _priceActorGateway.Tell(new FetchPriceAndVolume(_tickerSymbol));
                    _mediator.Tell(new Unsubscribe(_priceTopic, Self)); // unsubscribe until we acquire new source of truth pricing
                    Become(WaitingForPriceAndVolume);
                }
            });
        }
        public void ShouldGetPriceInfo()
        {
            // Arrange
            var phTableRepository         = Substitute.For <ITableRepository <PriceHistory> >();
            var DTOMethods                = Substitute.For <IDTOMethodsforPriceHistory>();
            PriceHistoryService phService = new PriceHistoryService(phTableRepository, DTOMethods);
            PriceHistory        priceHist = new PriceHistory
            {
                PriceHistoryID = 1,
                StockID        = 1,
                DateTimeBegin  = new DateTime(2019, 8, 20, 09, 55, 00),
                DateTimeEnd    = new DateTime(2019, 8, 20, 19, 30, 00),
                Price          = 200
            };
            PriceArguments priceArguments = new PriceArguments()
            {
                StockId        = 1,
                DateTimeLookUp = new DateTime(2019, 8, 20, 09, 56, 00)
            };

            DTOMethods.FindEntitiesByRequestDTO(priceArguments).Returns(new List <PriceHistory> {
                priceHist
            });



            // Act
            var priceHistory = phService.GetStockPriceByDateTime(priceArguments);

            // Assert
            var hist = DTOMethods.Received(1).FindEntitiesByRequestDTO(priceArguments);
        }
Esempio n. 7
0
        public static void VerifyPricesMaterial(IRepositoryWrapper _repositoryWrapper, Material material)
        {
            PriceHistory mostUpToDate = null;

            foreach (var item in material.PricePSM.PriceHistoryFuture)
            {
                if (mostUpToDate == null &&
                    item.Timestamp < DateTime.Now ||
                    mostUpToDate != null &&
                    item.Timestamp < DateTime.Now &&
                    mostUpToDate.Timestamp < item.Timestamp)
                {
                    mostUpToDate = item;
                }
            }

            if (mostUpToDate == null)
            {
                return;
            }
            if (!material.PricePSM.EditPrice(mostUpToDate.Price, mostUpToDate.Timestamp))
            {
                return;
            }
            material.PricePSM.PriceHistoryFuture.Remove(mostUpToDate);
            _repositoryWrapper.Material.UpdateMaterial(material);
        }
Esempio n. 8
0
        public ActionResult EditItem(ItemsViewModel ivm)
        {
            ViewBag.ItemSizeID = new SelectList(sdnApps.ItemSizes, "Id", "Size");
            var gotItem = sdnApps.Items.First(m => m.ID == ivm.ID);


            if (ivm.Price != null && ivm.SelectedItemId != null)
            {
                PriceHistory ph = new PriceHistory();

                ph.Date    = DateTime.Now;
                ph.StoreID = (int)ivm.SelectedItemId;
                ph.ItemID  = ivm.ID;
                ph.Price   = Convert.ToDecimal(ivm.Price);

                sdnApps.PriceHistories.Add(ph);
            }

            gotItem.Amount     = ivm.Amount;
            gotItem.Name       = ivm.Name;
            gotItem.Price      = (decimal?)ivm.Price;
            gotItem.StoreID    = ivm.SelectedItemId;
            gotItem.Have       = false;
            gotItem.ItemSizeID = ivm.ItemSizeID;

            sdnApps.SaveChanges();

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 9
0
        public IHttpActionResult deletePriceHistorys(PriceHistory c)
        {
            // PriceHistory c1 = new PriceHistory { Id=1, Isin=3, Date=Convert.ToDateTime("1992-03-20"), Price=2 };
            int changeLine = PriceHistoryDao.deletePriceHistorys(c);

            return(Ok(changeLine));
        }
Esempio n. 10
0
 public System.Object ServerCommunication(Version clientversion, ICommunicateable communicator, bool full, System.Object obj)
 {
     try
     {
         if (clientversion.Major > 0)
         {
             if (full)
             {
                 communicator.SendString(Id);
                 communicator.SendString(Name);
                 communicator.SendInt(StockIndexes.Count);
                 if (StockIndexes.Count > 0)
                 {
                     foreach (StockIndex stockindex in StockIndexes.Values)
                         communicator.SendString(stockindex.Id);
                 }
                 PriceHistory.ServerCommunication(clientversion, communicator, full, obj);
             }
             if (clientversion.Major > 0 && clientversion.Minor >= 1)
             {
                 communicator.SendDouble(MinPrice);
                 communicator.SendDouble(MaxPrice);
             }
             communicator.SendDouble(Price);
             communicator.SendInt(Available);
             communicator.SendInt(OwnedByPlayers);
         }
         return this;
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 11
0
        public async Task And_Provider_Has_Unresolved_Errors_That_Have_Known_Triage_Status(
            Apprenticeship source,
            DataLockStatus dataLockStatus,
            PriceHistory priceHistory,
            ApprenticeshipToApprenticeshipDetailsMapper mapper)
        {
            //Arrange
            dataLockStatus.Status       = Status.Fail;
            dataLockStatus.TriageStatus = TriageStatus.Restart;
            dataLockStatus.IsResolved   = false;
            source.IsProviderSearch     = true;
            source.PriceHistory         = new List <PriceHistory> {
                priceHistory
            };
            source.DataLockStatus = new List <DataLockStatus> {
                dataLockStatus
            };
            source.ApprenticeshipUpdate = new List <ApprenticeshipUpdate>();

            //Act
            var result = await mapper.Map(source);

            //Assert
            result.Alerts.Should().BeNullOrEmpty();
        }
Esempio n. 12
0
        public async Task And_Has_ErrorCode_DLock07_And_TriageStatus_Unknown_Then_ILR_Data_mismatch_Alert(
            Apprenticeship source,
            DataLockStatus dataLockStatus,
            PriceHistory priceHistory,
            ApprenticeshipToApprenticeshipDetailsMapper mapper)
        {
            source.PriceHistory = new List <PriceHistory> {
                priceHistory
            };
            source.IsProviderSearch     = true;
            dataLockStatus.ErrorCode    = DataLockErrorCode.Dlock07;
            dataLockStatus.TriageStatus = TriageStatus.Unknown;
            dataLockStatus.IsResolved   = false;
            source.PriceHistory         = new List <PriceHistory> {
                priceHistory
            };
            source.DataLockStatus = new List <DataLockStatus> {
                dataLockStatus
            };
            source.ApprenticeshipUpdate = new List <ApprenticeshipUpdate>();

            var result = await mapper.Map(source);

            result.Alerts.Should().BeEquivalentTo(new List <Alerts> {
                Alerts.IlrDataMismatch
            });
        }
Esempio n. 13
0
        public async Task And_Employer_Has_Unresolved_Errors_That_Have_Known_Triage_Status_And_Has_Course_DataLock_Changes_Requested_Only_One_Changes_Requested_Added(
            Apprenticeship source,
            DataLockStatus dataLockStatus,
            DataLockStatus dataLockStatus2,
            PriceHistory priceHistory,
            ApprenticeshipToApprenticeshipDetailsMapper mapper)
        {
            //Arrange
            dataLockStatus.Status        = Status.Fail;
            dataLockStatus.TriageStatus  = TriageStatus.Restart;
            dataLockStatus.IsResolved    = false;
            dataLockStatus2.ErrorCode    = DataLockErrorCode.Dlock03;
            dataLockStatus2.TriageStatus = TriageStatus.Restart;
            dataLockStatus2.IsResolved   = false;
            source.IsProviderSearch      = false;
            source.DataLockStatus        = new List <DataLockStatus> {
                dataLockStatus, dataLockStatus2
            };
            source.PriceHistory = new List <PriceHistory> {
                priceHistory
            };
            source.ApprenticeshipUpdate = new List <ApprenticeshipUpdate>();

            //Act
            var result = await mapper.Map(source);

            //Assert
            result.Alerts.Should().NotBeNullOrEmpty();
            result.Alerts.Should().BeEquivalentTo(new List <Alerts> {
                Alerts.ChangesRequested
            });
        }
Esempio n. 14
0
        public IHttpActionResult PostPriceHistory(PriceHistory priceHistory)
        {
            if (!ModelState.IsValid || priceHistory == null)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                unitOfWork.PriceHistories.Add(priceHistory);
                unitOfWork.Complete();
            }
            catch (DbUpdateException)
            {
                if (PriceHistoryExists(priceHistory.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = priceHistory.Id }, priceHistory));
        }
Esempio n. 15
0
        public IHttpActionResult PutPriceHistory(Guid id, PriceHistory priceHistory)
        {
            if (!ModelState.IsValid || priceHistory == null)
            {
                return(BadRequest(ModelState));
            }

            if (id != priceHistory.Id)
            {
                return(BadRequest());
            }

            try
            {
                PriceHistory db_pricehistory = unitOfWork.PriceHistories.Get(id);
                db_pricehistory.Price = priceHistory.Price;
                unitOfWork.PriceHistories.Update(db_pricehistory);
                unitOfWork.Complete();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PriceHistoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Esempio n. 16
0
 public void Save(Version fv, WsgFileStream fs)
 {
     try
     {
         if (fv.Major > 0)
         {
             fs.WriteString(Id);
             fs.WriteString(Name);
             fs.WriteInt(StockIndexes.Count);
             if (StockIndexes.Count > 0)
             {
                 foreach (StockIndex stockindex in StockIndexes.Values)
                     fs.WriteString(stockindex.Id);
             }
             PriceHistory.Save(fv, fs);
             if (fv.Major > 0 && fv.Minor >= 1)
             {
                 fs.WriteDouble(MinPrice);
                 fs.WriteDouble(MaxPrice);
             }
             fs.WriteDouble(Price);
             fs.WriteInt(Available);
             fs.WriteInt(OwnedByPlayers);
         }
     }
     catch (System.Exception ex)
     {
         throw ex;
     }
 }
        public IHttpActionResult Updatestockprice(dynamic price)
        {
            PriceHistory history = new PriceHistory();

            history.Isin       = price.isin;
            history.OfferPrice = price.OfferPrice;
            history.Type       = "Stock";
            history.BidPrice   = price.BidPrice;
            history.Date       = DateTime.Now;

            int changeline = PriceHistoryDao.setPriceHistory(history);

            List <Position> positions = PositionDao.getPositionsByIsin(history.Isin);
            Portfolio       portfolio = new Portfolio();
            int             changline = 0;

            foreach (Position p in positions)
            {
                portfolio = PortfolioDao.getPortfoliosById(p.PortfolioId);
                double           pnl         = Getportfoliopnl(portfolio.PortfolioId);
                PortfolioHistory porthistory = new PortfolioHistory();
                porthistory.PNL         = pnl;
                porthistory.Date        = DateTime.Now;
                porthistory.PortfolioId = portfolio.PortfolioId;
                int line = PortfolioHistoryDao.setPortfolioHistory(porthistory);
                changline++;
            }

            return(Ok("success"));
        }
        public decimal GetStockPriceByDateTime(PriceArguments args)
        {
            IEnumerable <PriceHistory> priceInfos = this.dtoMethods.FindEntitiesByRequestDTO(args).ToList();
            PriceHistory priceinfo = priceInfos.Single();
            decimal      price     = priceinfo.Price;

            return(price);
        }
Esempio n. 19
0
        public ActionResult DeleteConfirmed(int id)
        {
            PriceHistory priceHistory = db.PriceHistories.Find(id);

            db.PriceHistories.Remove(priceHistory);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public void UpdatePriceHistory(float price)
 {
     PriceHistory.Add(price);
     if (PriceHistory.Count > _priceHistoryLimit)
     {
         PriceHistory.RemoveAt(0);
     }
 }
Esempio n. 21
0
 public static void UpdatePriceHistory(this PriceHistory priceHistory, PriceHistoryViewModel priceHistoryVM)
 {
     priceHistory.ProductID  = priceHistoryVM.ProductID;
     priceHistory.UpdateBy   = priceHistoryVM.UpdateBy;
     priceHistory.UpdateDate = priceHistoryVM.UpdateDate;
     priceHistory.Price      = priceHistoryVM.Price;
     priceHistory.Promotion  = priceHistoryVM.Promotion;
 }
 private static Domain.Entities.PriceHistory ToDomainModel(PriceHistory apiType)
 {
     return(new Domain.Entities.PriceHistory
     {
         TotalCost = apiType.TotalCost,
         EffectiveFrom = apiType.EffectiveFrom,
         EffectiveTo = apiType.EffectiveTo
     });
 }
Esempio n. 23
0
        private static void AssertEquality(PriceHistory source, GetPriceEpisodesQueryResult.PriceEpisode result)
        {
            Assert.AreEqual(source.Id, result.Id);

            Assert.AreEqual(source.ApprenticeshipId, result.ApprenticeshipId);
            Assert.AreEqual(source.FromDate, result.FromDate);
            Assert.AreEqual(source.ToDate, result.ToDate);
            Assert.AreEqual(source.Cost, result.Cost);
        }
Esempio n. 24
0
        /// <summary>
        /// Sets new active price for the item, can update the database
        /// </summary>
        public void SetNewCurrentPrice(int price, DateTime purchaseTime, bool updateDatabase = false)
        {
            CurrentPriceInt = price;
            PriceHistory.Add(purchaseTime, price);

            if (updateDatabase)
            {
                DatabaseAccess.Access.UpdateNewCurrentPrice(ID, price, purchaseTime);
            }
        }
        public PriceVolumeViewActor(string tickerSymbol, IActorRef priceActorGateway, IActorRef mediator)
        {
            _tickerSymbol      = tickerSymbol;
            _priceActorGateway = priceActorGateway;
            _priceTopic        = PriceTopicHelpers.PriceUpdateTopic(_tickerSymbol);
            _mediator          = mediator;
            _history           = new PriceHistory(_tickerSymbol, ImmutableSortedSet <IPriceUpdate> .Empty);

            WaitingForPriceAndVolume();
        }
Esempio n. 26
0
 internal BL.DTO.PriceHistoryDto Mapping(PriceHistory priceHistory)
 {
     Mapper.Initialize(cfg => cfg.CreateMap <PriceHistory, BL.DTO.PriceHistoryDto>()
                       .ForMember(x => x.Product, o => o.Ignore())
                       .AfterMap((pH1, pH2) =>
     {
         pH2.Product = Mapping(pH1.Product);
     }));
     return(Mapper.Map <PriceHistory, BL.DTO.PriceHistoryDto>(priceHistory));
 }
Esempio n. 27
0
 public static int setPriceHistory(PriceHistory a)
 {
     //  Portfolio b = new Portfolio() { PortfolioId = 1, FirstName = "zhang", LastName = "Tingting", Email = "zhangtingting.code@gmail", telephone = "1111111111", Role = "admin" };
     using (DatabaseContext db = new DatabaseContext())
     {
         db.PriceHistorys.Add(a);
         int result = db.SaveChanges();
         return(result);
     }
 }
Esempio n. 28
0
        public IHttpActionResult GetPriceHistory(Guid id)
        {
            PriceHistory priceHistory = unitOfWork.PriceHistories.Get(id);

            if (priceHistory == null)
            {
                return(NotFound());
            }

            return(Ok(priceHistory));
        }
        public async Task <IHttpActionResult> GetStockLatestPrice(int stock_id)
        {
            PriceHistory priceHistory = await db.PriceHistories.Where(e => e.stock_id == stock_id).OrderByDescending(e => e.time).FirstOrDefaultAsync();

            if (priceHistory == null)
            {
                return(NotFound());
            }

            return(Ok(priceHistory));
        }
        public override bool ContainsDTO(TEntity entity)
        {
            PriceHistory priceHistory = entity;

            return

                (this.db.PriceHistories
                 .Any(c => c.DateTimeBegin == priceHistory.DateTimeBegin &&
                      c.DateTimeEnd == priceHistory.DateTimeEnd &&
                      c.StockID == c.StockID));
        }
Esempio n. 31
0
        public EditReturnModel UpdateProduct(Guid productId, Guid categoryId, string productCode, string name, string color, string size,
                                             double weight, string unitWeight, string classType, decimal priceVnd,
                                             decimal priceUsd, string unit,
                                             string manuf, string supplier, bool available,
                                             List<PropertyModel> properties, Guid adminId)
        {
            try
            {
                if (properties != null && properties.Count > 0)
                {
                    //Update property
                    foreach (var property in properties)
                    {
                        var item = DataContext.Properties.SingleOrDefault(p => p.Id == property.Id);
                        if (item == null)
                            DataContext.Properties.Add(new Property
                                {
                                    CreatedDate = DateTime.UtcNow.AddHours(7),
                                    Id = Guid.NewGuid(),
                                    Name = property.Name,
                                    ParentId = productId,
                                    DisplayText = property.DisplayText,
                                    PropertyParentId = property.PropertyParentId,
                                    Value = property.Value
                                });
                        else
                        {
                            item.DisplayText = property.DisplayText;
                            item.Value = property.Value;
                            item.Name = property.Name;
                            item.UpdatedDate = DateTime.UtcNow.AddHours(7);
                        }
                    }
                }
                var product = DataContext.Products.SingleOrDefault(p => p.ProductId == productId);

                if (product == null)
                    return new EditReturnModel() { Message = "PNE", Result = false };

                if (product.CurrentPriceUsd != priceUsd || product.CurrentPriceVnd != priceVnd)
                {
                    var price = new PriceHistory()
                        {
                            CreatedDate = DateTime.UtcNow.AddHours(7),
                            Id = Guid.NewGuid(),
                            ProductId = productId,
                            PriceUsd = priceUsd,
                            PriceVnd = priceVnd
                        };
                    DataContext.PriceHistories.Add(price);
                }

                product.CategoryId = categoryId;
                product.Available = available;
                product.Class = classType;
                product.UpdateDate = DateTime.UtcNow.AddHours(7);
                product.Name = name;
                product.UpdateBy = adminId;
                product.ProductId = productId;
                product.Color = Json.Serialize(color.Split(','));
                product.Manufacturer = manuf;
                product.Size = Json.Serialize(size.Split(','));
                product.Supplier = supplier;
                product.CurrentPriceUsd = priceUsd;
                product.CurrentPriceVnd = priceVnd;
                product.Unit = unit;
                product.UnitWeight = unitWeight;
                product.Weight = weight;
                product.ProductCode = productCode;

                var result = DataContext.SaveChanges();

                return new EditReturnModel { Result = result > 0 };

            }
            catch (Exception exception)
            {
                return new EditReturnModel() { Result = false, Message = exception.ToString() };
            }
        }
Esempio n. 32
0
        public EditReturnModel InsertProduct(Guid categoryId, string productCode, List<ProductPhotoEditModel> imageProducts, string name, string color, string size,
                                           double weight, string unitWeight, string classType, decimal priceVnd, decimal priceUsd, string unit,
                                           string manuf, string supplier, bool available,
                                           List<PropertyModel> properties, Guid adminId)
        {
            try
            {
                var productId = Guid.NewGuid();
                var permalink = GeneratePermalink(Utilities.NonUnicode(name));

                if (properties != null && properties.Count > 0)
                {
                    foreach (var property in properties)
                        DataContext.Properties.Add(new Property()
                            {
                                Name = property.Name,
                                CreatedDate = DateTime.UtcNow.AddHours(7),
                                DisplayText = property.DisplayText,
                                Id = Guid.NewGuid(),
                                ParentId = productId,
                                Value = property.Value
                            });
                }
                //Insert image
                foreach (var imageProduct in imageProducts)
                {
                    var imageId = Guid.NewGuid();

                    var pos = imageProduct.FileName.LastIndexOf('.');
                    var fileextention = pos == -1 ? ".jpg" : imageProduct.FileName.Substring(pos).ToLower();

                    var filenameLarge = "large-" + imageId + fileextention;
                    var filename = imageId.ToString() + fileextention;
                    var filenameMedium = "medium-" + imageId.ToString() + fileextention;

                    var uploadOrigin = Utilities.UploadFile(imageProduct.FileContent, filename, Utilities.TypePath.Product);
                    var upload = Utilities.UploadAndResizeImage(imageProduct.FileContent, filenameLarge, 500, Utilities.TypePath.Product);
                    var upLoadMedium = Utilities.UploadAndResizeImage(imageProduct.FileContent, filenameMedium, 200, Utilities.TypePath.Product);
                    if (!upload || !upLoadMedium || !uploadOrigin)
                    {
                        return new EditReturnModel()
                        {
                            Result = false,
                            Message = "Upload image fail. Please check again"
                        }; // Upload image fail
                    }

                    var photo = new ProductPhoto()
                        {
                            CreatedDate = DateTime.UtcNow.AddHours(7),
                            FileType = imageProduct.FileType,
                            Id = imageId,
                            ProductId = productId,
                            OriginalFileName = filename,
                            LargeFileName = filenameLarge,
                            MediumFileName = filenameMedium
                        };
                    DataContext.ProductPhotos.Add(photo);
                }

                var price = new PriceHistory()
                {
                    CreatedDate = DateTime.UtcNow.AddHours(7),
                    Id = Guid.NewGuid(),
                    ProductId = productId,
                    PriceUsd = priceUsd,
                    PriceVnd = priceVnd
                };
                DataContext.PriceHistories.Add(price);

                var product = new Product()
                    {
                        CategoryId = categoryId,
                        Available = available,
                        Class = classType,
                        CreatedDate = DateTime.UtcNow.AddHours(7),
                        Name = name,
                        CreateBy = adminId,
                        ProductId = productId,
                        Color = Json.Serialize(color.Split(',')),
                        Manufacturer = manuf,
                        Size = Json.Serialize(size.Split(',')),
                        Supplier = supplier,
                        CurrentPriceUsd = priceUsd,
                        CurrentPriceVnd = priceVnd,
                        Unit = unit,
                        UnitWeight = unitWeight,
                        Weight = weight,
                        Permalink = permalink,
                        ProductCode = productCode
                    };
                DataContext.Products.Add(product);

                var result = DataContext.SaveChanges();

                return new EditReturnModel { Result = result > 0, Message = productId.ToString() };

            }
            catch (Exception exception)
            {
                return new EditReturnModel() { Result = false, Message = exception.ToString() };
            }
        }