Esempio n. 1
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);
        }
Esempio n. 2
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);
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
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);
            }
        }
Esempio n. 5
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;
            }
        }
        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;
            }
        }
Esempio n. 7
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))
                });
            }
        }
Esempio n. 8
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)
                });
            }
        }
Esempio n. 9
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);
            }
        }
Esempio n. 10
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);
            }
        }
Esempio n. 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;
            }
        }
        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;
            }
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        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;
            }
        }
Esempio n. 15
0
        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;
            }
        }
Esempio n. 16
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;
            }
        }
Esempio n. 17
0
        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);
            }
        }
Esempio n. 18
0
        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;
            }
        }
Esempio n. 19
0
        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 }));
        }
Esempio n. 20
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);
        }
Esempio n. 21
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);
            }
        }
Esempio n. 22
0
        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);
            }
        }
Esempio n. 23
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);
            }
        }
Esempio n. 24
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);
            }
        }
Esempio n. 25
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);
                }
            }
        }
Esempio n. 26
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);
        }
Esempio n. 27
0
        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));
            }
        }
Esempio n. 28
0
        public CustomerAddressDto UpdateCustomerAddress(CustomerAddressDto model)
        {
            try
            {
                var customerAddressesList = _context.customersaddresses.Where(x => x.CustomerId == model.AddressCustomerId).ToList();

                if (customerAddressesList.Count == 0 || !customerAddressesList.Any(x => x.IsPrimary == true))
                {
                    model.IsPrimary = true;
                }
                else if (model.IsPrimary)
                {
                    foreach (var address in customerAddressesList)
                    {
                        address.IsPrimary = false;

                        _context.Entry(address).State = System.Data.Entity.EntityState.Modified;
                        _context.SaveChanges();
                    }
                }

                var oldCustomerAddress = _context.customersaddresses.FirstOrDefault(x => x.CustomerAddressID == model.CustomerAddressID);

                var updatedCustomerAddress = Mapper.Map <customersaddress>(model);
                updatedCustomerAddress.Modified   = DateTime.Now;
                updatedCustomerAddress.ModifiedBy = model.ModifiedBy;
                updatedCustomerAddress.Created    = oldCustomerAddress.Created;
                updatedCustomerAddress.CreatedBy  = oldCustomerAddress.CreatedBy;

                updatedCustomerAddress.CustomerId   = model.AddressCustomerId;
                updatedCustomerAddress.EmailAddress = model.customerEmailAddress;
                updatedCustomerAddress.Country      = Convert.ToInt32(model.SelectedCountryId);


                _context.Entry(oldCustomerAddress).CurrentValues.SetValues(updatedCustomerAddress);
                _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;
            }
        }
Esempio n. 29
0
 public IEnumerable <MarketplaceOrder> GetMarketplaceOrders(DateTime createdAfter)
 {
     try
     {
         return(_ordersService.GetMarketplaceOrders(createdAfter));
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine("Error Message: " + EisHelper.GetExceptionMessage(ex) + "\n" + ex.StackTrace);
         _logger.LogError(LogEntryType.OrderService,
                          string.Format("Error occured in fetching order for {0} <br/>Error message: {1}",
                                        _ordersService.ChannelName, EisHelper.GetExceptionMessage(ex)),
                          ex.StackTrace);
         return(null);
     }
 }
        public void UpdateOrderVendorProductInventory(List <MarketplaceOrder> orders)
        {
            try
            {
                var results = new List <OrderProductResult>();

                // iterate to each order and also to its order item
                foreach (var order in orders)
                {
                    // then, to its order items
                    foreach (var orderItem in order.OrderItems)
                    {
                        // let's determine if this item has already record in order upate history
                        var hasHistory = _repository.HasOrderItemUpdateHistory(orderItem.OrderItemId, order.OrderStatus, order.PurchaseDate);
                        if (hasHistory)
                        {
                            continue;
                        }

                        // otherwise let's create order item update history
                        _repository.CreateOrderItemUpdateHistory(orderItem, order.OrderStatus, order.PurchaseDate);

                        // manage the vendor product inventory
                        if (order.OrderStatus != OrderStatus.Canceled)
                        {
                            var result = _service.ManageOrderVendorProduct(orderItem);
                            results.Add(result);
                        }
                        else
                        {
                            _repository.ReturnVendorProductInventory(orderItem);
                        }
                    }
                }

                // notify Admin if there are insufficient products for the orders
                _service.EvaluateForInsufficientVendorProducts(results);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error Message: " + EisHelper.GetExceptionMessage(ex) + "\n" + ex.StackTrace);
                _logger.LogError(LogEntryType.OrderService,
                                 string.Format("Error in updating vendor product inventory <br/>Error message: {0}",
                                               EisHelper.GetExceptionMessage(ex)),
                                 ex.StackTrace);
            }
        }