public void createWindowsToast(AmazonItem item)
        {
            ToastContent content = new ToastContent()
            {
                Launch         = item.productURL,
                ActivationType = ToastActivationType.Protocol,
                Visual         = new ToastVisual()
                {
                    BindingGeneric = new ToastBindingGeneric()
                    {
                        Children =
                        {
                            new AdaptiveText()
                            {
                                Text = item.productTitle
                            },

                            new AdaptiveText()
                            {
                                Text = "The item is available at " + item.productPrice + ", at or lower than the desired price " + item.desiredPrice + "."
                            }
                        },

                        Attribution = new ToastGenericAttributionText()
                        {
                            Text = "Via Amazon Price Tracker"
                        },
                    }
                },
            };

            var toast = new ToastNotification(content.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
        private async Task <object> updateAmazonItemsList()
        {
            ObservableCollection <AmazonItem> dummList = new ObservableCollection <AmazonItem>();

            if (AmazonItems != null)
            {
                foreach (AmazonItem item in AmazonItems)
                {
                    List <String> itemProperties = await getAmazonItemFromURLAsync(item.productURL);

                    AmazonItem newItem;
                    if (itemProperties != null)
                    {
                        newItem = new AmazonItem(itemProperties[0], itemProperties[1], item.desiredPrice, itemProperties[2], itemProperties[3]);
                        newItem.previousPrice = item.productPrice;
                        dummList.Add(newItem);
                    }
                }

                AmazonItems          = dummList;
                dataGrid.ItemsSource = AmazonItems;
                await storeAmazonItemsAsync();
            }
            return(null);
        }
        private void RemoveContextMenuClick(object sender, RoutedEventArgs e)
        {
            var        b    = sender as FrameworkElement;
            AmazonItem item = b.DataContext as AmazonItem;

            AmazonItems.Remove(item);
            storeAmazonItemsAsync();
        }
        private async System.Threading.Tasks.Task AppendItemDataAsync(AmazonItem item)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   file          = await storageFolder.CreateFileAsync("items.txt", Windows.Storage.CreationCollisionOption.OpenIfExists);

            string[] line = { item.ToString() };
            await Windows.Storage.FileIO.AppendLinesAsync(file, line);
        }
Ejemplo n.º 5
0
        private static byte[] GetURLContents(string url)
        {
            // The downloaded resource ends up in the variable named content.
            var content = new MemoryStream();

            // Initialize an HttpWebRequest for the current URL.
            var webReq = (HttpWebRequest)WebRequest.Create(url);

            // Send the request to the Internet resource and wait for
            // the response.
            // Note: you can't use HttpWebRequest.GetResponse in a Windows Store app.
            using (WebResponse response = webReq.GetResponse())
            {
                // Get the data stream that is associated with the specified URL.
                using (Stream responseStream = response.GetResponseStream())
                {
                    // Read the bytes in responseStream and copy them to content.
                    responseStream.CopyTo(content);
                }
            }

            // parse and add AmazonItem into collection
            string html = UTF8Encoding.UTF8.GetString(content.ToArray());

            string[] lines  = html.Split(new char[] { '\n' });
            bool     start  = false;
            string   useful = string.Empty;

            foreach (string line in lines)
            {
                if (line.Contains("<div class=\"zg_itemImageImmersion\">"))
                {
                    start = true;
                }
                if (start)
                {
                    useful += line;
                    if (line.Contains("<img src="))
                    {
                        string title = RegexHelper.GrabPattern(useful, "title=\"", "\" onload");
                        if (string.IsNullOrEmpty(title))
                        {
                            title = RegexHelper.GrabPattern(useful, "title=\"", "\"/>");
                        }
                        string     u    = RegexHelper.GrabPattern(useful, "href=\"", "\"><img");
                        AmazonItem item = new AmazonItem(title, u);
                        items.Add(item);
                        System.Diagnostics.Debug.WriteLine(item.ToString());

                        start  = false;
                        useful = string.Empty;
                    }
                }
            }

            // Return the result as a byte array.
            return(content.ToArray());
        }
Ejemplo n.º 6
0
 public ProductAmazonVm(AmazonItem amazonItem)
 {
     ASIN        = amazonItem.ASIN;
     Title       = amazonItem.Title.Replace("\"", string.Empty);
     Description = amazonItem.Description.Replace("\"", string.Empty);
     Image       = amazonItem.Image;
     Author      = amazonItem.Author;
     Amount      = amazonItem.Price.ToString();
 }
Ejemplo n.º 7
0
        public void SeriesTest()
        {
            AmazonItem target   = new AmazonItem("The Index Card: Why Personal Finance Doesn’t Have to Be Complicated", @"http://www.amazon.com/The-Index-Card-Personal-Complicated/dp/1591847680/ref=zg_bs_2665_1");
            string     expected = "1591847680";
            string     actual   = target.Series;

            Console.WriteLine(actual);
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 8
0
    public void itemDataRequestFinished(string json)
    {
        if (itemDataRequestFinishedEvent != null)
        {
            var ht = json.hashtableFromJson();
            var unavailableSkus = ht["unavailableSkus"] as ArrayList;
            var availableSkus   = ht["availableSkus"] as ArrayList;

            itemDataRequestFinishedEvent(unavailableSkus.ToList <string>(), AmazonItem.fromArrayList(availableSkus));
        }
    }
        private void CopyURLContextMenuClick(object sender, RoutedEventArgs e)
        {
            var        b    = sender as FrameworkElement;
            AmazonItem item = b.DataContext as AmazonItem;

            DataPackage dataPackage = new DataPackage();

            dataPackage.RequestedOperation = DataPackageOperation.Copy;
            dataPackage.SetText(item.productURL);
            Clipboard.SetContent(dataPackage);
        }
        private async void VisitContextMenuClick(object sender, RoutedEventArgs e)
        {
            var        b    = sender as FrameworkElement;
            AmazonItem item = b.DataContext as AmazonItem;
            var        uri  = new Uri(@"" + item.productURL);

            var success = await Windows.System.Launcher.LaunchUriAsync(uri);

            if (success)
            {
                Debug.WriteLine("URI: Success");
            }
            else
            {
                Debug.WriteLine("URI: failed");
            }
        }
        //add an AmazonItem to the database and return its id
        private int AddAmazonItem(AmazonItem item)
        {
            //create a Product object from the model
            var product = new Product()
            {
                ProductType         = ProductType.SimpleProduct,
                VisibleIndividually = true,
                Name            = item.Title,
                AdminComment    = "ASIN=" + item.ASIN + ";",
                FullDescription = item.Description,

                //the following properties were copy-pasted from samples
                Price                         = item.Price,
                ProductTemplateId             = _productTemplateRepository.Table.FirstOrDefault(pt => pt.Name == "Simple product").Id,
                AllowCustomerReviews          = true,
                OrderMinimumQuantity          = 1,
                OrderMaximumQuantity          = 10000,
                ManageInventoryMethod         = ManageInventoryMethod.ManageStock,
                NotifyAdminForQuantityBelow   = 1,
                DisplayStockAvailability      = true,
                LowStockActivity              = LowStockActivity.DisableBuyButton,
                BackorderMode                 = BackorderMode.NoBackorders,
                AllowBackInStockSubscriptions = false,
                Published                     = true,
                CreatedOnUtc                  = DateTime.UtcNow,
                UpdatedOnUtc                  = DateTime.UtcNow
            };

            //add an image to the product
            byte[] imageBinary;
            using (var client = new WebClient())
            {
                imageBinary = client.DownloadData(item.ImageUrl);
            }
            product.ProductPictures.Add(new ProductPicture()
            {
                Picture      = _pictureService.InsertPicture(imageBinary, MimeMapping.GetMimeMapping(item.ImageUrl), _pictureService.GetPictureSeName(product.Name), true),
                DisplayOrder = 1,
            });

            //add the product to the database
            _productService.InsertProduct(product);

            return(product.Id);
        }
        private async void add_button_Click(object sender, RoutedEventArgs e)
        {
            progressRing.IsActive = true;
            String url           = url_text_box.Text;
            String desired_price = desired_price_text_box.Text;

            List <String> itemProperties = await getAmazonItemFromURLAsync(url);


            if (itemProperties != null)
            {
                try
                {
                    AmazonItem item = new AmazonItem(itemProperties[0], itemProperties[1], double.Parse(desired_price.Trim()), itemProperties[2], itemProperties[3]);
                    if (item.productPrice <= item.desiredPrice && item.productStatus.Equals("Available") && item.previousPrice != item.productPrice)
                    {
                        createWindowsToast(item);
                    }
                    _ = AppendItemDataAsync(item);
                    _ = StoreURLDataAsync(url, desired_price);
                    AmazonItems.Add(item);
                    await storeAmazonItemsAsync();

                    await lib.Toggle();
                }
                catch (Exception er)
                {
                    Debug.WriteLine(er.StackTrace);
                    MessageDialog message = new MessageDialog("An error occured! Please try again.");
                    message.Title = "Error";
                    await message.ShowAsync();
                }
                finally
                {
                    progressRing.IsActive       = false;
                    url_text_box.Text           = "";
                    desired_price_text_box.Text = "";
                }
            }
        }
        public ActionResult CreateFromASIN(AmazonImportModel.CreateFromASINModel model)
        {
            //allow this page to been seen only after logging in
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            {
                return(null);
            }

            if (ModelState.IsValid)
            {
                var allASINs = GetAllAmazonProductASINs();
                if (GetAllAmazonProductASINs().Contains(model.ASIN))                 //product already exists, show error
                {
                    ModelState["ASIN"].Errors.Add("A product with this ASIN already exists");
                }
                else
                {
                    AmazonItem item = AmazonSearcher.GetItem(model.ASIN);

                    if (item != null)                    //item was found on Amazon
                    {
                        //add the created Product to the database
                        int productId = AddAmazonItem(item);

                        //open "Edit product" page for the newly created product
                        return(RedirectToAction("Edit", "Product", new { id = productId }));
                    }
                    else                     //item was not found
                    {
                        ModelState["ASIN"].Errors.Add("An item with this ASIN was not found on Amazon");
                    }
                }         //if (GetAllAmazonProductASINs().Contains(model.ASIN))
            }             //if ModelState.IsValid

            //problem occured, display the form again with an appropriate error message
            return(View("Nop.Plugin.Misc.AmazonImport.Views.MiscAmazonImport.CreateFromASIN", model));
        }
        public ActionResult CreateFromASIN(string ASIN)
        {
            //allow this page to been seen only after logging in
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            {
                return(null);
            }

            if (ASIN == null)             //no ASIN supplied, show form
            {
                var model = new AmazonImportModel.CreateFromASINModel();
                return(View("Nop.Plugin.Misc.AmazonImport.Views.MiscAmazonImport.CreateFromASIN", model));
            }

            //if product already exists, show error
            if (GetAllAmazonProductASINs().Contains(ASIN))
            {
                return(View("Nop.Plugin.Misc.AmazonImport.Views.MiscAmazonImport.ItemAlreadyExists"));
            }

            //search for product form amazon
            AmazonItem item = AmazonSearcher.GetItem(ASIN);

            if (item != null)             //add product to database and open the product editing form
            {
                int productId = AddAmazonItem(item);

                //open "Edit product" page for the newly created product
                return(RedirectToAction("Edit", "Product", new { id = productId }));
            }
            else             //product could no longer be found on amazon
            {
                _logger.Error("Adding product failed: product could no longer be found on Amazon");
                return(null);
            }
        }
Ejemplo n.º 15
0
        public List<AmazonItem> GetProducts(string url)
        {
            string strResult = string.Empty;
            List<AmazonItem> items = new List<AmazonItem>();
            try
            {
                WebRequest request = HttpWebRequest.Create(url);
                WebResponse response = request.GetResponse();
                XmlDocument doc = new XmlDocument();
                //using (Stream stream = response.GetResponseStream())
                //{
                //    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                //    String responseString = reader.ReadToEnd();
                //}

                doc.Load(response.GetResponseStream());

                XmlNodeList errorMessageNodes = doc.GetElementsByTagName("Message");
                if (errorMessageNodes != null && errorMessageNodes.Count > 0)
                {
                    String message = errorMessageNodes.Item(0).InnerText;

                }

                string price = null;
                // custom to whatever ResponseGroup you chose

                string s;

                foreach (XmlElement node in doc.GetElementsByTagName("Item"))
                {
                   product  = new AmazonItem();

                   try
                   {
                       string pages = doc.GetElementsByTagName("TotalPages")[0].InnerText;
                       string keywords = doc.GetElementsByTagName("Keywords")[0].InnerText;
                       string searchIndex = doc.GetElementsByTagName("SearchIndex")[0].InnerText;
                       product.pagecount = pages;
                       product.keyword = keywords;
                       product.SearchIndex = searchIndex;
                   }
                   catch (Exception ex) { }

                    product.ProductId = node.ChildNodes[0].InnerText;

                    var offers = node.GetElementsByTagName("Offers");
                    var links = node.GetElementsByTagName("ItemLinks");
                    var feature = node.GetElementsByTagName("Feature");
                    var listp = node.GetElementsByTagName("ListPrice");
                   product.imageSets = GetImages(node.GetElementsByTagName("ImageSets"));
                    var attributes = node.GetElementsByTagName("ItemAttributes");
                    var dimensions = node.GetElementsByTagName("ItemDimensions");

                    product.ListPrices = GetPrice(listp);
                    product.Label = node.GetElementsByTagName("Label")[0].InnerText  ?? "N/A";
                    product.LargeImage = node.GetElementsByTagName("LargeImage")[0].ChildNodes[0].InnerText ?? "N/A";
                    product.MediumImage = node.GetElementsByTagName("MediumImage")[0].ChildNodes[0].InnerText ?? "N/A";
                    product.SmallImage = node.GetElementsByTagName("SmallImage")[0].ChildNodes[0].InnerText ?? "N/A";
                    product.Title = node.GetElementsByTagName("Title")[0].InnerText ?? "N/A";

                    Offers(offers);
                    Links(links);
                    Attributes(attributes);

                    items.Add(product);
                }

                response.Close();

            }

            catch (Exception ex)
            {

            }

            return items;
        }
Ejemplo n.º 16
0
        public static List <AmazonItem> getItems(string url) //amazon-i url ning vastu saab List<AmazonItem>
        {
            List <AmazonItem> ami = new List <AmazonItem>();

            try
            {
                xml_source += url + "\n<br />\n<br />";
                string            def_xmlns    = "";
                XPathDocument     document     = new XPathDocument(url);
                XPathNavigator    navigator    = document.CreateNavigator();
                XPathNodeIterator nodeIterator = navigator.Select(@"//namespace::*[not(. = ../../namespace::*)]");
                while (nodeIterator.MoveNext())
                {
                    if (nodeIterator.Current.LocalName.Equals(""))
                    {
                        def_xmlns = nodeIterator.Current.Value;
                    }
                }
                XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
                manager.AddNamespace("x", def_xmlns);
                try
                {
                    err += navigator.SelectSingleNode("//*/x:Items/x:Request/x:Errors/x:Error/x:Message", manager).ToString() + "\n<br />";
                }
                catch (Exception)
                {
                    //Kui siin viga tekib, siis see tähendab suure tõenäosusega, et tegelikult viga ei olnud
                }
                XPathNodeIterator nodes = navigator.Select("//*/x:Items/x:Item", manager);
                tothits  = navigator.SelectSingleNode("//*/x:TotalResults", manager).ToString();
                totpages = navigator.SelectSingleNode("//*/x:TotalPages", manager).ToString();
                int totalItems = toint(tothits);

                Console.WriteLine("Total: " + tothits);
                string isValid = navigator.SelectSingleNode("//*/x:Items/x:Request/x:IsValid", manager).ToString();
                Console.WriteLine("IsValid=" + isValid);
                // err = "NNE";

                Console.WriteLine("ErrorMessage:\n" + err);
                if (isValid.Equals("False"))
                {
                    Console.WriteLine("ErrorMessage:\n" + err);
                }
                string searchIndex = navigator.SelectSingleNode("//*/x:Items/x:Request/x:ItemSearchRequest/x:SearchIndex", manager).ToString();

                //string tot = navigator.SelectSingleNode("//*/x:TotalResults", manager).ToString();
                //Console.WriteLine(tot);
                //string err = navigator.SelectSingleNode("//*/x:Errors/x:Error/x:Message", manager).ToString();
                //Console.WriteLine(err);
                Console.ReadLine();
                foreach (XPathNavigator nodeItem in nodes)
                {
                    string Title          = "NOTITLE";
                    string Code           = "NOCODE";
                    string Price          = "0";
                    string FormattedPrice = "USD";
                    string Image          = "http://www.urti.org/images/no-image.gif";
                    string ImageHeight    = "160";
                    string ImageWidth     = "120";

                    try
                    {
                        Title = nodeItem.SelectSingleNode("x:ItemAttributes/x:Title", manager).ToString();
                    }
                    catch (Exception e)
                    {
                        err2 += e.ToString();
                    }
                    try
                    {
                        Code = nodeItem.SelectSingleNode("x:OfferSummary/x:*/x:CurrencyCode", manager).ToString();
                    }
                    catch (Exception e)
                    {
                        err2 += e.ToString();
                    }
                    try
                    {
                        Price = nodeItem.SelectSingleNode("x:OfferSummary/x:*/x:Amount", manager).ToString();
                    }
                    catch (Exception e)
                    {
                        err2 += e.ToString();
                    }
                    try
                    {
                        FormattedPrice = nodeItem.SelectSingleNode("x:OfferSummary/x:*/x:FormattedPrice", manager).ToString();
                    }
                    catch (Exception e)
                    {
                        err2 += e.ToString();
                    }
                    try
                    {
                        Image       = nodeItem.SelectSingleNode("x:MediumImage/x:URL", manager).ToString();
                        ImageHeight = nodeItem.SelectSingleNode("x:MediumImage/x:Height", manager).ToString();
                        ImageWidth  = nodeItem.SelectSingleNode("x:MediumImage/x:Width", manager).ToString();
                    }
                    catch (Exception e)
                    {
                        err2 += e.ToString();
                    }
                    AmazonItem ai = new AmazonItem();
                    ai.Title       = Title;
                    ai.Price       = (toint(Price) * 1.0) / 100.0;
                    ai.Img         = Image;
                    ai.ImgHeight   = ImageHeight;
                    ai.ImgWidth    = ImageWidth;
                    ai.SearchIndex = searchIndex;
                    ai.Code        = Code;
                    ami.Add(ai);
                    //Console.WriteLine(counter++ + ": " + Title + " " + (toint(Price)*1.0)/100.0 + " " + Code);
                }
                return(ami);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                err2 += e.ToString() + "\n<br />";
                return(ami);
            }
        }
        public static Container ConvertToShipDTO(TOTMASTR totMastr)
        {
            if (!string.IsNullOrWhiteSpace(totMastr.PALLET_ASN)) // Ship only needs to know about the pallet records if the given carton is on a pallet
            {
                return(null);
            }

            if ((totMastr.ACCUM_QTY == null || totMastr.ACCUM_QTY == 0) &&
                (totMastr.ACTION != (short)TotMastrActions.PrePrintCartonLabel && totMastr.ACTION != (short)TotMastrActions.PreRateOrder)) // Don't send Ship records with no quantity associated, unless it is a pre-print or pre-rate
            {
                return(null);
            }

            Container           container           = new Container();
            string              ltlPackageType      = null;
            WarehouseSyncClient warehouseSyncClient = WarehouseConnectionAdapter.GetNewWarehouseSyncClient();

            try
            {
                #region Load External Data
                IList <TOTEDETL> totDetls           = null;
                List <string>    toteLabelsOnPallet = new List <string>()
                {
                    totMastr.TOTLABEL
                };

                if (!string.IsNullOrWhiteSpace(totMastr.IS_PALLET) && totMastr.IS_PALLET == "1")
                {
                    IList <TOTMASTR> totMastrsOnPallet = warehouseSyncClient.FindAllTOTMASTRPaged(TOTMASTRHydration.None,
                                                                                                  string.Format("TOTMASTR.Where(item => item.PALLET_ASN == \"{0}\" && item.ACCUM_QTY > 0 && item.SHP_CNSLDT == \"{1}\")", totMastr.CARTON_ASN, totMastr.SHP_CNSLDT));

                    if (totMastrsOnPallet != null && totMastrsOnPallet.Count > 0)
                    {
                        toteLabelsOnPallet.AddRange(totMastrsOnPallet.Select(tmp => tmp.TOTLABEL).Distinct());
                    }
                }

                string totDetlQuery = "TOTEDETL.Where(item => ";

                foreach (string toteLabelOnPallet in toteLabelsOnPallet)
                {
                    totDetlQuery += string.Format("item.TOTLABEL == \"{0}\" || ", toteLabelOnPallet);
                }

                totDetlQuery = totDetlQuery.Substring(0, totDetlQuery.Length - 4) + ")";

                totDetls = warehouseSyncClient.FindAllTOTEDETLPaged(TOTEDETLHydration.None,
                                                                    string.Format("{0}.Take({1})", totDetlQuery, WarehouseIntegrationConfig.Instance.PageSize));
                int i = 0;

                while (totDetls != null && totDetls.Count > 0)
                {
                    i++;

                    IList <TOTEDETL> remainingTotdetls = warehouseSyncClient.FindAllTOTEDETLPaged(TOTEDETLHydration.None,
                                                                                                  string.Format("{0}.Take({1}).Skip({2})", totDetlQuery, WarehouseIntegrationConfig.Instance.PageSize, (i * WarehouseIntegrationConfig.Instance.PageSize)));

                    if (remainingTotdetls == null || remainingTotdetls.Count == 0)
                    {
                        break;
                    }

                    foreach (TOTEDETL remainingTotdetl in remainingTotdetls)
                    {
                        totDetls.Add(remainingTotdetl);
                    }
                }
                #endregion

                #region ContainerOption
                container.ContainerOption = new ContainerOption();
                container.ContainerOption.AdditionalHandling           = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("H")) ? true : false;
                container.ContainerOption.AdultSignatureRequired       = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("A")) ? true : false;
                container.ContainerOption.AppointmentDelivery          = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("D")) ? true : false;
                container.ContainerOption.DoNotSafeDrop                = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("1")) ? true : false;
                container.ContainerOption.ProofRequireSignatureAdult19 = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("2")) ? true : false;
                container.ContainerOption.LeaveAtDoor = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("3")) ? true : false;

                if (!string.IsNullOrWhiteSpace(totMastr.COD) && totMastr.COD == "C")
                {
                    container.CODContainer = true;
                    container.ContainerOption.CODAmount = totMastr.SHIP_COD;

                    if (!string.IsNullOrWhiteSpace(totMastr.COD_PAY))
                    {
                        container.ContainerOption.CODPaymentType = ShipXMLMapsAdapter.GetShipCODPaymentTypeCode(totMastr.COD_PAY);
                    }
                }

                container.ContainerOption.DeliveryConfirmation         = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("C")) ? true : false;
                container.ContainerOption.FedExDirectSignatureRequired = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("T")) ? true : false;

                if (!string.IsNullOrWhiteSpace(totMastr.IS_PALLET) && totMastr.IS_PALLET == "1")
                {
                    container.ContainerOption.InnerPackageCount = warehouseSyncClient.FindAllTOTMASTRCount(
                        string.Format("TOTMASTR.Where(item => item.PALLET_ASN == \"{0}\" && item.ACCUM_QTY > 0 && item.SHP_CNSLDT == \"{1}\")", totMastr.CARTON_ASN, totMastr.SHP_CNSLDT));

                    ltlPackageType = "Pallet";
                }
                else
                {
                    container.ContainerOption.InnerPackageCount = 1;
                    ltlPackageType = "Carton";
                }

                if (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("I"))
                {
                    container.ContainerOption.InsuranceType = 1;
                    container.TransmitDeclaredValue         = true;
                }

                container.ContainerOption.SignatureRequired = (!string.IsNullOrWhiteSpace(totMastr.SHP_OPTION) && totMastr.SHP_OPTION.Contains("S")) ? true : false;
                #endregion

                #region ContainerReferenceFields
                container.ContainerReferenceFields = new ContainerReferenceFields()
                {
                    ReferenceField1 = StringUtils.Left(totMastr.MESSAGE1, 50),
                    ReferenceField2 = StringUtils.Left(totMastr.MESSAGE2, 50),
                    ReferenceField3 = StringUtils.Left(totMastr.MESSAGE3, 50),
                    ReferenceField4 = StringUtils.Left(totMastr.MESSAGE4, 50),
                    ReferenceField5 = StringUtils.Left(totMastr.MESSAGE5, 50)
                };
                #endregion

                container.DeclaredValueAmount = totMastr.SHIP_DV;
                container.DocumentNumber      = StringUtils.Left(totMastr.PACKSLIP, 30);
                container.Height        = totMastr.SHIP_HEIGHT;
                container.IdentityField = StringUtils.Left(totMastr.CARTON_ASN, 50);
                container.Length        = totMastr.SHIP_LENGTH;

                #region PackageType
                if (totMastr.SHP_OPTION.Contains("F"))
                {
                    container.PackageType = "LETTER";
                }

                if (totMastr.SHP_OPTION.Contains("G"))
                {
                    container.PackageType = "SBOX";
                }

                if (totMastr.SHP_OPTION.Contains("K"))
                {
                    container.PackageType = "MBOX";
                }

                if (totMastr.SHP_OPTION.Contains("J"))
                {
                    container.PackageType = "LBOX";
                }

                if (totMastr.SHP_OPTION.Contains("X"))
                {
                    container.PackageType = "BOX";
                }

                if (totMastr.SHP_OPTION.Contains("N"))
                {
                    container.PackageType = "USPSRRBA";
                }

                if (totMastr.SHP_OPTION.Contains("O"))
                {
                    container.PackageType = "USPSRRBB";
                }

                if (totMastr.SHP_OPTION.Contains("P"))
                {
                    container.PackageType = "USPSRRBC";
                }

                if (totMastr.SHP_OPTION.Contains("U"))
                {
                    container.PackageType = "PAK";
                }

                if (totMastr.SHP_OPTION.Contains("V"))
                {
                    container.PackageType = "MDEXBX";
                }

                if (totMastr.SHP_OPTION.Contains("Y"))
                {
                    container.PackageType = "LGEXBX";
                }

                if (totMastr.SHP_OPTION.Contains("?"))
                {
                    container.PackageType = "TUBE";
                }

                if (totMastr.SHP_OPTION.Contains("!"))
                {
                    container.PackageType = "FRE";
                }

                if (totMastr.SHP_OPTION.Contains("Q"))
                {
                    container.PackageType = "EXLGEXBX";
                }

                if (totMastr.SHP_OPTION.Contains("$"))
                {
                    container.PackageType = "SMEXBX";
                }

                if (string.IsNullOrWhiteSpace(container.PackageType))
                {
                    container.PackageType = "CUSTOM";
                }
                #endregion

                container.PONumber  = StringUtils.Left(totMastr.CUST_ORDER, 50);
                container.Shippable = true;                 // Currently hard-coded since this is a "ship" integration as of today, not a "pack" integration

                if (totMastr.ACTION == (short)TotMastrActions.RateManifestShipment || totMastr.ACTION == (short)TotMastrActions.DeleteCarton)
                {
                    if (ShipIntegrationConfig.Instance.UseLastMileTrackingNumber)
                    {
                        container.TrackingNumber = string.IsNullOrWhiteSpace(totMastr.CAPTUREDBC) ? StringUtils.Left(totMastr.TRACKTRACE, 50) : StringUtils.Left(totMastr.CAPTUREDBC, 50);
                    }
                    else
                    {
                        container.TrackingNumber = StringUtils.Left(totMastr.TRACKTRACE, 50);
                    }
                }

                container.UOM = new UOM()
                {
                    Name = StringUtils.Left(ShipIntegrationConfig.Instance.WeightUnitOfMeasure, 50)
                };
                container.Weight = totMastr.WEIGHT == null || totMastr.WEIGHT == 0 ? ShipIntegrationConfig.Instance.DefaultContainerWeight : totMastr.WEIGHT;
                container.Width  = totMastr.SHIP_WIDTH;

                #region AmazonItems, ContainerCIs, and LTLData
                if ((totDetls == null || totDetls.Count == 0) && totMastr.ACTION == (short)TotMastrActions.PreRateOrder)
                {
                    LTLData ltlData = new LTLData()
                    {
                        CommodityClass = StringUtils.Left(ShipIntegrationConfig.Instance.ForcedPreRateCommodityClass, 50)
                    };

                    container.LTLDatas.Add(ltlData);
                }

                foreach (TOTEDETL totDetl in totDetls)
                {
                    IList <Config>   configs        = null;
                    IList <ProdMstr> ciLTLProdMstrs = null;
                    IList <CUBISCAN> cubiscans      = null;
                    ContainerCI      containerCI    = new ContainerCI();
                    LTLData          ltlData        = new LTLData();

                    #region Load External Data
                    configs        = warehouseSyncClient.FindAllConfigPaged(ConfigHydration.None, "Config.Where(item => item.ConfigKey.StartsWith(\"PACKSIZE_\"))");
                    ciLTLProdMstrs = warehouseSyncClient.FindProdMstrsBySearchCriteriaPaged(new ProdMstrsBySearchCriteria()
                    {
                        Extended = totDetl.EXTENDED
                    },
                                                                                            ProdMstrHydration.None, 0, 1);
                    cubiscans = warehouseSyncClient.FindAllCUBISCANPaged(CUBISCANHydration.None,
                                                                         string.Format("CUBISCAN.Where(item => item.PRODUCT == \"{0}\" && item.PACKSIZE == {1}).Take(1)", totDetl.PRODUCT, totDetl.PACKSIZE));
                    #endregion

                    #region AmazonItems
                    if (IsAmazonOrder(totMastr.SHP_OPTION))
                    {
                        AmazonItem amazonItem = new AmazonItem();

                        amazonItem.Container = container;

                        var pickDetls = warehouseSyncClient.FindAllPickDetlPaged(PickDetlHydration.None, string.Format("PickDet.Where(item => item.PackSlip == \"{0}\" && item.LineNumber == \"{1}\")",
                                                                                                                       totDetl.PACKSLIP, totDetl.ORDER_SEQ));

                        if (pickDetls == null || pickDetls.Count == 0)
                        {
                            throw new Exception("One or more items on the shipment did not provide an Amazon item identifier!");
                        }

                        if (ShipIntegrationConfig.Instance.AmazonAssumeBoxPerLine && pickDetls[0].IS_CMPN == "E") // This is a kit component, thus the kit parent needs looking up for the Amazon item ID
                        {
                            string[] splitKitLineNum = totDetl.ORDER_SEQ.Split('.');                              // Kit component line numbers look like this: 1.001
                            string   parentLineNum   = splitKitLineNum[0];                                        // Putting this into a variable for code readability
                            var      parentPickDetls = warehouseSyncClient.FindAllPickDetlPaged(PickDetlHydration.None,
                                                                                                string.Format("PickDet.Where(item => item.PackSlip == \"{0}\" && item.LineNumber == \"{1}\")", totDetl.PACKSLIP, parentLineNum));
                            if (parentPickDetls == null || parentPickDetls.Count == 0 || string.IsNullOrWhiteSpace(parentPickDetls[0].CustomerCrossReference))
                            {
                                throw new Exception("One or more items on the shipment did not provide an Amazon item identifier!");
                            }
                            amazonItem.ItemId   = StringUtils.Left(parentPickDetls[0].CustomerCrossReference, 128);
                            amazonItem.Quantity = parentPickDetls[0].QuantityPicked;
                        }
                        else                         // This is a regular item, not a kit
                        {
                            if (string.IsNullOrWhiteSpace(pickDetls[0].CustomerCrossReference))
                            {
                                throw new Exception("One or more items on the shipment did not provide an Amazon item identifier!");
                            }
                            amazonItem.ItemId   = StringUtils.Left(pickDetls[0].CustomerCrossReference, 128);
                            amazonItem.Quantity = totDetl.QTY;
                        }

                        container.AmazonItems.Add(amazonItem);
                    }
                    #endregion

                    #region ContainerCI
                    containerCI.Container            = container;
                    containerCI.CountryOfManufacture = StringUtils.Left(totDetl.CTRY_ORIG, 2);
                    containerCI.HarmonizedTariffCode = StringUtils.Left(totDetl.TariffClass, 10);
                    containerCI.Quantity             = totDetl.QTY;
                    containerCI.UnitValue            = totDetl.SELL_PRICE;

                    if (!string.IsNullOrWhiteSpace(totMastr.SHIP_VIA) && !string.IsNullOrWhiteSpace(totMastr.SHIP_SERVC) &&
                        (totMastr.SHIP_VIA.StartsWith("DHLGM") || totMastr.SHIP_VIA.StartsWith("DHLAMP") || totMastr.SHIP_VIA.StartsWith("GLOBEG")))
                    {
                        containerCI.CIDescription = StringUtils.Left(string.Format("{0} - {1}", StringUtils.Left(totDetl.PRODUCT, 20), totDetl.DESCRIPT), 250);
                    }
                    else
                    {
                        containerCI.CIDescription = StringUtils.Left(totDetl.CommodityDescription, 250);
                    }

                    if (ciLTLProdMstrs != null && ciLTLProdMstrs.Count > 0)
                    {
                        containerCI.UnitWeight = ciLTLProdMstrs[0].Weight;

                        if (totDetl.PACKSIZE.HasValue && configs != null && configs.Count > 0)
                        {
                            if (ciLTLProdMstrs[0].Size1 == totDetl.PACKSIZE && configs.Any(item => item.ConfigKey == "PACKSIZE_1"))
                            {
                                containerCI.QuantityUOM = StringUtils.Left(configs.Where(item => item.ConfigKey == "PACKSIZE_1").First().CValue, 10);
                            }
                            else if (ciLTLProdMstrs[0].Size2 == totDetl.PACKSIZE && configs.Any(item => item.ConfigKey == "PACKSIZE_2"))
                            {
                                containerCI.QuantityUOM = StringUtils.Left(configs.Where(item => item.ConfigKey == "PACKSIZE_2").First().CValue, 10);
                            }
                            else if (ciLTLProdMstrs[0].Size3 == totDetl.PACKSIZE && configs.Any(item => item.ConfigKey == "PACKSIZE_3"))
                            {
                                containerCI.QuantityUOM = StringUtils.Left(configs.Where(item => item.ConfigKey == "PACKSIZE_3").First().CValue, 10);
                            }
                            else if (ciLTLProdMstrs[0].Size4 == totDetl.PACKSIZE && configs.Any(item => item.ConfigKey == "PACKSIZE_4"))
                            {
                                containerCI.QuantityUOM = StringUtils.Left(configs.Where(item => item.ConfigKey == "PACKSIZE_4").First().CValue, 10);
                            }
                            else if (ciLTLProdMstrs[0].Size5 == totDetl.PACKSIZE && configs.Any(item => item.ConfigKey == "PACKSIZE_5"))
                            {
                                containerCI.QuantityUOM = StringUtils.Left(configs.Where(item => item.ConfigKey == "PACKSIZE_5").First().CValue, 10);
                            }
                        }
                    }

                    if (cubiscans != null && cubiscans.Count > 0)
                    {
                        containerCI.UnitWeight = cubiscans[0].WEIGHT;
                    }

                    container.ContainerCIs.Add(containerCI);
                    #endregion

                    #region LTLDatas
                    ltlData.CommodityClassDescription = StringUtils.Left(totDetl.CommodityDescription, 100);
                    ltlData.Container         = container;
                    ltlData.InnerPackageCount = 1;
                    ltlData.PackageType       = ltlPackageType;

                    if (totMastr.ACTION == (short)TotMastrActions.PreRateOrder && !string.IsNullOrWhiteSpace(ShipIntegrationConfig.Instance.ForcedPreRateCommodityClass))
                    {
                        ltlData.CommodityClass = StringUtils.Left(ShipIntegrationConfig.Instance.ForcedPreRateCommodityClass, 50);
                    }
                    else
                    {
                        ltlData.CommodityClass = StringUtils.Left(!string.IsNullOrWhiteSpace(totDetl.FreightClass) ? totDetl.FreightClass : ShipIntegrationConfig.Instance.DefaultCommodityClass, 50);
                    }

                    if (!string.IsNullOrWhiteSpace(totDetl.NMFCNumber))
                    {
                        if (totDetl.NMFCNumber.Contains("-"))
                        {
                            string[] splitNMFC = totDetl.NMFCNumber.Split('-');

                            ltlData.NMFCCode    = StringUtils.Left(splitNMFC[0], 50);
                            ltlData.NMFCItemSub = StringUtils.Left(splitNMFC[1], 10);
                        }
                        else
                        {
                            ltlData.NMFCCode = StringUtils.Left(totDetl.NMFCNumber, 50);
                        }
                    }

                    if (ciLTLProdMstrs != null && ciLTLProdMstrs.Count > 0)
                    {
                        //if (totDetls.Count > 1)
                        //    ltlData.Weight = ciLTLProdMstrs[0].Weight;
                        //else
                        //    ltlData.Weight = container.Weight;

                        if (ciLTLProdMstrs[0].Weight != null && totDetl.QTY != null)
                        {
                            ltlData.Weight = ciLTLProdMstrs[0].Weight * totDetl.QTY;
                        }
                    }

                    container.LTLDatas.Add(ltlData);
                    #endregion
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (warehouseSyncClient != null)
                {
                    warehouseSyncClient.Close();
                    warehouseSyncClient = null;
                }
            }

            return(container);
        }