Beispiel #1
0
        public SavedSearchFilterDto CreateSavedSearchFilter(SavedSearchFilterDto model)
        {
            try
            {
                var savedsearchfilter = Mapper.Map <savedsearchfilter>(model);
                savedsearchfilter.Created   = DateTime.UtcNow;
                savedsearchfilter.CreatedBy = model.CreatedBy;


                _context.savedsearchfilters.Add(savedsearchfilter);
                _context.SaveChanges();
                model.Id = savedsearchfilter.Id;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Beispiel #2
0
        private void updateProductsDetail(List <ProductAmazon> amazonProducts)
        {
            try
            {
                // iterate and update the EIS product info with data from marketplace
                foreach (var amazonProduct in amazonProducts)
                {
                    _repository.UpdateEisProduct(amazonProduct, _systemJob.SubmittedBy);
                    _repository.DoUpdateOrInsertAmazon(amazonProduct, _systemJob.SubmittedBy);

                    // parsed and save its images
                    if (amazonProduct.Images != null || amazonProduct.Images.Any())
                    {
                        _repository.UpdateProductImages(amazonProduct.Images.Select(x => x.Url).ToList(),
                                                        amazonProduct.EisSKU);
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.AmazonGetInfoWorker, errorMsg, ex.StackTrace);

                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.AmazonGetInfoWorker,
                                 string.Format("Error in updating products. <br/> Error message: {0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message),
                                 ex.StackTrace);

                _jobRepository.UpdateSystemJobStatus(_systemJob.Id, JobStatus.Failed);
            }
        }
        public string GetNextEisSKUForCompany(int companyId)
        {
            string eisSKU = null;

            using (var context = new EisInventoryContext())
            {
                // 1st get the StartSKUCode for this product via its Company
                var company = context.companies.FirstOrDefault(x => x.Id == companyId);
                if (company == null)
                {
                    return(null);
                }

                // get the SKU start code and also its serial SKU code...
                var skuCodeStart  = company.SKUCodeStart.Trim();
                var serialSkuCode = company.SearialSKUCode.Trim();

                // get the max EisSKU for this company
                var maxEisSKU = context.products
                                .Where(x => x.CompanyId == companyId && x.SkuType == SkuType.Normal)
                                .Max(x => x.EisSKU);

                // get the serial SKU code for this EIS SKU
                if (!string.IsNullOrEmpty(maxEisSKU))
                {
                    serialSkuCode = maxEisSKU.RightStartAt(skuCodeStart.Length);
                }

                // get the next SKU code and assign it to the model
                serialSkuCode = EisHelper.GetNextCode(serialSkuCode);
                eisSKU        = string.Format("{0}{1}", skuCodeStart, serialSkuCode);
            }

            return(eisSKU);
        }
        public MessageTemplateDto UpdateMessageTemplate(MessageTemplateDto model)
        {
            try
            {
                var oldMessageTemplate     = _context.messagetemplates.FirstOrDefault(x => x.Id == model.Id);
                var updatedMessageTemplate = Mapper.Map <messagetemplate>(model);
                updatedMessageTemplate.Modified = DateTime.Now;

                _context.Entry(oldMessageTemplate).CurrentValues.SetValues(updatedMessageTemplate);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
        public CustomerNotesDto UpdateCustomerNotes(CustomerNotesDto model)
        {
            try
            {
                var oldCustomerNotes = _context.customersnotes.FirstOrDefault(x => x.CustomerNotesId == model.CustomerNotesId);

                var updatedCustomerNotes = Mapper.Map <customersnote>(model);
                updatedCustomerNotes.Modified   = DateTime.Now;
                updatedCustomerNotes.ModifiedBy = model.ModifiedBy;
                updatedCustomerNotes.Created    = oldCustomerNotes.Created;
                updatedCustomerNotes.CreatedBy  = oldCustomerNotes.CreatedBy;
                updatedCustomerNotes.CustomerId = model.NotesCustomerId;


                _context.Entry(oldCustomerNotes).CurrentValues.SetValues(updatedCustomerNotes);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Beispiel #6
0
        public void SubmitSingleProductEndItem(ItemFeed itemFeed, string submittedBy)
        {
            try
            {
                if (string.IsNullOrEmpty(itemFeed.ItemId))
                {
                    _logger.LogInfo(LogEntryType.eBayEndListing, string.Format("Unable to send END_ITEM feed for \'{0}\' since it doesn't have ItemId. \nRequested by: {1}", itemFeed.EisSKU, submittedBy));
                    return;
                }

                // create the end item request
                var endItemCall = new EndItemCall(_context);
                endItemCall.EndItem(itemFeed.ItemId, EndReasonCodeType.NotAvailable);

                // let's set the eBay product ItemId to null
                _logger.SeteBayItemIdToNull(new List <ItemFeed> {
                    itemFeed
                });

                _logger.LogInfo(LogEntryType.eBayEndListing, string.Format("Successfully posted single END_ITEM feed for {0} - {1} item. \nRequested by: {2} \nAPI Message: {3}",
                                                                           ChannelName, itemFeed.EisSKU, submittedBy, endItemCall.ApiResponse.Message));
            }
            catch (Exception ex)
            {
                var description = string.Format("Error in submitting END_ITEM feed for {0}. \nError Message: {2} \nRequested by: {3}",
                                                itemFeed.EisSKU,
                                                EisHelper.GetExceptionMessage(ex),
                                                submittedBy);
                _logger.LogError(LogEntryType.eBayEndListing, description, ex.StackTrace);
            }
        }
        public SystemEmailDto CreateSystemEmail(SystemEmailDto model)
        {
            try
            {
                var systemEmail = Mapper.Map <systememail>(model);
                systemEmail.Created    = DateTime.UtcNow;
                systemEmail.CreatedBy  = model.ModifiedBy;
                systemEmail.ModifiedBy = null;

                _context.systememails.Add(systemEmail);
                _context.SaveChanges();
                model.Id = systemEmail.Id;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
        public CustomerNotesDto CreateCustomerNotes(CustomerNotesDto model)
        {
            try
            {
                var customerNotes = Mapper.Map <customersnote>(model);
                customerNotes.Created    = DateTime.UtcNow;
                customerNotes.CreatedBy  = model.ModifiedBy;
                customerNotes.ModifiedBy = null;
                customerNotes.CustomerId = model.NotesCustomerId;

                _context.customersnotes.Add(customerNotes);
                _context.SaveChanges();
                model.CustomerNotesId = customerNotes.CustomerNotesId;

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.CustomerService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
        public bool CreateVendorProduct(VendorProductDto model)
        {
            try
            {
                // get its vendor's info and if it's always on stock, use it alwaysQuantity
                var vendor = _context.vendors.FirstOrDefault(x => x.Id == model.VendorId);
                if (vendor.IsAlwaysInStock)
                {
                    model.Quantity = vendor.AlwaysQuantity ?? 0;
                }

                var product = Mapper.Map <vendorproduct>(model);
                product.Created   = DateTime.UtcNow;
                product.CreatedBy = model.ModifiedBy;

                _context.vendorproducts.Add(product);
                _context.SaveChanges();

                // generated id
                model.EisSupplierSKU = product.EisSupplierSKU;

                return(true);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(false);
            }
        }
        public ActionResult UpdateProducteBay(string id, ProducteBayDto model)
        {
            try
            {
                // get the original product
                var eBay = _productService.GetProducteBay(id);

                // try to determine the category ID for the eBay
                int categoryId = 0;
                Int32.TryParse(model.CategoryName, out categoryId);

                // try to look the value for category name if the category is null
                if (model.CategoryId == null)
                {
                    model.CategoryId = categoryId != 0 ? (int?)categoryId : null;
                }

                if (eBay == null)
                {
                    _productService.SaveProducteBay(model);
                }
                else
                {
                    _productService.UpdateProducteBay(id, model);
                }

                TempData["Message"] = "Changes have been successfully saved!";
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = string.Format("Error in saving eBay product. Exception Msg: {0}",
                                                         EisHelper.GetExceptionMessage(ex));
            }
            return(RedirectToAction("edit", new { id = id }));
        }
Beispiel #11
0
        public SavedSearchFilterDto UpdateSavedSearchFilter(SavedSearchFilterDto model)
        {
            try
            {
                var oldSavedFilterSearch     = _context.savedsearchfilters.FirstOrDefault(x => x.Id == model.Id);
                var updatedSavedFilterSearch = Mapper.Map <savedsearchfilter>(model);

                updatedSavedFilterSearch.Created   = DateTime.Now;
                updatedSavedFilterSearch.CreatedBy = model.CreatedBy;

                _context.Entry(oldSavedFilterSearch).CurrentValues.SetValues(updatedSavedFilterSearch);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Beispiel #12
0
        public void SubmitSingleProductPriceFeed(MarketplacePriceFeedDto priceItem, string submittedBy)
        {
            try
            {
                // create the Amazon envelope for the Price feed
                var envelope = RequestHelper.CreatePriceFeedEnvelope(new List <AmazonPriceFeed> {
                    priceItem.AmazonPriceFeed
                });

                // parse the envelope into file
                var xmlFullName = XmlParser.WriteXmlToFile(envelope, "AmazonSinglePriceFeed");

                var submitFeedController = new SubmitFeedController(_amazonClient,
                                                                    _logger,
                                                                    _credential.MarketplaceId,
                                                                    _credential.MerchantId,
                                                                    submittedBy);
                var streamResponse = submitFeedController.SubmitFeedAndGetResponse(xmlFullName, AmazonFeedType._POST_PRODUCT_PRICING_DATA_);
                parsedResultStreamAndLogReport(streamResponse, AmazonEnvelopeMessageType.Price, submittedBy);

                _logger.LogInfo(LogEntryType.AmazonPriceUpdate, string.Format("{0} - Successfully posted single price feed for EisSKU \'{1}\' \nRequested by: {2}",
                                                                              ChannelName, priceItem.EisSKU, submittedBy));
            }
            catch (Exception ex)
            {
                var description = string.Format("{0} - Error in submitting single price feed for EisSKU \'{3}\'. \nError Message: {1} \nRequested by: {2}",
                                                ChannelName,
                                                EisHelper.GetExceptionMessage(ex),
                                                submittedBy,
                                                priceItem.EisSKU);
                _logger.Add(LogEntrySeverity.Error, LogEntryType.AmazonPriceUpdate, description, ex.StackTrace);
            }
        }
Beispiel #13
0
        public ProductAmazonDto UpdateProductAmazon(string eisSku, ProductAmazonDto model)
        {
            var oldProduct = _context.productamazons.Find(eisSku);

            try
            {
                // ensure the EIS SKU is upper cased
                model.EisSKU.ToUpper();
                _context.Entry(oldProduct).CurrentValues.SetValues(model);
                oldProduct.Modified   = DateTime.UtcNow;
                oldProduct.ModifiedBy = model.ModifiedBy;

                _context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }

            return(model);
        }
Beispiel #14
0
        public ProductAmazonDto SaveProductAmazon(ProductAmazonDto model)
        {
            var product = Mapper.Map <ProductAmazonDto, productamazon>(model);

            try
            {
                product.Modified   = DateTime.UtcNow;
                product.ModifiedBy = model.ModifiedBy;

                _context.productamazons.Add(product);
                _context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }

            return(model);
        }
Beispiel #15
0
        public ProductDto SaveProduct(ProductDto model)
        {
            try
            {
                // ensure the EIS SKU is upper cased
                model.EisSKU.ToUpper();
                var product = Mapper.Map <ProductDto, product>(model);
                product.CreatedBy = model.ModifiedBy;
                product.Created   = DateTime.UtcNow;

                _context.products.Add(product);
                _context.SaveChanges();

                return(Mapper.Map <product, ProductDto>(product));
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                return(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(model);
            }
        }
Beispiel #16
0
        public static LogEntry CheckFileFromFtp(Credential credential)
        {
            var parsedFileName = string.Format(credential.FileName, DateTime.Now);

            try
            {
                var isFileExist = false;
                if (credential.FileName.Contains("*"))
                {
                    isFileExist = checkFilePartFromFtp(credential);
                }
                else
                {
                    isFileExist = checkFilenameFromFtp(credential);
                }

                var message = isFileExist ? "and the \'{0}\'file is exist in FTP server!"
                    : "but the \'{0}\'file does NOT exist in FTP server!";

                return(new LogEntry
                {
                    Severity = isFileExist ? LogEntrySeverity.Information : LogEntrySeverity.Error,
                    Description = string.Format("FTP credentials are valid {0}", string.Format(message, parsedFileName)),
                });
            }
            catch (Exception ex)
            {
                return(new LogEntry
                {
                    Severity = LogEntrySeverity.Error,
                    Description = string.Format("The \'{0}\' file may not exist from FTP server or the credentials are invalid!<br/>Error Msg: {1}",
                                                parsedFileName, EisHelper.GetExceptionMessage(ex))
                });
            }
        }
Beispiel #17
0
        public VendorDto CreateVendor(VendorDto model)
        {
            try
            {
                var vendor = Mapper.Map<VendorDto, vendor>(model);
                vendor.CreatedBy = model.ModifiedBy;
                vendor.Created = DateTime.UtcNow;

                _context.vendors.Add(vendor);
                _context.SaveChanges();

                // update all of its vendor products if it is configured as always in stock
                if (vendor.IsAlwaysInStock)
                    upateVendorProductsQuantity(vendor.Id, vendor.AlwaysQuantity ?? 0);

                return Mapper.Map<vendor, VendorDto>(vendor);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                return model;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return model;
            }
        }
Beispiel #18
0
        public static LogEntry CheckFtpConnection(Credential credential)
        {
            var ftpFullPath = string.Format("ftp://{0}:{1}/{2}/", credential.Server,
                                            credential.Port,
                                            string.IsNullOrEmpty(credential.RemoteFolder) ? string.Empty : credential.RemoteFolder);

            try
            {
                // get the object to communicate with the FTP server
                var request = (FtpWebRequest)WebRequest.Create(new Uri(ftpFullPath));
                request.Method      = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(credential.UserName, credential.Password);
                request.KeepAlive   = false;
                request.GetResponse();

                return(new LogEntry
                {
                    Severity = LogEntrySeverity.Information,
                    Description = "FTP credentials are valid and server is reachable!",
                });
            }
            catch (Exception ex)
            {
                return(new LogEntry
                {
                    Severity = LogEntrySeverity.Error,
                    Description = "Error in checking FTP connection! Error Msg: " + EisHelper.GetExceptionMessage(ex)
                });
            }
        }
Beispiel #19
0
        public void SubmitSingleProductInventoryFeed(MarketplaceInventoryFeed inventoryFeed, string submittedBy)
        {
            try
            {
                // parse the EIS product and create Amazon envelope
                var envelope = RequestHelper.CreateInventoryFeedEnvelope(new List <AmazonInventoryFeed> {
                    inventoryFeed.AmazonInventoryFeed
                });

                // parse the envelope into file
                var xmlFullName = XmlParser.WriteXmlToFile(envelope, "AmazonSingleInventoryFeed");

                var submitFeedController = new SubmitFeedController(_amazonClient,
                                                                    _logger,
                                                                    _credential.MarketplaceId,
                                                                    _credential.MerchantId,
                                                                    submittedBy);
                var streamResponse = submitFeedController.SubmitFeedAndGetResponse(xmlFullName, AmazonFeedType._POST_INVENTORY_AVAILABILITY_DATA_);
                parsedResultStreamAndLogReport(streamResponse, AmazonEnvelopeMessageType.Inventory, submittedBy);

                _logger.LogInfo(LogEntryType.AmazonInventoryUpdate, string.Format("{0} - Successfully posted single inventory feed for EisSKU \'{1}\'.\nRequested by: {2}",
                                                                                  ChannelName, inventoryFeed.EisSKU, submittedBy));
            }
            catch (Exception ex)
            {
                var description = string.Format("{0} - Error in submitting single product inventory feed for EisSKU \'{3}\'. \nError Message: {1} \nRequested by: {2}",
                                                ChannelName,
                                                EisHelper.GetExceptionMessage(ex),
                                                submittedBy,
                                                inventoryFeed.EisSKU);
                _logger.Add(LogEntrySeverity.Error, LogEntryType.AmazonInventoryUpdate, description, ex.StackTrace);
            }
        }
        public SystemEmailDto UpdateSystemEmail(SystemEmailDto model)
        {
            try
            {
                var oldSystemEmail     = _context.systememails.FirstOrDefault(x => x.Id == model.Id);
                var updatedSystemEmail = Mapper.Map <systememail>(model);
                updatedSystemEmail.Modified   = DateTime.Now;
                updatedSystemEmail.ModifiedBy = model.ModifiedBy;
                updatedSystemEmail.Created    = oldSystemEmail.Created;
                updatedSystemEmail.CreatedBy  = oldSystemEmail.CreatedBy;



                _context.Entry(oldSystemEmail).CurrentValues.SetValues(updatedSystemEmail);
                _context.SaveChanges();

                return(model);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }
        }
Beispiel #21
0
        public bool CreateCompany(CompanyDto model)
        {
            try
            {
                var company = Mapper.Map <CompanyDto, company>(model);
                company.Created    = DateTime.UtcNow;
                company.CreatedBy  = model.ModifiedBy;
                company.ModifiedBy = null;

                _context.companies.Add(company);
                _context.SaveChanges();
                model.Id = company.Id;

                return(true);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.VendorService, errorMsg, ex.StackTrace);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(false);
            }
        }
Beispiel #22
0
        public int SaveMarketplaceOrders(List <MarketplaceOrder> orderResults)
        {
            try
            {
                var results = new List <OrderProductResult>();

                // iterate and convert the order results into order domain object
                foreach (var orderResult in orderResults)
                {
                    // let's check first if this marketplace order already exist to the db
                    var existingOrder = _context.orders.FirstOrDefault(x => x.OrderId == orderResult.OrderId);
                    if (existingOrder != null)
                    {
                        continue;
                    }

                    // map the order result into order domain and set the its EIS order Id
                    var order = Mapper.Map <order>(orderResult);
                    order.EisOrderId = GetNextEisOrderId();
                    _context.orders.Add(order);

                    foreach (var orderItem in orderResult.OrderItems)
                    {
                        // create also the order update history for orderitems
                        _context.orderupdatehistories.Add(new orderupdatehistory
                        {
                            OrderItemId  = orderItem.OrderItemId,
                            QtyOrdered   = orderItem.QtyOrdered,
                            OrderStatus  = orderResult.OrderStatus,
                            PurchaseDate = orderResult.PurchaseDate,
                            ResultDate   = DateTime.UtcNow
                        });

                        // create order products and update the product inventory
                        var result = ManageOrderVendorProduct(orderItem);
                        results.Add(result);
                    }

                    // let's save the changes 1by1 so we can get its EIS OrderID
                    _context.SaveChanges();
                }

                // notify Admin if there are insufficient products for the orders
                EvaluateForInsufficientVendorProducts(results);
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.OrderService, errorMsg, ex.StackTrace);
                return(0);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.OrderService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                return(0);
            }

            return(orderResults.Count);
        }
        public void UpdateProductImages(List <string> imageUrls, string eisSku)
        {
            // check if there's any image URLs
            if (imageUrls == null || !imageUrls.Any())
            {
                return;
            }

            try
            {
                using (var context = new EisInventoryContext())
                {
                    // get the Amazon images
                    var amazonImages = context.productimages
                                       .Where(x => x.EisSKU == eisSku && x.ImageType != "CUSTOM")
                                       .ToList();
                    foreach (var image in amazonImages)
                    {
                        // delete first the image file from the directory
                        _imageHelper.RemoveProductImage(eisSku, image.FileName);

                        // then the image record from the database
                        context.productimages.Remove(image);
                    }

                    // let's save the changes first for the deleted images
                    context.SaveChanges();

                    // download and add the images
                    foreach (var url in imageUrls)
                    {
                        // download the image from net and save it to the file system
                        var fileName = _imageHelper.SaveProductImage(eisSku, url);
                        if (string.IsNullOrEmpty(fileName))
                        {
                            continue;
                        }

                        // add the database to the database
                        context.productimages.Add(new productimage
                        {
                            EisSKU    = eisSku,
                            Caption   = "Amazon",
                            FileName  = fileName,
                            ImageType = "LARGE",
                            Order_    = 99
                        });
                    }

                    // save the images
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.AmazonGetInfoWorker, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
            }
        }
Beispiel #24
0
        public void UpdateCustomerFiles(List <string> imageUrls, int customerId)
        {
            // check if there's any image URLs
            if (imageUrls == null || !imageUrls.Any())
            {
                return;
            }

            try
            {
                using (var context = new EisInventoryContext())
                {
                    // get the Customer images
                    var CustomerImages = context.customerimages
                                         .Where(x => x.CustomerId == customerId)
                                         .ToList();
                    foreach (var image in CustomerImages)
                    {
                        // delete first the image file from the directory
                        _fileHelper.RemoveFile(_subFolderName, customerId.ToString(), image.FileName);

                        // then the image record from the database
                        context.customerimages.Remove(image);
                    }

                    // let's save the changes first for the deleted images
                    context.SaveChanges();

                    // download and add the images
                    foreach (var url in imageUrls)
                    {
                        // download the image from net and save it to the file system
                        var extension = Path.GetExtension(url);
                        var fileName  = _fileHelper.SaveFile(_subFolderName, customerId.ToString(), extension, url);
                        if (string.IsNullOrEmpty(fileName))
                        {
                            continue;
                        }

                        // add the database to the database
                        context.customerimages.Add(new customerimage
                        {
                            CustomerId = customerId,
                            Caption    = "Customer",
                            FileName   = fileName,
                            Order_     = 99
                        });
                    }

                    // save the images
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.CustomerService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
            }
        }
Beispiel #25
0
        private void updateEisProduct(MarketplaceProduct product)
        {
            try
            {
                var eisProduct = _productService.GetProductByEisSKU(product.EisSKU);
                if (eisProduct == null)
                {
                    return;
                }

                product.EisSKU = eisProduct.EisSKU;

                //eisProduct.Name = product.ProductTitle;

                // set the EIS product Package's Dimension
                eisProduct.Brand  = product.Brand;
                eisProduct.Color  = product.Color;
                eisProduct.EAN    = product.EAN;
                eisProduct.Model_ = product.Model;

                // determine the product type id of the marketplace product
                eisProduct.ProductTypeId = _productTypeService.ConfigureProductTypeName(((ProductAmazon)product).ProductTypeName, ((ProductAmazon)product).ProductGroup);

                // set the product' package dimension
                if (product.PackageDimension != null)
                {
                    eisProduct.PkgLength     = product.PackageDimension.Length.Value;
                    eisProduct.PkgWidth      = product.PackageDimension.Width.Value;
                    eisProduct.PkgHeight     = product.PackageDimension.Height.Value;
                    eisProduct.PkgLenghtUnit = product.PackageDimension.Length.Unit;

                    // parse the weigh and its unit
                    eisProduct.PkgWeight     = product.PackageDimension.Weight.Value;
                    eisProduct.PkgWeightUnit = product.PackageDimension.Weight.Unit;
                }

                // set the EIS product Item's dimension
                if (product.ItemDimension != null)
                {
                    eisProduct.ItemLength     = product.ItemDimension.Length.Value;
                    eisProduct.ItemWidth      = product.ItemDimension.Width.Value;
                    eisProduct.ItemHeight     = product.ItemDimension.Height.Value;
                    eisProduct.ItemLenghtUnit = product.ItemDimension.Length.Unit;

                    // parse the weigh and its unit
                    eisProduct.ItemWeight     = product.ItemDimension.Weight.Value;
                    eisProduct.ItemWeightUnit = product.ItemDimension.Weight.Unit;
                }

                // save the chnages
                _productService.UpdateProduct(eisProduct.EisSKU, eisProduct);
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.MarketplaceProductManager, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Convert the SubmitFeedResponse stream for the post feed folow into a AmazonExeption if needed
        /// </summary>
        /// <param name="responseStream">The response stream object</param>
        /// <param name="messageType">The type of the message</param>
        /// <returns></returns>
        private void parsedResultStreamAndLogReport(Stream responseStream, AmazonEnvelopeMessageType messageType, string submittedBy)
        {
            try
            {
                using (var stream = responseStream)
                {
                    // the result may not be an XML document. This will be reveled with testing.
                    var doc = new XmlDocument();
                    doc.Load(stream);

                    var report            = doc.SelectSingleNode("/AmazonEnvelope/Message/ProcessingReport");
                    var processingSummary = report.SelectSingleNode("ProcessingSummary");
                    var processingReport  = new MarketplaceProcessingReport
                    {
                        MerchantId          = _credential.MerchantId,
                        MessageType         = messageType.ToString(),
                        TransactionId       = report.SelectSingleNode("DocumentTransactionID").InnerText,
                        MessagesProcessed   = int.Parse(processingSummary.SelectSingleNode("MessagesProcessed").InnerText),
                        MessagesSuccessful  = int.Parse(processingSummary.SelectSingleNode("MessagesSuccessful").InnerText),
                        MessagesWithError   = int.Parse(processingSummary.SelectSingleNode("MessagesWithError").InnerText),
                        MessagesWithWarning = int.Parse(processingSummary.SelectSingleNode("MessagesWithWarning").InnerText),
                        StatusCode          = report.SelectSingleNode("StatusCode").InnerText,
                        SubmittedBy         = submittedBy
                    };

                    // parsed the any processing report results
                    var results       = report.SelectNodes("Result");
                    var reportResults = new List <MarketplaceProcessingReportResult>();
                    foreach (XmlNode result in results)
                    {
                        reportResults.Add(new MarketplaceProcessingReportResult
                        {
                            TransactionId  = processingReport.TransactionId,
                            MessageId      = int.Parse(result.SelectSingleNode("MessageID").InnerText),
                            Code           = result.SelectSingleNode("ResultCode").InnerText,
                            MessageCode    = result.SelectSingleNode("ResultMessageCode").InnerText,
                            Description    = result.SelectSingleNode("ResultDescription").InnerText,
                            AdditionalInfo = result.SelectSingleNode("AdditionalInfo/AmazonOrderID") == null ? "" : result.SelectSingleNode("AdditionalInfo/AmazonOrderID").InnerText
                        });
                    }

                    // add it to the report summary
                    processingReport.ReportResults = reportResults;

                    // save it to the database
                    _logger.AddProcessingReport(processingReport);
                }
            }
            catch (Exception ex)
            {
                _logger.Add(LogEntrySeverity.Error,
                            LogEntryType.AmazonOrdersProvider,
                            string.Format("{2} - Error in parsing {0} result response stream. <br/> Error Message: {1}", messageType.ToString(),
                                          EisHelper.GetExceptionMessage(ex), ChannelName),
                            ex.StackTrace);
            }
        }
Beispiel #27
0
        private void resubmitInventoryStatusBySingleFeeds(List <eBayInventoryFeed> inventoryFeeds, string submittedBy, bool isPriceUpdate = false, bool isQuantityUpdate = false)
        {
            for (var i = 0; i < inventoryFeeds.Count; i++)
            {
                try
                {
                    // create inventory item feed
                    var inventoryStatus = new InventoryStatusType
                    {
                        ItemID = inventoryFeeds[i].ItemId
                    };

                    // set the new price if its price update
                    if (isPriceUpdate)
                    {
                        inventoryStatus.StartPrice = new AmountType
                        {
                            currencyID = CurrencyCodeType.USD,
                            Value      = (double)inventoryFeeds[i].BinPrice,
                        };
                    }

                    // set the new quantity if its for inventory update
                    if (isQuantityUpdate)
                    {
                        inventoryStatus.Quantity          = inventoryFeeds[i].InventoryQuantity;
                        inventoryStatus.QuantitySpecified = true;
                    }

                    var inventoryStatusCollection = new InventoryStatusTypeCollection();
                    inventoryStatusCollection.Add(inventoryStatus);

                    // send the inventory collection request
                    var apiCall = new ReviseInventoryStatusCall(_context);
                    var inventoryStatusResult = apiCall.ReviseInventoryStatus(inventoryStatusCollection);

                    var description = string.Format("Successfully posting {0} feed for {1}.  \nRequested by: {2}",
                                                    (isPriceUpdate ? "PRICE" : "INVENTORY"),
                                                    inventoryFeeds[i].EisSKU,
                                                    submittedBy);
                    _logger.LogInfo(LogEntryType.eBayInventoryUpdate, description);
                    Console.WriteLine(description);
                }
                catch (Exception ex)
                {
                    var description = string.Format("Error in submitting single {0} feed for {1} . \nError Message: {2} \nRequested by: {3}",
                                                    (isPriceUpdate ? "PRICE" : "INVENTORY"),
                                                    inventoryFeeds[i].EisSKU,
                                                    EisHelper.GetExceptionMessage(ex),
                                                    submittedBy);
                    _logger.LogError(LogEntryType.eBayInventoryUpdate, string.Format("Single: {0}/{1} - {2}", i + 1, inventoryFeeds.Count, description), ex.StackTrace);
                    Console.WriteLine(description);
                }
            }
        }
        public ActionResult Save(string id, ProductDto model)
        {
            // create view bag first for the vendors
            populateViewBags();
            var originpage = string.IsNullOrEmpty(id) ? "create" : "edit";

            model.ModifiedBy = User.Identity.Name;

            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values.SelectMany(e => e.Errors.Select(x => x.ErrorMessage));
                ModelState.AddModelError("", string.Join("<br/>", errors));

                // return to the original page which the request came from
                return(View(originpage, model));
            }

            if (string.IsNullOrEmpty(id))
            {
                // generate the EisSKU for this product
                // 1st get the StartSKUCode for this product via its Company
                var company       = _companyService.GetCompany(model.CompanyId);
                var skuCodeStart  = company.SKUCodeStart.Trim();
                var serialSkuCode = company.SearialSKUCode.Trim();

                // get the max EisSKU for this company
                var maxEisSKU = _productService.GetMaxEisSKUByCompany(model.CompanyId);
                if (!string.IsNullOrEmpty(maxEisSKU))
                {
                    serialSkuCode = maxEisSKU.RightStartAt(skuCodeStart.Length);
                }

                // get the next SKU code and assign it to the model
                serialSkuCode = EisHelper.GetNextCode(serialSkuCode);
                model.EisSKU  = string.Format("{0}{1}", skuCodeStart, serialSkuCode);

                // check if the EisSKU exists
                if (_productService.IsEisSKUExists(model.EisSKU))
                {
                    ModelState.AddModelError("", string.Format("The \'{0}\' EIS SKU is already exist!", model.EisSKU));
                    return(View(originpage, model));
                }

                // if we got this far, everything is OK
                _productService.SaveProduct(model);
            }
            else
            {
                // if we got this far, everything is OK
                _productService.UpdateProduct(id, model);
            }

            TempData["Message"] = "Changes have been successfully saved!";
            return(RedirectToAction("Edit", new { id = model.EisSKU }));
        }
Beispiel #29
0
        public bool CreateOrUpdateBigCommerceCustomFields(List <BigCommerceCustomFieldDto> customFields)
        {
            var success = false;

            try
            {
                var forUpdateData = customFields.Where(o => o.Id != -1 && o.ProductId != -1).ToList();
                var forCreateData = customFields.Where(o => o.Id == -1 && o.ProductId != -1).ToList();
                var forDeleteData = customFields.Where(o => o.ProductId == -1).ToList();

                // Update Custom Fields
                foreach (var data in forUpdateData)
                {
                    var eisCustomField = _context.bigcommercecustomfields.FirstOrDefault(o => o.Id == data.Id);

                    if (eisCustomField != null)
                    {
                        eisCustomField.Name = data.Name;
                        eisCustomField.Text = data.Text;
                    }
                }


                // Create Custom Fields
                foreach (var data in forCreateData)
                {
                    var eisCustomField = Mapper.Map <BigCommerceCustomFieldDto, bigcommercecustomfield>(data);

                    _context.bigcommercecustomfields.Add(eisCustomField);
                }


                //  Delete Custom Fields
                foreach (var data in forDeleteData)
                {
                    var eisCustomField = _context.bigcommercecustomfields.FirstOrDefault(o => o.Id == data.Id);

                    if (eisCustomField != null)
                    {
                        _context.bigcommercecustomfields.Remove(eisCustomField);
                    }
                }

                success = _context.SaveChanges() > 0;
            } catch (Exception ex)
            {
                success = false;

                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
            }

            return(success);
        }
        public JsonResult _DeleteProduct(string id)
        {
            try
            {
                _productService.DeleteProduct(id);

                return(Json(new { Success = "Product has been successfully deleted!" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new { Error = "Error in deleting product! - Message: " + EisHelper.GetExceptionMessage(ex) }, JsonRequestBehavior.AllowGet));
            }
        }