Beispiel #1
0
        private void FedExOperations(DataRow dr)
        {
            // Set this to true to process a COD shipment and print a COD return Label
            bool isCodShipment             = false;
            ProcessShipmentRequest request = CreateShipmentRequest(isCodShipment, dr);

            //
            ShipWebServiceClient.ShipServiceWebReference.ShipService service = new ShipWebServiceClient.ShipServiceWebReference.ShipService();
            if (usePropertyFile())
            {
                service.Url = getProperty("endpoint");
            }
            //
            try
            {
                // Call the ship web service passing in a ProcessShipmentRequest and returning a ProcessShipmentReply
                ProcessShipmentReply reply = service.processShipment(request);
                if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING)
                {
                    ShowShipmentReply(isCodShipment, reply, txtLblPath.Text);
                }
                ShowNotifications(reply);
            }
            catch (SoapException e)
            {
                Console.WriteLine(e.Detail.InnerText);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            //Console.WriteLine("\nPress any key to quit !");
            //Console.ReadKey();
        }
Beispiel #2
0
        public override void CreateShipment()
        {
            ShipReply result = null;
            ProcessShipmentRequest request = CreateShipmentRequest();

            try
            {
                ShipService service = new ShipService();
                service.Url = Url;
                ProcessShipmentReply reply = service.processShipment(request);
                if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
                {
                    result = SetShipmentReply(reply);
                }
                else
                {
                    if (reply.Notifications.Length > 0)
                    {
                        ErrorMessage = string.Format("{0} {1}", reply.Notifications[0].Code, reply.Notifications[0].Message);
                    }
                }

                ShipReplyEx = result;
            }
            catch (SoapException e)
            {
                Debug.WriteLine(e.Detail.InnerText);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            // return result;
        }
        public void ExecuteRequest()
        {
            ShipService service = new ShipService();

            try
            {
                if (_request.RequestedShipment == null)
                {
                    return;
                }

                _reply = service.processShipment(_request);
                foreach (CompletedPackageDetail packageDetail in _reply.CompletedShipmentDetail.CompletedPackageDetails)
                {
                    _trackingIds = packageDetail.TrackingIds;
                    if (packageDetail.PackageRating != null && packageDetail.PackageRating.PackageRateDetails != null)
                    {
                        _packageRateDetails = packageDetail.PackageRating.PackageRateDetails;
                    }
                    else
                    {
                        Console.WriteLine("No Rating information returned.\n");
                    }
                    _completedPackageDetail  = packageDetail;
                    _completedShipmentDetail = _reply.CompletedShipmentDetail;
                }
            }
            catch (SoapException e)
            {
            }
            catch (Exception e)
            {
            }
        }
Beispiel #4
0
 private static void ShowShipmentReply(ProcessShipmentReply reply)
 {
     Console.WriteLine("Shipment Reply details:");
     // Details for each package
     foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
     {
         ShowTrackingDetails(packageDetail.TrackingIds);
         if (null != reply.CompletedShipmentDetail.ShipmentRating)
         {
             ShowPackageRateDetails(reply.CompletedShipmentDetail.ShipmentRating);
         }
         else
         {
             Console.WriteLine("Shipment Rates not returned/");
         }
         if (null != packageDetail.Label.Parts[0].Image)
         {
             // Save outbound shipping label
             string LabelPath = "c:\\";
             if (usePropertyFile())
             {
                 LabelPath = getProperty("labelpath");
             }
             string LabelFileName = LabelPath + packageDetail.TrackingIds[0].TrackingNumber + ".pdf";
             SaveLabel(LabelFileName, packageDetail.Label.Parts[0].Image);
         }
         ShowBarcodeDetails(packageDetail.OperationalDetail.Barcodes);
     }
     ShowPackageRouteDetails(reply.CompletedShipmentDetail.OperationalDetail);
 }
Beispiel #5
0
        /// <summary>
        /// 获取物流细节
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="notices"></param>
        /// <returns></returns>
        public static Dictionary <string, T> GetLogisticsDetail <T>(Context ctx, List <DeliveryNotice> notices)
        {
            string messages             = "";
            Dictionary <string, T> dict = new Dictionary <string, T>();

            // Set this to true to process a COD shipment and print a COD return Label

            if (notices != null && notices.Count > 0)
            {
                foreach (var notice in notices)
                {
                    ProcessShipmentRequest request = CreateShipmentRequest(notice);

                    LogXML("DeliveryNoitceNo:" + notice.FBillNo + " Request ", request, typeof(ProcessShipmentRequest));

                    ShipService service = new ShipService();
                    if (usePropertyFile())
                    {
                        service.Url = getProperty("endpoint");
                    }
                    //
                    try
                    {
                        // Call the ship web service passing in a ProcessShipmentRequest and returning a ProcessShipmentReply
                        ProcessShipmentReply reply = service.processShipment(request);

                        LogXML("DeliveryNoitceNo:" + notice.FBillNo + " Reply ", reply, typeof(ProcessShipmentReply));
                        messages += GetNotifications(reply);

                        if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
                        {
                            notice.TraceEntry = GetShipmentReply(reply);
                            //LogXML(reply, typeof(ProcessShipmentReply));
                        }
                        RecordNotifications(ctx, reply);
                    }
                    catch (SoapException ex)
                    {
                        SynchroDataHelper.WriteSynchroLog(ctx, SynchroDataType.DeliveryNoticeBill, ex.Message + System.Environment.NewLine + ex.StackTrace);
                    }
                    catch (Exception ex)
                    {
                        SynchroDataHelper.WriteSynchroLog(ctx, SynchroDataType.DeliveryNoticeBill, ex.Message + System.Environment.NewLine + ex.StackTrace);
                    }
                }
            }

            HttpResponseResult result = new HttpResponseResult();

            result.Message = messages;

            dict.Add("result", (T)(Object)result);
            dict.Add("notices", (T)(Object)notices);

            return(dict);
        }
Beispiel #6
0
 private static void RecordNotifications(Context ctx, ProcessShipmentReply reply)
 {
     if (reply != null)
     {
         SynchroDataHelper.WriteSynchroLog(ctx, SynchroDataType.DeliveryNoticeBill, GetNotifications(reply));
     }
     else
     {
         SynchroDataHelper.WriteSynchroLog(ctx, SynchroDataType.DeliveryNoticeBill, "Fedex无响应");
     }
 }
Beispiel #7
0
        /// <summary>
        /// 获取装运响应
        /// </summary>
        /// <param name="isCodShipment"></param>
        /// <param name="reply"></param>
        /// <returns></returns>
        private static List <DeliveryNoticeTraceEntry> GetShipmentReply(ProcessShipmentReply reply)
        {
            List <DeliveryNoticeTraceEntry> traces = null;

            // Details for each package
            foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
            {
                traces = GetTrackingDetails(packageDetail.TrackingIds);
            }
            return(GetPackageRouteDetails(reply.CompletedShipmentDetail.OperationalDetail, traces));
        }
Beispiel #8
0
 private static void ShowNotifications(ProcessShipmentReply reply)
 {
     Console.WriteLine("Notifications");
     for (int i = 0; i < reply.Notifications.Length; i++)
     {
         Notification notification = reply.Notifications[i];
         Console.WriteLine("Notification no. {0}", i);
         Console.WriteLine(" Severity: {0}", notification.Severity);
         Console.WriteLine(" Code: {0}", notification.Code);
         Console.WriteLine(" Message: {0}", notification.Message);
         Console.WriteLine(" Source: {0}", notification.Source);
     }
 }
Beispiel #9
0
        private ShipReply SetShipmentReply(ProcessShipmentReply reply)
        {
            ShipReply result = new ShipReply();

            //Details for each package
            foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
            {
                if (null != packageDetail.Label.Parts[0].Image)
                {
                    result.TrackNumber = packageDetail.TrackingIds[0].TrackingNumber;
                    result.TrackFormId = packageDetail.TrackingIds[0].FormId;
                    result.LabelImage  = packageDetail.Label.Parts[0].Image;
                }
            }
            return(result);
        }
Beispiel #10
0
 private static void ShowShipmentReply(bool isCodShipment, ProcessShipmentReply reply)
 {
     Console.WriteLine("Shipment Reply details:");
     Console.WriteLine("Package details\n");
     // Details for each package
     foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
     {
         ShowTrackingDetails(packageDetail.TrackingIds);
         if (packageDetail.PackageRating != null && packageDetail.PackageRating.PackageRateDetails != null)
         {
             ShowPackageRateDetails(packageDetail.PackageRating.PackageRateDetails);
         }
         else
         {
             Console.WriteLine("No Rating information returned.\n");
         }
         ShowBarcodeDetails(packageDetail.OperationalDetail.Barcodes);
         ShowShipmentLabels(isCodShipment, reply.CompletedShipmentDetail, packageDetail);
     }
     ShowPackageRouteDetails(reply.CompletedShipmentDetail.OperationalDetail);
 }
Beispiel #11
0
 private static void ShowShipmentReply(bool isCodShipment, ProcessShipmentReply reply, string lablePath)
 {
     Console.WriteLine("Shipment Reply details:");
     Console.WriteLine("Package details\n");
     // Details for each package
     foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
     {
         ShowTrackingDetails(packageDetail.TrackingIds);
         if (null != packageDetail.PackageRating && null != packageDetail.PackageRating.PackageRateDetails)
         {
             ShowPackageRateDetails(packageDetail.PackageRating.PackageRateDetails);
         }
         else
         {
             Console.WriteLine("Rate information not returned");
         }
         ShowBarcodeDetails(packageDetail.OperationalDetail.Barcodes);
         ShowShipmentLabels(isCodShipment, reply.CompletedShipmentDetail, packageDetail, lablePath);
     }
     ShowPackageRouteDetails(reply.CompletedShipmentDetail.OperationalDetail);
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            // Set this to true to process a COD shipment and print a COD return Label
            bool isCodShipment             = true;
            ProcessShipmentRequest request = CreateShipmentRequest(isCodShipment);

            LogXML(request, typeof(ProcessShipmentRequest));
            //
            ShipService service = new ShipService();

            //if (usePropertyFile())
            //         {
            //             service.Url = getProperty("endpoint");
            //         }

            //
            try
            {
                // Call the ship web service passing in a ProcessShipmentRequest and returning a ProcessShipmentReply
                ProcessShipmentReply reply = service.processShipment(request);
                //
                if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
                {
                    ShowShipmentReply(isCodShipment, reply);
                    //LogXML(reply, typeof(ProcessShipmentReply));
                }
                ShowNotifications(reply);
            }
            catch (SoapException e)
            {
                Console.WriteLine(e.Detail.InnerText);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("Press any key to quit !");
            Console.ReadKey();
        }
Beispiel #13
0
        //private static NameValueCollection ShowNotifications(ProcessShipmentReply reply, out string resultCode, out string resultMessage)
        private static NameValueCollection ShowNotifications(ProcessShipmentReply reply, out string resultMessage)
        {
            NameValueCollection nvNotification = new NameValueCollection();

            //resultCode = string.Empty;
            resultMessage = string.Empty;

            try
            {
                if (reply.Notifications[0] != null)
                {
                    Notification notification = reply.Notifications[0];

                    nvNotification.Add("Code", Basic.IsNull(notification.Code, ""));
                    nvNotification.Add("Message", Basic.IsNull(notification.Message, ""));
                    nvNotification.Add("Severity", Basic.IsNull(notification.Severity, "")); //ERROR,FAILURE,NOTE,SUCCESS,WARNING
                    nvNotification.Add("Source", Basic.IsNull(notification.Source, ""));

                    /*
                     * resultCode = notification.Code;
                     * resultMessage = notification.Message;
                     * string NoticeSeverity = notification.Severity.ToString();
                     * string NoticeSource = notification.Source;
                     */
                }
                else
                {
                    resultMessage = "reply.Notifications[0] is null.";
                }
            }
            catch (Exception ex)
            {
                resultMessage = "[Error ShowNotifications] " + ex.Message;
            }

            return(nvNotification);
        }
Beispiel #14
0
        private static string GetNotifications(ProcessShipmentReply reply)
        {
            string messages = "";

            if (reply != null)
            {
                if (reply.Notifications != null && reply.Notifications.Length > 0)
                {
                    for (int i = 0; i < reply.Notifications.Length; i++)
                    {
                        Notification notification = reply.Notifications[i];

                        string message = string.Format("Notification no. {0}", i) + System.Environment.NewLine
                                         + string.Format("Severity: {0}", notification.Severity) + System.Environment.NewLine
                                         + string.Format("Code: {0}", notification.Code) + System.Environment.NewLine
                                         + string.Format("Message: {0}", notification.Message) + System.Environment.NewLine
                                         + string.Format("Source: {0}", notification.Source);

                        messages += message;
                    }
                }
            }
            return(messages);
        }
        private void HandleSuccess(ProcessShipmentReply reply)
        {
            if (reply.CompletedShipmentDetail.CompletedPackageDetails == null)
            {
                Result = null;
            }
            foreach (CompletedPackageDetail pkg in reply.CompletedShipmentDetail.CompletedPackageDetails)
            {
                if (pkg.TrackingIds != null)
                {
                    foreach (var id in pkg.TrackingIds)
                    {
                        trackingNumber = id.TrackingNumber;
                        Result = id.TrackingNumber;
                        WriteLog(string.Format("Received tracking number: {0}", id.TrackingNumber), Color.Green);
                        var path = Path.Combine(Path.GetDirectoryName(Settings.LabelDirectory), "FedEx.csv");

                        List<string> rates = new List<string>();

                        var rating = reply.CompletedShipmentDetail.ShipmentRating;
                        if (rating != null && rating.ShipmentRateDetails != null)
                        {
                            foreach (var rate in rating.ShipmentRateDetails)
                            {
                                rates.Add(rate.TotalNetFedExCharge.Amount.ToString() + " " + rate.TotalNetFedExCharge.Currency.ToString());
                            }
                        }

                        string d1, d2, d3;
                        d1 = d2 = d3 = "";

                        if (reply.CompletedShipmentDetail != null && reply.CompletedShipmentDetail.OperationalDetail != null) {
                            if (reply.CompletedShipmentDetail.OperationalDetail.DeliveryDaySpecified)
                            {
                                d1 = reply.CompletedShipmentDetail.OperationalDetail.DeliveryDay.ToString();
                            }
                            if (reply.CompletedShipmentDetail.OperationalDetail.DeliveryDateSpecified)
                            {
                                d2 = reply.CompletedShipmentDetail.OperationalDetail.DeliveryDate.ToShortDateString();
                            }
                            if (reply.CompletedShipmentDetail.OperationalDetail.TransitTimeSpecified)
                            {
                                d3 = reply.CompletedShipmentDetail.OperationalDetail.TransitTime.ToString();
                            }
                        }

                        File.AppendAllText(path, string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\"\n",
                            DateTime.Now.ToLongTimeString(), currentDespatch.SalesOrderNumber, currentDespatch.DespatchNumber,
                            id.TrackingNumber, string.Join(", ", rates.ToArray()), d1, d2, d3

                        ));
                        return;
                    }
                }
            }
        }
Beispiel #16
0
        public OrderKitBO MakeShipment()
        {
            OrderKitBO obo = new OrderKitBO();
            // Set this to true to process a COD shipment and print a COD return Label
            bool isCodShipment             = false;
            ProcessShipmentRequest request = CreateShipmentRequest(isCodShipment);
            // LogXML(request, typeof(ProcessShipmentRequest));
            //
            ShipService service = new ShipService();

            if (usePropertyFile())
            {
                service.Url = getProperty("endpoint");
            }
            //
            try
            {
                // Call the ship web service passing in a ProcessShipmentRequest and returning a ProcessShipmentReply
                ProcessShipmentReply reply = service.processShipment(request);
                //
                if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
                {
                    // ShowShipmentReply(isCodShipment, reply);
                    //LogXML(reply, typeof(ProcessShipmentReply));
                    foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
                    {
                        if (packageDetail.TrackingIds != null)
                        {
                            for (int i = 0; i < packageDetail.TrackingIds.Length; i++)
                            {
                                obo.TrackNumber      = packageDetail.TrackingIds[i].TrackingNumber;
                                obo.LabelGeneratedOn = DateTime.Now.ToShortDateString();
                            }
                        }
                        ShowShipmentLabels(isCodShipment, reply.CompletedShipmentDetail, packageDetail);
                    }
                    if (reply.CompletedShipmentDetail.OperationalDetail.DeliveryDateSpecified)
                    {
                        obo.DeleveryOn = reply.CompletedShipmentDetail.OperationalDetail.DeliveryDate.ToShortDateString();
                    }
                }
                List <CourierNotificationBO> notifi = new List <CourierNotificationBO>();
                for (int i = 0; i < reply.Notifications.Length; i++)
                {
                    Notification notification = reply.Notifications[i];
                    notifi.Add(new CourierNotificationBO()
                    {
                        cNotification = notification.Message,
                    });
                    //obo.oNotifications.Add(new CourierNotificationBO()
                    //{
                    //    cNotification = notification.Message,
                    //    //cNotification = "Notification no. " + i + " Severity: " + notification.Severity + " Code: " + notification.Code + " Message: " + notification.Message,
                    //});

                    /* Console.WriteLine("Notification no. {0}", i);
                     * Console.WriteLine(" Severity: {0}", notification.Severity);
                     * Console.WriteLine(" Code: {0}", notification.Code);
                     * Console.WriteLine(" Message: {0}", notification.Message);
                     * Console.WriteLine(" Source: {0}", notification.Source);*/
                }
                obo.oNotifications = notifi;
                //ShowNotifications(reply);
            }
            catch (SoapException e)
            {
                obo.Exception = e.Detail.InnerText;
                //Console.WriteLine(e.Detail.InnerText);
            }
            catch (Exception e)
            {
                //obo.Exception = e.Message;
                obo.Exception = "Exception: " + "Target Site: " + e.TargetSite + "message : " + e.Message;

                //Console.WriteLine(e.Message);
            }
            //  Console.WriteLine("Press any key to quit !");
            //  Console.ReadKey();
            return(obo);
        }
        private void ShowShipmentReply(ProcessShipmentReply reply)
        {
            if (reply.CompletedShipmentDetail == null)
                return;

            WriteToBuffer(string.Format("Shipment Reply details:"));
            // Details for each package
            if (reply.CompletedShipmentDetail.CompletedPackageDetails != null)
            {
                List<ShippingDocument> docs = new List<ShippingDocument>();

                foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
                {
                    ShowTrackingDetails(packageDetail.TrackingIds);
                    ShowPackageRateDetails(reply.CompletedShipmentDetail.ShipmentRating);

                    if (packageDetail.Label != null) {
                        docs.Add(packageDetail.Label);
                    }
                    if (packageDetail.PackageDocuments != null)
                    {
                        docs.AddRange(packageDetail.PackageDocuments);
                    }

                    ShowBarcodeDetails(packageDetail.OperationalDetail.Barcodes);
                }

                if (reply.CompletedShipmentDetail.ShipmentDocuments != null) {
                    docs.AddRange(reply.CompletedShipmentDetail.ShipmentDocuments);
                }

                int n = 1;
                foreach (ShippingDocument doc in docs)
                {
                    if (doc.TypeSpecified && doc.Type == ReturnedShippingDocumentType.TERMS_AND_CONDITIONS)
                    {
                        continue;
                    }
                    short copies = short.Parse(doc.CopiesToPrint);
                    int k = 1;
                    foreach (ShippingDocumentPart part in doc.Parts)
                    {
                        SaveLabel(Path.Combine(Settings.LabelDirectory, currentDespatch.SalesOrderNumber + "-" + n.ToString() + "-" + k.ToString() + "-" + doc.CopiesToPrint + ".png"), part.Image, copies);
                        k++;
                    }
                    n++;
                }
            }

            ShowPackageRouteDetails(reply.CompletedShipmentDetail.OperationalDetail);
        }
Beispiel #18
0
        public ProcessShipmentReply CreateBox(List <Box> boxList, ShippingMethod method, DirectLine directLine)
        {
            ProcessShipmentRequest request = _shipmentInit();

            request.TransactionDetail = new QDLogistics.FedExShipService.TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "*** Process Shipment Request ***";

            request.RequestedShipment = new RequestedShipment()
            {
                ShipTimestamp          = DateTime.Today,
                DropoffType            = DropoffType.REGULAR_PICKUP,
                ServiceType            = (QDLogistics.FedExShipService.ServiceType)method.MethodType,
                PackagingType          = (QDLogistics.FedExShipService.PackagingType)method.BoxType,
                Shipper                = _shipperInit(),
                ShippingChargesPayment = new Payment()
                {
                    PaymentType = PaymentType.SENDER, Payor = new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    }
                },
                PackageCount = boxList.Count().ToString()
            };

            request.RequestedShipment.Recipient = new Party()
            {
                Contact = new QDLogistics.FedExShipService.Contact()
                {
                    PersonName  = directLine.ContactName,
                    CompanyName = directLine.CompanyName,
                    PhoneNumber = directLine.PhoneNumber
                },
                Address = new QDLogistics.FedExShipService.Address()
                {
                    StreetLines         = new string[] { directLine.StreetLine1, directLine.StreetLine2 },
                    City                = directLine.City,
                    StateOrProvinceCode = directLine.StateName,
                    PostalCode          = directLine.PostalCode,
                    CountryName         = directLine.CountryName,
                    CountryCode         = directLine.CountryCode
                }
            };

            int NumberOfPieces = 1;

            string[] IDS      = new string[] { "IDS", "IDS (US)" };
            string   currency = IDS.Contains(directLine.Abbreviation) ? "USD" : Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), boxList[0].Packages.First(p => p.IsEnable.Value).Orders.OrderCurrencyCode.Value);
            //string currency = Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), box.Packages.First(p => p.IsEnable.Value).Orders.OrderCurrencyCode.Value);
            var commodityList = new List <QDLogistics.FedExShipService.Commodity>();
            var itemLineList  = new List <RequestedPackageLineItem>();

            QDLogistics.FedExShipService.Money customsValue;

            Dictionary <string, StockKeepingUnit.SkuData> SkuData;

            using (StockKeepingUnit stock = new StockKeepingUnit())
            {
                var allPackages = boxList.SelectMany(b => b.Packages.Where(p => p.IsEnable.Value)).ToList();
                customsValue = new QDLogistics.FedExShipService.Money()
                {
                    Currency = currency, Amount = allPackages.Sum(p => p.DeclaredTotal)
                };
                var IDs = allPackages.SelectMany(p => p.Items.Where(i => i.IsEnable.Value)).Select(i => i.ProductID).Distinct().ToArray();
                SkuData = stock.GetSkuData(IDs);
            }

            foreach (Box box in boxList)
            {
                List <Items> itemList = box.Packages.Where(p => p.IsEnable.Value).SelectMany(p => p.Items.Where(i => i.IsEnable.Value)).ToList();

                QDLogistics.FedExShipService.Commodity commodity = new QDLogistics.FedExShipService.Commodity
                {
                    NumberOfPieces       = boxList.Count().ToString(),
                    Description          = string.Join(", ", itemList.Select(i => i.Skus.ProductType.ProductTypeName).Distinct().ToArray()),
                    CountryOfManufacture = "CN",
                    Weight = new QDLogistics.FedExShipService.Weight()
                    {
                        Units = request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? QDLogistics.FedExShipService.WeightUnits.LB : QDLogistics.FedExShipService.WeightUnits.KG,
                        Value = itemList.Sum(i => i.Qty.Value * ((decimal)(SkuData[i.ProductID]?.Weight ?? i.Skus.ShippingWeight) / (request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? 453 : 1000)))
                    },
                    Quantity      = 1,
                    QuantityUnits = "EA",
                    UnitPrice     = new QDLogistics.FedExShipService.Money()
                    {
                        Currency = currency, Amount = box.Packages.Where(p => p.IsEnable.Value).Sum(p => p.DeclaredTotal)
                    },
                    CustomsValue      = customsValue,
                    QuantitySpecified = true
                };

                commodityList.Add(commodity);
                itemLineList.Add(new RequestedPackageLineItem()
                {
                    SequenceNumber = NumberOfPieces++.ToString(),
                    InsuredValue   = new QDLogistics.FedExShipService.Money()
                    {
                        Amount = 0, Currency = currency
                    },
                    Weight             = commodity.Weight,
                    CustomerReferences = new CustomerReference[]
                    {
                        new CustomerReference()
                        {
                            CustomerReferenceType = CustomerReferenceType.CUSTOMER_REFERENCE,
                            Value = box.BoxID
                        }
                    }
                });
            }

            request.RequestedShipment.TotalWeight = new QDLogistics.FedExShipService.Weight()
            {
                Units = request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? QDLogistics.FedExShipService.WeightUnits.LB : QDLogistics.FedExShipService.WeightUnits.KG,
                Value = commodityList.Select(c => c.Weight).Sum(w => w.Value)
            };

            request.RequestedShipment.CustomsClearanceDetail = new CustomsClearanceDetail()
            {
                DutiesPayment = new Payment()
                {
                    PaymentType = PaymentType.SENDER, Payor = new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    }
                },
                DocumentContent          = InternationalDocumentContentType.DOCUMENTS_ONLY,
                Commodities              = new QDLogistics.FedExShipService.Commodity[1],
                DocumentContentSpecified = true
            };

            request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[1];

            request.RequestedShipment.LabelSpecification = new LabelSpecification()
            {
                LabelOrder                        = LabelOrderType.SHIPPING_LABEL_FIRST,
                LabelFormatType                   = LabelFormatType.COMMON2D,
                ImageType                         = ShippingDocumentImageType.ZPLII,
                LabelStockType                    = LabelStockType.STOCK_4X6,
                LabelPrintingOrientation          = LabelPrintingOrientationType.BOTTOM_EDGE_OF_TEXT_FIRST,
                LabelOrderSpecified               = true,
                ImageTypeSpecified                = true,
                LabelStockTypeSpecified           = true,
                LabelPrintingOrientationSpecified = true
            };

            ProcessShipmentReply reply = new ProcessShipmentReply();

            using (ShipPortTypeClient client = new ShipPortTypeClient())
            {
                var endpoint = client.Endpoint;
                ConsoleOutputBehavior consoleOutputBehavior = new ConsoleOutputBehavior();
                client.Endpoint.Behaviors.Add(consoleOutputBehavior);

                try
                {
                    var basePath = HostingEnvironment.MapPath("~/FileUploads");
                    var filePath = Path.Combine(basePath, "export", "box", boxList[0].Create_at.ToString("yyyy/MM/dd"), boxList[0].MainBox);
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    for (int i = 0; i < itemLineList.Count(); i++)
                    {
                        if (!i.Equals(0))
                        {
                            request.RequestedShipment.TotalWeight      = null;
                            request.RequestedShipment.MasterTrackingId = reply.CompletedShipmentDetail.MasterTrackingId;
                        }
                        request.RequestedShipment.CustomsClearanceDetail.CustomsValue   = commodityList[i].CustomsValue;
                        request.RequestedShipment.CustomsClearanceDetail.Commodities[0] = commodityList[i];
                        request.RequestedShipment.RequestedPackageLineItems[0]          = itemLineList[i];

                        reply = client.processShipment(request);
                        if (reply.HighestSeverity.Equals(QDLogistics.FedExShipService.NotificationSeverityType.ERROR) || reply.HighestSeverity.Equals(QDLogistics.FedExShipService.NotificationSeverityType.FAILURE))
                        {
                            throw new Exception(string.Join("\n", reply.Notifications.Select(n => n.Message).ToArray()));
                        }

                        boxList[i].TrackingNumber = reply.CompletedShipmentDetail.CompletedPackageDetails.First().TrackingIds.Select(t => t.TrackingNumber).First();

                        var content = reply.CompletedShipmentDetail.CompletedPackageDetails.First().Label.Parts.First().Image;
                        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://api.labelary.com/v1/printers/8dpmm/labels/4x6/");
                        webRequest.Method        = "POST";
                        webRequest.Accept        = "application/pdf";
                        webRequest.ContentType   = "application/x-www-form-urlencoded";
                        webRequest.ContentLength = content.Length;

                        using (Stream requestStream = webRequest.GetRequestStream())
                        {
                            requestStream.Write(content, 0, content.Length);

                            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse();
                            using (Stream responseStream = response.GetResponseStream())
                            {
                                using (FileStream fileStream = File.Create(Path.Combine(filePath, boxList[i].BoxID + ".pdf")))
                                {
                                    responseStream.CopyTo(fileStream);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    QDLogistics.FedExShipService.Notification notification = new QDLogistics.FedExShipService.Notification();

                    if (!string.IsNullOrEmpty(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML))
                    {
                        XElement element = XElement.Parse(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML);
                        notification.Message = element.Attributes("Message").Any() ? element.Attributes("Message").First().Value : element.Attributes("Desc").First().Value;
                    }
                    else
                    {
                        notification.Message = e.Message;
                    }

                    reply = new ProcessShipmentReply()
                    {
                        Notifications = new QDLogistics.FedExShipService.Notification[] { notification }
                    };
                }
            }

            return(reply);
        }
Beispiel #19
0
        public ProcessShipmentReply Create(Packages package)
        {
            ProcessShipmentRequest request = _shipmentInit();

            request.TransactionDetail = new QDLogistics.FedExShipService.TransactionDetail();
            request.TransactionDetail.CustomerTransactionId = "*** Process Shipment Request ***";

            request.RequestedShipment = new RequestedShipment()
            {
                ShipTimestamp          = DateTime.Today,
                DropoffType            = DropoffType.REGULAR_PICKUP,
                ServiceType            = (QDLogistics.FedExShipService.ServiceType)package.Method.MethodType,
                PackagingType          = (QDLogistics.FedExShipService.PackagingType)package.Method.BoxType,
                Shipper                = _shipperInit(),
                ShippingChargesPayment = new Payment()
                {
                    PaymentType = PaymentType.SENDER, Payor = new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    }
                },
                PackageCount = "1"
            };

            Addresses address = package.Orders.Addresses;

            request.RequestedShipment.Recipient = new Party()
            {
                Contact = new QDLogistics.FedExShipService.Contact()
                {
                    PersonName  = string.Join(" ", new string[] { address.FirstName, address.MiddleInitial, address.LastName }),
                    CompanyName = address.CompanyName,
                    PhoneNumber = address.PhoneNumber
                },
                Address = new QDLogistics.FedExShipService.Address()
                {
                    StreetLines         = new string[] { address.StreetLine1, address.StreetLine2 },
                    City                = address.City,
                    StateOrProvinceCode = address.StateName,
                    PostalCode          = address.PostalCode,
                    CountryName         = address.CountryName,
                    CountryCode         = address.CountryCode
                }
            };

            Dictionary <string, StockKeepingUnit.SkuData> SkuData;

            using (StockKeepingUnit stock = new StockKeepingUnit())
            {
                var IDs = package.Items.Where(i => i.IsEnable.Value).Select(i => i.ProductID).Distinct().ToArray();
                SkuData = stock.GetSkuData(IDs);
            }

            string currency = Enum.GetName(typeof(QDLogistics.OrderService.CurrencyCodeType2), package.Orders.OrderCurrencyCode.Value);

            QDLogistics.FedExShipService.Money customsValue = new QDLogistics.FedExShipService.Money()
            {
                Currency = currency, Amount = package.DeclaredTotal
            };
            QDLogistics.FedExShipService.Commodity commodity = new QDLogistics.FedExShipService.Commodity
            {
                NumberOfPieces       = "1",
                Description          = string.Join(", ", package.Items.Select(i => i.Skus.ProductType.ProductTypeName).Distinct().ToArray()),
                CountryOfManufacture = "CN",
                Weight = new QDLogistics.FedExShipService.Weight()
                {
                    Units = address.CountryCode.Equals("US") ? QDLogistics.FedExShipService.WeightUnits.LB : QDLogistics.FedExShipService.WeightUnits.KG,
                    Value = package.Items.Where(i => i.IsEnable.Equals(true)).Sum(i => i.Qty.Value * ((decimal)(SkuData[i.ProductID]?.Weight ?? i.Skus.ShippingWeight) / (request.RequestedShipment.Shipper.Address.CountryCode.Equals("US") ? 453 : 1000)))
                },
                Quantity          = 1,
                QuantityUnits     = "EA",
                UnitPrice         = customsValue,
                CustomsValue      = customsValue,
                QuantitySpecified = true
            };

            request.RequestedShipment.CustomsClearanceDetail = new CustomsClearanceDetail()
            {
                DutiesPayment = new Payment()
                {
                    PaymentType = address.CountryCode.Equals("US") && package.ShippingMethod.Equals(35) ? PaymentType.SENDER : PaymentType.RECIPIENT,
                    Payor       = address.CountryCode.Equals("US") && package.ShippingMethod.Equals(35) ? new Payor()
                    {
                        ResponsibleParty = _shipperInit()
                    } : null
                },
                DocumentContent          = InternationalDocumentContentType.DOCUMENTS_ONLY,
                CustomsValue             = customsValue,
                Commodities              = new QDLogistics.FedExShipService.Commodity[] { commodity },
                DocumentContentSpecified = true
            };

            request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[] {
                new RequestedPackageLineItem()
                {
                    SequenceNumber = "1",
                    InsuredValue   = new QDLogistics.FedExShipService.Money()
                    {
                        Amount = package.NeedInsurance ? package.DeclaredTotal : 0, Currency = currency
                    },
                    Weight             = commodity.Weight,
                    CustomerReferences = new CustomerReference[]
                    {
                        new CustomerReference()
                        {
                            CustomerReferenceType = CustomerReferenceType.CUSTOMER_REFERENCE,
                            Value = package.OrderID.ToString()
                        }
                    }
                }
            };

            request.RequestedShipment.LabelSpecification = new LabelSpecification()
            {
                LabelFormatType                   = LabelFormatType.COMMON2D,
                ImageType                         = ShippingDocumentImageType.ZPLII,
                LabelStockType                    = LabelStockType.STOCK_4X6,
                LabelPrintingOrientation          = LabelPrintingOrientationType.BOTTOM_EDGE_OF_TEXT_FIRST,
                ImageTypeSpecified                = true,
                LabelStockTypeSpecified           = true,
                LabelPrintingOrientationSpecified = true
            };

            ProcessShipmentReply reply;

            using (ShipPortTypeClient client = new ShipPortTypeClient())
            {
                var endpoint = client.Endpoint;
                ConsoleOutputBehavior consoleOutputBehavior = new ConsoleOutputBehavior();
                client.Endpoint.Behaviors.Add(consoleOutputBehavior);

                try
                {
                    reply = client.processShipment(request);
                }
                catch (Exception e)
                {
                    QDLogistics.FedExShipService.Notification notification = new QDLogistics.FedExShipService.Notification();

                    if (!string.IsNullOrEmpty(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML))
                    {
                        XElement element = XElement.Parse(consoleOutputBehavior.ConsoleOutputInspector.ResponseXML);
                        notification.Message = element.Attributes("Message").Any() ? element.Attributes("Message").First().Value : element.Attributes("Desc").First().Value;
                    }
                    else
                    {
                        notification.Message = e.Message;
                    }

                    reply = new ProcessShipmentReply()
                    {
                        Notifications = new QDLogistics.FedExShipService.Notification[] { notification }
                    };
                }
            }

            return(reply);
        }
Beispiel #20
0
        public ShipServiceResponse ShipClientService(ShipServiceInfo clsService, AddressInfo clsAddress)
        {
            FedExWebServiceClient.ShipServiceWebReference.ShipService service = new FedExWebServiceClient.ShipServiceWebReference.ShipService();
            ShipServiceResponse shipResponse = new ShipServiceResponse();

            string iResultCode    = string.Empty;
            string iResultMessage = string.Empty;
            string iErrorMessage  = string.Empty;
            string retValue       = string.Empty;
            string strApiUrl      = string.Empty;

            string noticeCode     = string.Empty;
            string noticeMessage  = string.Empty;
            string noticeSeverity = string.Empty;
            string noticeSource   = string.Empty;


            // WebService Url Setting
            retValue = GetWebserviceUrl(out strApiUrl);
            if (!string.IsNullOrEmpty(retValue))
            {
                shipResponse.isSuccess    = false;
                shipResponse.ErrorMessage = "[ERROR] Ship Webservice url is empty.\r\n  Error Message : " + retValue;

                return(shipResponse);
            }

            try
            {
                bool isCodShipment = clsService.IsCOD; // Don't use cash on delivery in US.

                // Create Shipment Request
                ProcessShipmentRequest request = CreateShipmentRequest(clsService, clsAddress, isCodShipment);

                // Webservice URL
                service.Url = strApiUrl;

                // Call the ship web service passing in a ProcessShipmentRequest and returning a ProcessShipmentReply

                System.Diagnostics.Debug.WriteLine(Encoding.Default.GetString(serializeToSoap(request)));

                ProcessShipmentReply reply = service.processShipment(request);

                // Call ShowNotifications(reply)
                NameValueCollection nvcNotification = ShowNotifications(reply, out iResultMessage);
                foreach (string nvKey in nvcNotification.AllKeys)
                {
                    switch (nvKey)
                    {
                    case "Code":
                        shipResponse.NoticeCode = nvcNotification[nvKey].ToString();
                        break;

                    case "Message":
                        shipResponse.NoticeMessage = nvcNotification[nvKey].ToString();
                        break;

                    case "Severity":
                        shipResponse.NoticeSeverity = nvcNotification[nvKey].ToString();
                        break;

                    case "Source":
                        shipResponse.NoticeSource = nvcNotification[nvKey].ToString();
                        break;

                    default:
                        break;
                    }
                }

                // SUCCESS, NOTE, WARNING
                if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING)
                {
                    shipResponse.HighestSeverity = reply.HighestSeverity.ToString();

                    //retVal = ShowNotifications(reply, out iResultCode, out iResultMessage);
                    // Call ShowNotifications(reply)

                    shipResponse = ShowShipmentReply(isCodShipment, reply, clsService, shipResponse, out retValue);

                    //shipResponse.ResultCode = iResultCode;
                    //shipResponse.ResultMessage = iResultMessage;

                    if (retValue.Equals(string.Empty))
                    {
                        shipResponse.isSuccess = true;
                    }
                    else
                    {
                        // Check FedexTrackingNumber (If Smart_Post service type)
                        if (!string.IsNullOrEmpty(shipResponse.FedexTrackingNumber) && !string.IsNullOrEmpty(shipResponse.FedexLabelString))
                        {
                            shipResponse.isSuccess = true;  // if exists Tracking number and Label string.
                        }
                        else
                        {
                            shipResponse.isSuccess = false;
                        }

                        shipResponse.ErrorMessage = "[ShowShipmentReply Error] " + retValue;
                    }
                }
                else // ERROR, FAILURE
                {
                    shipResponse.HighestSeverity = Basic.IsNull(reply.HighestSeverity.ToString(), "Empty");

                    shipResponse.isSuccess    = false;
                    shipResponse.ErrorMessage = "[" + shipResponse.HighestSeverity + "] Notification Code: " + shipResponse.NoticeCode + ",\r\nNotification Message: " + shipResponse.NoticeMessage;

                    //retVal = ShowNotifications(reply, out iResultMessage);

                    //if (retVal == "")
                    //{
                    //    shipResponse.ResultCode = iResultCode;
                    //    shipResponse.ResultMessage = iResultMessage;

                    //    shipResponse.isSuccess = false;
                    //    shipResponse.ErrorMessage = "[" + shipResponse.HighestSeverity + "] ResultCode: " + shipResponse.NoticeCode + ", ResultMsg: " + shipResponse.NoticeMessage;
                    //}
                    //else
                    //{
                    //    shipResponse.isSuccess = false;
                    //    shipResponse.ErrorMessage = retVal;
                    //}
                }

                //shipResponse.NoticeCode = noticeCode;
                //shipResponse.NoticeMessage = noticeMessage;
                //shipResponse.NoticeSeverity = noticeSeverity;
                //shipResponse.NoticeSource = noticeSource;
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                throw ex;
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }
            }

            return(shipResponse);
        }
        private void ShowNotifications(ProcessShipmentReply reply)
        {
            if (reply.Notifications.Length == 0)
                return;

            WriteLog("Notifications", Color.Red);
            for (int i = 0; i < reply.Notifications.Length; i++)
            {
                Notification notification = reply.Notifications[i];
                WriteLog(string.Format(@"Notification no. {0}
             Severity: {1}
             Code: {2}
             Message: {3}
             Source: {4}", i, notification.Severity, notification.Code, notification.Message, notification.Source), Color.Red);
            }
        }
Beispiel #22
0
        private static ShipServiceResponse ShowShipmentReply(bool isCodShipment, ProcessShipmentReply reply, ShipServiceInfo clsService, ShipServiceResponse objResponse, out string retVal)
        {
            //F21.Service.ShipServiceResponse objResponse = new F21.Service.ShipServiceResponse();
            retVal = string.Empty;

            try
            {
                // Carrier code types : FDXC(Cargo), FDXE(Express), FDXG(Ground), FXCC(Custom Critical), FXFX(Freight), FXSP - ? (Reference FedEx Document)
                // SmartPost Reply details
                if (clsService.ServiceType == ServiceType.SMART_POST)
                {
                    if (reply.CompletedShipmentDetail.SmartPostDetail.PickUpCarrierSpecified)
                    {
                        objResponse.SmartPickupCode = reply.CompletedShipmentDetail.SmartPostDetail.PickUpCarrier.ToString();
                    }

                    if (reply.CompletedShipmentDetail.SmartPostDetail.MachinableSpecified)
                    {
                        objResponse.SmartMachinable = reply.CompletedShipmentDetail.SmartPostDetail.Machinable;
                    }
                }

                // Details for each package
                if (reply.CompletedShipmentDetail.CompletedPackageDetails != null)
                {
                    System.Diagnostics.Debug.WriteLine("CompletedPackageDetails Array Length : " + reply.CompletedShipmentDetail.CompletedPackageDetails.Length);
                    foreach (CompletedPackageDetail packageDetail in reply.CompletedShipmentDetail.CompletedPackageDetails)
                    {
                        //Get Fedex TrackingNumber  (ShowTrackingDetails)
                        if (packageDetail.TrackingIds != null)
                        {
                            System.Diagnostics.Debug.WriteLine("TrackingIds Array Length : " + packageDetail.TrackingIds.Length);
                            for (int i = 0; i < packageDetail.TrackingIds.Length; i++)
                            {
                                // TrackingIdType (EXPRESS,FEDEX,FREIGHT,GROUND,USPS)
                                // Update ShipService version from v15 to v17
                                objResponse.TrackingIdType      = packageDetail.TrackingIds[i].TrackingIdType.ToString();
                                objResponse.FedexTrackingNumber = packageDetail.TrackingIds[i].TrackingNumber;
                                objResponse.FormId            = packageDetail.TrackingIds[i].FormId;
                                objResponse.UspsApplicationId = Basic.IsNull(packageDetail.TrackingIds[i].UspsApplicationId, "");

                                /*  (Comment out the below sourcecode)
                                 * if (packageDetail.TrackingIds[i].TrackingIdType == TrackingIdType.USPS)
                                 * {
                                 *  objResponse.USPSTrackingIdType = packageDetail.TrackingIds[i].TrackingIdType.ToString();
                                 *  objResponse.USPSTrackingNumber = packageDetail.TrackingIds[i].TrackingNumber;
                                 *  objResponse.USPSFormId = packageDetail.TrackingIds[i].FormId;
                                 * }
                                 * else
                                 * {
                                 *  objResponse.TrackingIdType = packageDetail.TrackingIds[i].TrackingIdType.ToString();
                                 *  objResponse.FedexTrackingNumber = packageDetail.TrackingIds[i].TrackingNumber;
                                 *  objResponse.FormId = packageDetail.TrackingIds[i].FormId;
                                 * }
                                 */
                            }
                        }
                        else
                        {
                            // Tracking Number Issue
                            retVal = "[ERROR] packageDetail.TrackingIds is null.";
                        }

                        //Get LabelString (ShowShipmentLabels)
                        if (packageDetail.Label.Parts != null)
                        {
                            if (clsService.LabelImageType == ShippingDocumentImageType.ZPLII)
                            {
                                // Get ZPL Label Strig
                                objResponse.FedexLabelString = ShowShipmentLabels(packageDetail);
                            }
                            else if (clsService.LabelImageType == ShippingDocumentImageType.PDF)
                            {
                                objResponse.FedexLabelString = ShowShipmentLabels3(isCodShipment, reply.CompletedShipmentDetail, packageDetail);
                            }
                            else
                            {
                                objResponse.FedexLabelString = ShowShipmentLabels(packageDetail);
                            }
                        }
                        else
                        {
                            retVal = retVal + " [ERROR] packageDetail.Label.Parts is null.";
                        }

                        // *** Check functon (ShowPackageRateDetails) Don't use package rate detalis information
                        // PackageRateDetails 에러가 종종 발생하기 때문에 주석 처리, TrackingNumber, ZplString Value 가 존재하면 정상 처리함.

                        /* (Comment out the below sourcecode)
                         * if (packageDetail.PackageRating.PackageRateDetails != null)
                         * {
                         *  System.Diagnostics.Debug.WriteLine("PackageRateDetails Array Length :" + packageDetail.PackageRating.PackageRateDetails.Length);
                         *  foreach (PackageRateDetail ratedPackage in packageDetail.PackageRating.PackageRateDetails)
                         *  {
                         *      System.Diagnostics.Debug.WriteLine("Billing weight :" + ratedPackage.BillingWeight.Value.ToString());
                         *      System.Diagnostics.Debug.WriteLine("Billing weight Units :" + ratedPackage.BillingWeight.Units.ToString());
                         *
                         *      objResponse.BillingWeight = ratedPackage.BillingWeight.Value;
                         *      objResponse.BillingWeightUnits = ratedPackage.BillingWeight.Units.ToString();
                         *
                         *      System.Diagnostics.Debug.WriteLine("Base charge : " + ratedPackage.BaseCharge.Amount + "-" + ratedPackage.BaseCharge.Currency);
                         *      System.Diagnostics.Debug.WriteLine("Total surcharge : " + ratedPackage.TotalSurcharges.Amount + "-" + ratedPackage.TotalSurcharges.Currency);
                         *
                         *      if (ratedPackage.Surcharges != null)
                         *      {
                         *          foreach (Surcharge surcharge in ratedPackage.Surcharges)
                         *          {
                         *              System.Diagnostics.Debug.WriteLine("Surcharge : " + surcharge.SurchargeType + " - " + surcharge.Amount.Amount + " - " + surcharge.Amount.Currency);
                         *          }
                         *      }
                         *
                         *      if (ratedPackage.NetCharge != null)
                         *      {
                         *          System.Diagnostics.Debug.WriteLine("Net charge : " + ratedPackage.NetCharge.Amount + "-" + ratedPackage.NetCharge.Currency);
                         *      }
                         *  }
                         * }
                         */
                        //---------------------------------------------------------------------------------------------------------------------------------------

                        // Get Barcode (ShowBarcodeDetails)
                        if (packageDetail.OperationalDetail.Barcodes != null)
                        {
                            if (packageDetail.OperationalDetail.Barcodes.StringBarcodes != null)
                            {
                                System.Diagnostics.Debug.WriteLine("StringBarcodes Array Length :" + packageDetail.OperationalDetail.Barcodes.StringBarcodes.Length);
                                for (int i = 0; i < packageDetail.OperationalDetail.Barcodes.StringBarcodes.Length; i++)
                                {
                                    //List<string> list = new List<string>();

                                    // String Barcode Types : ADDRESS, ASTRA, FEDEX_1D, GROUND, POSTAL,USPS
                                    // Update ShipService version from v15 to v17
                                    objResponse.Barcode     = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Value;
                                    objResponse.BarcodeType = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Type.ToString();

                                    /* (Comment out the below sourcecode)
                                     * if (packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Type == StringBarcodeType.USPS)
                                     * {
                                     *  objResponse.USPSBarcode = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Value;
                                     *  objResponse.USPSBarcodeType = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Type.ToString();
                                     * }
                                     * else
                                     * {
                                     *  objResponse.Barcode = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Value;
                                     *  objResponse.BarcodeType = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Type.ToString();
                                     * }
                                     */
                                    //Object reference not set to an instance of an object.
                                    //objResponse.ResponseStringBarcodes[i] = packageDetail.OperationalDetail.Barcodes.StringBarcodes[i].Value;
                                }
                            }

                            // Don't use BinaryBarcodes (Comment out the BinaryBarcodes sourcecode)

                            /*
                             * if (packageDetail.OperationalDetail.Barcodes.BinaryBarcodes != null)
                             * {
                             *  System.Diagnostics.Debug.WriteLine("BinaryBarcodes Array Length :" + packageDetail.OperationalDetail.Barcodes.BinaryBarcodes.Length);
                             *  for (int i = 0; i < packageDetail.OperationalDetail.Barcodes.BinaryBarcodes.Length; i++)
                             *  {
                             *      objResponse.BinaryBarcodeType = packageDetail.OperationalDetail.Barcodes.BinaryBarcodes[i].Type.ToString();
                             *  }
                             * }
                             */
                        }
                    }
                }

                // ShowPackageRouteDetails
                if (reply.CompletedShipmentDetail.OperationalDetail != null)
                {
                    ShipmentOperationalDetail routingDetail = reply.CompletedShipmentDetail.OperationalDetail;
                    objResponse.UrsaPrefixCode        = routingDetail.UrsaPrefixCode;
                    objResponse.UrsaSuffixCode        = routingDetail.UrsaSuffixCode;
                    objResponse.DestinationLocationId = routingDetail.DestinationLocationId;
                    objResponse.AirportId             = routingDetail.AirportId;


                    if (routingDetail.TransitTimeSpecified)
                    {
                        objResponse.TransitTime = routingDetail.TransitTime.ToString();
                    }

                    /*
                     * if (routingDetail.DeliveryDaySpecified)
                     * {
                     *  string DeliveryDay = routingDetail.DeliveryDay.ToString();
                     * }
                     *
                     * if (routingDetail.DeliveryDateSpecified)
                     * {
                     *  string DeliveryShortDate = routingDetail.DeliveryDate.ToShortDateString();
                     * }
                     */

                    //throw new Exception("Test Error");
                }
            }
            catch (Exception ex)
            {
                retVal = retVal + "[ShowShipmentReply Error] " + ex.Message;
            }

            return(objResponse);
        }
        public override ProcessShipmentResult ProcessShipment(Order order, ShippingLabelType shippingLabelType)
        {
            ErrorMessages.Clear();

            ProcessShipmentResult result = new ProcessShipmentResult();

            FedExServiceType serviceType;

            if (!WA.Enum <FedExServiceType> .TryParse(order.ShippingServiceOption, out serviceType))
            {
                throw new ApplicationException(string.Format("Unable to determine FedEx service type for '{0}'", order.ShippingServiceOption));
            }

            ContactInfo sender = GetSender();

            ContactInfo recipient = new ContactInfo()
            {
                FirstName   = order.CustomerFirstName,
                LastName    = order.CustomerLastName,
                Email       = order.CustomerEmail,
                Phone       = order.ShipTelephone,
                CompanyName = order.ShipRecipientBusinessName,
                Address     = new WA.Shipping.AddressInfo()
                {
                    StreetLines = new List <string>()
                    {
                        order.ShipAddress1
                    },
                    City        = order.ShipCity,
                    RegionCode  = order.ShipRegion,
                    PostalCode  = order.ShipPostalCode,
                    CountryCode = order.ShipCountryCode
                }
            };

            if (!string.IsNullOrEmpty(order.ShipAddress2))
            {
                recipient.Address.StreetLines.Add(order.ShipAddress2);
            }

            List <PackageInfo> packages = StoreOrderItemsToPackageList(order.OrderItemCollectionByOrderId).ToList();

            ShippingDocumentImageType fedexLabelType = ShippingDocumentImageType.PDF;

            switch (shippingLabelType)
            {
            case ShippingLabelType.PNG:
                fedexLabelType = ShippingDocumentImageType.PNG;
                break;

            case ShippingLabelType.PDF:
                fedexLabelType = ShippingDocumentImageType.PDF;
                break;
            }


            ProcessShipmentReply reply = fedExApi.ProcessShipment(sender, recipient, packages, serviceType, fedexLabelType);

            if ((reply.HighestSeverity != WA.Shipping.FedExShipService.NotificationSeverityType.ERROR) && (reply.HighestSeverity != WA.Shipping.FedExShipService.NotificationSeverityType.FAILURE))
            {
                List <TrackingId> trackingIds = new List <TrackingId>();
                foreach (CompletedPackageDetail pkg in reply.CompletedShipmentDetail.CompletedPackageDetails)
                {
                    //---- Tracking #'s
                    trackingIds.AddRange(pkg.TrackingIds);
                    //foreach (WA.Shipping.FedExShipService.TrackingId trackingId in pkg.TrackingIds)
                    //{
                    //    //Console.WriteLine(string.Format(@"Tracking #: {0}", trackingId.TrackingNumber));
                    //    trackingNums.Add(trackingId.TrackingNumber);
                    //}

                    //---- Package Info/Weights
                    //foreach (WA.Shipping.FedExShipService.PackageRateDetail ratedPackage in pkg.PackageRating.PackageRateDetails)
                    //{
                    //    Console.WriteLine("\nRate details");
                    //    Console.WriteLine("\nRate Type: " + ratedPackage.RateType);
                    //    if (ratedPackage.BillingWeight != null)
                    //        Console.WriteLine("Billing weight {0} {1}", ratedPackage.BillingWeight.Value, ratedPackage.BillingWeight.Units);
                    //    if (ratedPackage.BaseCharge != null)
                    //        Console.WriteLine("Base charge {0} {1}", ratedPackage.BaseCharge.Amount, ratedPackage.BaseCharge.Currency);
                    //    if (ratedPackage.NetCharge != null)
                    //        Console.WriteLine("Net charge {0} {1}", ratedPackage.NetCharge.Amount, ratedPackage.NetCharge.Currency);
                    //    if (ratedPackage.Surcharges != null)
                    //    {
                    //        // Individual surcharge for each package
                    //        foreach (WA.Shipping.FedExShipService.Surcharge surcharge in ratedPackage.Surcharges)
                    //        {
                    //            Console.WriteLine("{0} surcharge {1} {2}", surcharge.SurchargeType, surcharge.Amount.Amount, surcharge.Amount.Currency);
                    //        }
                    //    }
                    //    if (ratedPackage.TotalSurcharges != null)
                    //    {
                    //        Console.WriteLine("Total surcharge {0} {1}", ratedPackage.TotalSurcharges.Amount, ratedPackage.TotalSurcharges.Currency);
                    //    }
                    //}

                    //---- Route / Transit Details
                    //Console.WriteLine("\nRouting details");
                    //Console.WriteLine("URSA prefix {0} suffix {1}", reply.CompletedShipmentDetail.RoutingDetail.UrsaPrefixCode, reply.CompletedShipmentDetail.RoutingDetail.UrsaSuffixCode);
                    //Console.WriteLine("Service commitment {0} Airport ID {1}", reply.CompletedShipmentDetail.RoutingDetail.DestinationLocationId, reply.CompletedShipmentDetail.RoutingDetail.AirportId);

                    //if (reply.CompletedShipmentDetail.RoutingDetail.DeliveryDaySpecified)
                    //{
                    //    Console.WriteLine("Delivery day " + reply.CompletedShipmentDetail.RoutingDetail.DeliveryDay);
                    //}
                    //if (reply.CompletedShipmentDetail.RoutingDetail.DeliveryDateSpecified)
                    //{
                    //    Console.WriteLine("Delivery date " + reply.CompletedShipmentDetail.RoutingDetail.DeliveryDate.ToShortDateString());
                    //}
                    //Console.WriteLine("Transit time " + reply.CompletedShipmentDetail.RoutingDetail.TransitTime);

                    //---- Label
                    //WA.Shipping.FedExShipService.CompletedShipmentDetail completedShipmentDetail = reply.CompletedShipmentDetail;
                    if (pkg.Label.Parts[0].Image != null)
                    {
                        result.ShippingLabelBytes = pkg.Label.Parts[0].Image;
                        result.LabelType          = WA.Enum <ShippingLabelType> .TryParseOrDefault(fedexLabelType.ToString(), ShippingLabelType.PDF);

                        //string labelFilename = string.Format(@"{0}.pdf", pkg.TrackingIds[0].TrackingNumber);

                        // Save label buffer to file
                        //using (FileStream labelFile = new FileStream(labelFilename, FileMode.Create))
                        //{
                        //    labelFile.Write(pkg.Label.Parts[0].Image, 0, pkg.Label.Parts[0].Image.Length);
                        //    labelFile.Close();
                        //}
                        //Console.WriteLine(@"Label file written to ""{0}""", labelFilename);
                    }
                }
                if (trackingIds.Count > 0)
                {
                    result.TrackingNumber = trackingIds.Select(t => string.Format("{0}: {1}", t.TrackingIdType, t.TrackingNumber)).ToList().ToDelimitedString(", ");
                }
                else
                {
                    result.TrackingNumber = trackingIds.Select(t => t.TrackingNumber).First();
                }

                result.Success = true;
            }
            else
            {
                foreach (var error in reply.Notifications)
                {
                    if (error.Severity == WA.Shipping.FedExShipService.NotificationSeverityType.ERROR || error.Severity == WA.Shipping.FedExShipService.NotificationSeverityType.FAILURE)
                    {
                        ErrorMessages.Add(string.Format(@"Code: {0}, Error: {1}", error.Code, error.Message));
                    }
                }

                result.ErrorMessages.AddRange(ErrorMessages);
            }

            return(result);
        }
Beispiel #24
0
        /// <summary>
        /// 获取物流细节
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="notices"></param>
        /// <returns></returns>
        public static Dictionary <string, T> GetLogisticsDetail <T>(Context ctx, List <DeliveryNotice> notices)
        {
            HttpResponseResult     result   = null;
            string                 messages = "";
            Dictionary <string, T> dict     = new Dictionary <string, T>();

            // Set this to true to process a COD shipment and print a COD return Label

            if (notices != null && notices.Count > 0)
            {
                foreach (var notice in notices)
                {
                    if (notice != null && !string.IsNullOrWhiteSpace(notice.F_HS_ShippingMethod))
                    {
                        if (notice.F_HS_ShippingMethod.CompareTo("CN-FEDEX") == 0 || notice.F_HS_ShippingMethod.CompareTo("CN-FEDEX-IE") == 0)
                        {
                            ProcessShipmentRequest request = CreateShipmentRequest(notice);

                            LogXML("DeliveryNoitceNo:" + notice.FBillNo + " Request ", request, typeof(ProcessShipmentRequest));

                            ShipService service = new ShipService();

                            try
                            {
                                // Call the ship web service passing in a ProcessShipmentRequest and returning a ProcessShipmentReply
                                ProcessShipmentReply reply = service.processShipment(request);

                                LogXML("DeliveryNoitceNo:" + notice.FBillNo + " Reply ", reply, typeof(ProcessShipmentReply));
                                messages += GetNotifications(reply);

                                if ((reply.HighestSeverity != NotificationSeverityType.ERROR) && (reply.HighestSeverity != NotificationSeverityType.FAILURE))
                                {
                                    notice.TraceEntry = GetShipmentReply(reply);
                                    //LogXML(reply, typeof(ProcessShipmentReply));
                                    string srcFile  = "C:\\Fedex\\" + reply.CompletedShipmentDetail.CompletedPackageDetails[0].TrackingIds[0].TrackingNumber + ".pdf";
                                    string fileName = reply.CompletedShipmentDetail.CompletedPackageDetails[0].TrackingIds[0].TrackingNumber + ".pdf";
                                    SaveLabel(srcFile, reply.CompletedShipmentDetail.CompletedPackageDetails[0]);
                                    //FileUtil.DownLoad("\\10.2.0.88\FedEx","Abbott","thebest957153", srcFile, fileName);
                                }
                                RecordNotifications(ctx, reply);
                            }
                            catch (SoapException ex)
                            {
                                result          = new HttpResponseResult();
                                result.Message += ex.Message + System.Environment.NewLine + ex.StackTrace;
                                LogUtils.WriteSynchroLog(ctx, SynchroDataType.DeliveryNoticeBill, ex.Message + System.Environment.NewLine + ex.StackTrace);
                            }
                            catch (Exception ex)
                            {
                                result          = new HttpResponseResult();
                                result.Message += ex.Message + System.Environment.NewLine + ex.StackTrace;
                                LogUtils.WriteSynchroLog(ctx, SynchroDataType.DeliveryNoticeBill, ex.Message + System.Environment.NewLine + ex.StackTrace);
                            }
                        }
                        else
                        {
                            result          = new HttpResponseResult();
                            result.Message += "物流方式为CN-FEDEX或CN-FEDEX-IE才可以下单FedEx!";
                        }
                    }
                }
            }
            else
            {
                result          = new HttpResponseResult();
                result.Message += "根据出货表编码查询不到相关的出货信息!";
            }

            if (!string.IsNullOrWhiteSpace(messages))
            {
                result         = new HttpResponseResult();
                result.Message = messages;
            }

            dict.Add("result", (T)(Object)result);
            dict.Add("notices", (T)(Object)notices);

            return(dict);
        }