public CreatePickupResponse RequestNewPickup(CreatePickupRequest req)
        {
            // Validate the request

            List <ValidationResult> validationResult = Common.Validate(ref req);

            if (validationResult.Any())
            {
                string errors = MyDHLAPIValidationException.PrintResults(validationResult);
                throw new MyDHLAPIValidationException(validationResult);
            }

            LastJSONRequest           = JsonConvert.SerializeObject(req, Formatting.Indented);
            LastNewPickupJSONRequest  = LastJSONRequest;
            LastJSONResponse          = SendRequestAndReceiveResponse(LastJSONRequest, "PickupRequest");
            LastNewPickupJSONResponse = LastJSONResponse;

            CreatePickupResponse retval;

            try
            {
                // Deserialize the result back to an object.
                List <string> errors = new List <string>();

                retval = JsonConvert.DeserializeObject <CreatePickupResponse>(LastJSONResponse
                                                                              , new JsonSerializerSettings()
                {
                    Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
                    {
                        errors.Add(args.ErrorContext.Error.Message);
                        args.ErrorContext.Handled = true;
                    }
                });
            }
            catch
            {
                retval = new CreatePickupResponse();
            }

            return(retval);
        }
Beispiel #2
0
        private void BtnRequestPickup_Click(object sender, EventArgs e)
        {
            ClearInputErrors();

            SetStatusText("Validating inputs...", true, true, 0);

            // Set our time counters
            DateTime processStart          = DateTime.Now;
            DateTime rateQueryRequestStart = DateTime.Now;
            DateTime rateQueryRequestEnd   = DateTime.Now;
            DateTime pickupRequestStart    = DateTime.Now;
            DateTime pickupRequestEnd      = DateTime.Now;

            // Validate all our inputs
            if (!ValidateInputs())
            {
                MessageBox.Show("Please fix the issues on the inputs marked in red.");
                SetStatusText("Input validation failed!", false);
                return;
            }

            // All validation done, send the data to GloWS.
#pragma warning disable IDE0017 // Simplify object initialization
            try
            {
                this.Enabled = false;

                // Clear result fields
                txtResultBookingReferenceNumber.Clear();
                Application.DoEvents();

                // Determine if this is a dox or non-dox shipment
                bool isDox      = !(new[] { "3", "4", "8", "E", "F", "H", "J", "M", "P", "Q", "V", "Y" }).Contains(cmbProductCode.SelectedValue.ToString());
                bool isDomestic = "N" == cmbProductCode.Text;

                SetStatusText("Preparing request...", true, true, 10);

                MyDHLAPI api = new MyDHLAPI_REST_Library.MyDHLAPI(Common.CurrentCredentials["Username"]
                                                                  , Common.CurrentCredentials["Password"]
                                                                  , Common.CurrentRestBaseUrl);

                CreatePickupRequest req = new CreatePickupRequest();

                /*** Request Header ***/
                //req.PickUpRequest.Request = new Request()
                //{
                //    ServiceHeader = new ServiceHeader()
                //    {
                //        ShippingSystemPlatform = "MyDHL API Test App"
                //        , ShippingSystemPlatformVersion = Application.ProductVersion
                //        , Plugin = "MyDHL API C# Library"
                //        , PluginVersion = api.GetVersion()
                //    }
                //};

#pragma warning restore IDE0017 // Simplify object initialization
                req.PickUpRequest = new PickUpRequest();
                req.PickUpRequest.PickUpShipment = new PickUpShipment();
                req.PickUpRequest.PickUpShipment.ShipmentDetails = new ShipmentDetails();

                req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.ServiceType      = cmbProductCode.SelectedValue.ToString();
                req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.LocalServiceType = cmbProductCode.SelectedValue.ToString();

                // SU = Standard (american) Units (LB, IN); SI = Standard International (KG, CM)
                if ("KG" == cmbShipmentWeightUOM.SelectedValue.ToString())
                {
                    req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.UnitOfMeasurement = Enums.UnitOfMeasurement.SI;
                }
                else
                {
                    req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.UnitOfMeasurement = Enums.UnitOfMeasurement.SU;
                }

                // If the billing element is defined (it should be used anyway) then there is no need for the
                // generic shipmentInfo.Account element to be populated.
                //shipmentInfo.Account = txtShipperAccountNumber.Text;
                req.PickUpRequest.PickUpShipment.Billing = new Billing(txtShipperAccountNumber.Text
                                                                       , Enums.PaymentTypes.Shipper);
                DateTime timestamp;

                if (DateTime.Now.TimeOfDay > new TimeSpan(18, 00, 00))
                {
                    timestamp = DateTime.Now.AddDays(1);
                    timestamp = new DateTime(timestamp.Year, timestamp.Month, timestamp.Day, 10, 0, 0);
                }
                else
                {
                    timestamp = DateTime.Now.AddMinutes(10);
                }

                req.PickUpRequest.PickUpShipment.PickupTimestamp         = timestamp;
                req.PickUpRequest.PickUpShipment.PickupLocationCloseTime = timestamp.AddHours(4).TimeOfDay;

                req.PickUpRequest.PickUpShipment.Addresses = new AddressInformation();

                req.PickUpRequest.PickUpShipment.Remarks = txtRemarks.Text;

                /*** SHIPPER ***/
                AddressData shipper = new AddressData();

                if (!IsBlank(txtShipperCompany))
                {
                    shipper.Contact.CompanyName = txtShipperCompany.Text;
                }
                else
                {
                    shipper.Contact.CompanyName = txtShipperName.Text;
                }
                shipper.Contact.PersonName   = txtShipperName.Text;
                shipper.Contact.EMailAddress = txtShipperEMailAddress.Text;
                shipper.Contact.PhoneNumber  = txtShipperMobileNumber.Text;

                shipper.Address.AddressLine1    = txtShipperAddress1.Text;
                shipper.Address.AddressLine2    = txtShipperAddress2.Text;
                shipper.Address.AddressLine3    = txtShipperAddress3.Text;
                shipper.Address.CityName        = txtShipperCity.Text;
                shipper.Address.USStateCode     = txtShipperState.Text;
                shipper.Address.CountryCode     = txtShipperCountry.Text;
                shipper.Address.PostalOrZipCode = txtShipperPostalCode.Text;

                req.PickUpRequest.PickUpShipment.Addresses.Shipper = shipper;

                /*** CONSIGNEE ***/
                AddressData consignee = new AddressData();

                if (!IsBlank(txtConsigneeCompany))
                {
                    consignee.Contact.CompanyName = txtConsigneeCompany.Text;
                }
                else
                {
                    consignee.Contact.CompanyName = txtConsigneeName.Text;
                }
                consignee.Contact.PersonName   = txtConsigneeName.Text;
                consignee.Contact.EMailAddress = txtConsigneeEMailAddress.Text;
                consignee.Contact.PhoneNumber  = txtConsigneeMobileNumber.Text;

                consignee.Address.AddressLine1    = txtConsigneeAddress1.Text;
                consignee.Address.AddressLine2    = txtConsigneeAddress2.Text;
                consignee.Address.AddressLine3    = txtConsigneeAddress3.Text;
                consignee.Address.CityName        = txtConsigneeCity.Text;
                consignee.Address.USStateCode     = txtConsigneeState.Text;
                consignee.Address.CountryCode     = txtConsigneeCountry.Text;
                consignee.Address.PostalOrZipCode = txtConsigneePostalCode.Text;

                req.PickUpRequest.PickUpShipment.Addresses.Recipient = consignee;

                /*** PICKUP ***/
                req.PickUpRequest.PickUpShipment.Addresses.Pickup = req.PickUpRequest.PickUpShipment.Addresses.Shipper;

                /*** REQUESTOR ***/
                req.PickUpRequest.PickUpShipment.Addresses.BookingRequestor = req.PickUpRequest.PickUpShipment.Addresses.Recipient;

                /*** PIECES ***/

                Package singlePackage = new Package
                {
                    PackageNumber      = 1,
                    Weight             = decimal.Parse($"{txtShipmentWeight.Text}"),
                    CustomerReferences = txtShipmentReference.Text,
                };

                decimal height = GetDimension(ref txtShipmentHeight);
                decimal width  = GetDimension(ref txtShipmentWidth);
                decimal depth  = GetDimension(ref txtShipmentDepth);

                if (height > 0 &&
                    width > 0 &&
                    depth > 0)
                {
                    // Keep the divisor at 5000.0, this forces .NET to treate the result as a float and not an integer.
                    singlePackage.Dimensions = new Dimensions(height, width, depth);
                }

                req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.Packages             = new Packages();
                req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.Packages.PackageList = new List <Package>();
                req.PickUpRequest.PickUpShipment.ShipmentDetails.ShipmentDetail.Packages.PackageList.Add(singlePackage);

                /*** GENERATE PICKUP ***/
                CreatePickupResponse resp;

                SetStatusText("Sending shipment request...", true, true, 40);

                try
                {
                    pickupRequestStart = DateTime.Now;
                    resp = api.RequestNewPickupAsync(req).Result;
                }
                catch (MyDHLAPIValidationException gvx)
                {
                    MessageBox.Show(gvx.Message, "GVX");
                    txtResultBookingReferenceNumber.Text = "VALIDATION ERROR!";
                    if (gvx.Data.Contains("ValidationResults"))
                    {
                        txtMessages.Text = MyDHLAPIValidationException.PrintResults((List <ValidationResult>)gvx.Data["ValidationResults"]);
                    }
                    SetStatusText($"Shipment contains validation errors! Took {(DateTime.Now - processStart):hh\\:mm\\:ss}", false);
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "EX");
                    txtResultBookingReferenceNumber.Text = "ERROR!";
                    SetStatusText($"Shipment error! Took {(DateTime.Now - processStart):hh\\:mm\\:ss}", false);
                    return;
                }
                finally
                {
                    pickupRequestEnd = DateTime.Now;
                }

                MyDHLAPI_Request  = api.LastNewPickupJSONRequest;
                MyDHLAPI_Response = api.LastNewPickupJSONResponse;

                if (null == resp || !Notification.HasSuccessCode(resp.Notifications))
                {
                    MessageBox.Show("There was an error in requesting the pickup.");
                    SetStatusText($"Pickup generation failed! Took {(DateTime.Now - processStart):c}", false);
                    return;
                }

                SetStatusText($"Pickup Requested, displaying results...", true, true, 50);

                // Display our results

                txtResultBookingReferenceNumber.Text = (string.IsNullOrEmpty(resp.PickupRequestNumber) ? string.Empty : resp.PickupRequestNumber);
                txtMessages.Text = Notification.GetAllNotifications(resp.Notifications, Environment.NewLine);

                DateTime processEnd = DateTime.Now;

                /*** Save for cancelation ***/
                Common.SuccessfulPickupRequests.Add(new Objects.SuccessfulPickupRequest()
                {
                    PickupDate            = req.PickUpRequest.PickUpShipment.PickupTimestamp
                    , PickupCountry       = req.PickUpRequest.PickUpShipment.Addresses.Pickup.Address.CountryCode
                    , RequestorName       = req.PickUpRequest.PickUpShipment.Addresses.BookingRequestor.Contact.PersonName
                    , PickupRequestNumber = resp.PickupRequestNumber
                });

                /*** Set status bar time sections ***/
                SetStatusTimeText(ref tsslPickupTimeLabel, ref tsslPickupTime, pickupRequestStart, pickupRequestEnd);
                SetStatusTimeText(ref tsslTotalTimeLabel, ref tsslTotalTime, processStart, processEnd);
                SetStatusText("Process complete.", false);
            }
            finally
            {
                this.Enabled = true;
            }
        }
 public Task <CreatePickupResponse> RequestNewPickupAsync(CreatePickupRequest req)
 {
     return(Task.Run(() => RequestNewPickup(req)));
 }