public CreateShipmentResponse RequestShipment(CreateShipmentRequest req) { // First generate the JSON request (for possible use by the developer later) LastJSONRequest = JsonConvert.SerializeObject(req, Formatting.Indented); LastShipJSONRequest = LastJSONRequest; // Validate the request List <ValidationResult> validationResult = Common.Validate(ref req); if (validationResult.Any()) { string errors = MyDHLAPIValidationException.PrintResults(validationResult); throw new MyDHLAPIValidationException(validationResult); } // Send the request and capture the response LastJSONResponse = SendRequestAndReceiveResponse(LastJSONRequest, "ShipmentRequest"); LastShipJSONResponse = LastJSONResponse; CreateShipmentResponse retval; try { // Deserialize the result back to an object. List <string> errors = new List <string>(); retval = JsonConvert.DeserializeObject <CreateShipmentResponse>(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 CreateShipmentResponse(); } return(retval); }
public DeletePickupResponse RequestDeletePickup(DeletePickupRequest 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); LastDeletePickupJSONRequest = LastJSONRequest; LastJSONResponse = SendRequestAndReceiveResponse(LastJSONRequest, "DeleteShipment"); LastDeletePickupJSONResponse = LastJSONResponse; DeletePickupResponse retval; try { // Deserialize the result back to an object. List <string> errors = new List <string>(); retval = JsonConvert.DeserializeObject <DeletePickupResponse>(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 DeletePickupResponse(); } return(retval); }
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; } }
private void BtnGo_Click(object sender, EventArgs e) { try { this.Enabled = false; this.UseWaitCursor = true; Cursor.Current = Cursors.WaitCursor; if (string.IsNullOrWhiteSpace(txtAccountNumber.Text) || string.IsNullOrWhiteSpace(txtAWBNumber.Text)) { MessageBox.Show(@"Missing data."); return; } txtAccountNumber.Text = txtAccountNumber.Text.Trim(); txtAWBNumber.Text = txtAWBNumber.Text.Trim(); MyDHLAPI api = new MyDHLAPI(Common.CurrentCredentials["Username"] , Common.CurrentCredentials["Password"] , Common.CurrentRestBaseUrl); EPodResponse ePod = api.GetEPod(txtAWBNumber.Text , txtAccountNumber.Text // ReSharper disable once PossibleInvalidCastException , (Enums.EPodType)cmbPODType.SelectedItem); _lastJsonRequest = api.LastEPoDJSONRequest; _lastJsonResponse = api.LastEPoDJSONResponse; if (null != ePod && null != ePod.EPod) { string tempFilename = System.IO.Path.GetTempFileName(); switch (ePod.EPod.MimeType) { case "application/pdf": tempFilename += ".pdf"; break; case "image/jpeg": case "image/jpg": tempFilename += ".jpg"; break; case "image/png": tempFilename += ".png"; break; } System.IO.File.WriteAllBytes(tempFilename, ePod.EPod.Image); System.Diagnostics.Process.Start(tempFilename); } else { txtResult.Text = "ePOD not found for the supplied AWB # and Account # combination."; } } catch (MyDHLAPIValidationException gvx) { txtResult.Text = MyDHLAPIValidationException.PrintResults(gvx.ExtractValidationResults(), 0); } catch (Exception ex) { txtResult.Text = ex.Message; } finally { this.Enabled = true; this.UseWaitCursor = false; Cursor.Current = Cursors.Default; } }
private void BtnGo_Click(object sender, EventArgs e) { MyDHLAPI api = new MyDHLAPI(Common.CurrentCredentials["Username"] , Common.CurrentCredentials["Password"] , Common.CurrentRestBaseUrl); try { this.Enabled = false; this.UseWaitCursor = true; Cursor.Current = Cursors.WaitCursor; if (string.IsNullOrWhiteSpace(txtPickupCountry.Text) || string.IsNullOrWhiteSpace(txtRequestorName.Text)) { MessageBox.Show(@"Missing data."); return; } txtPickupCountry.Text = txtPickupCountry.Text.Trim(); txtRequestorName.Text = txtRequestorName.Text.Trim(); txtPickupRequestNumber.Text = txtPickupRequestNumber.Text.Trim(); DeletePickupRequest req = new DeletePickupRequest { DeleteRequest = new DeleteRequest { Request = new Request() { ServiceHeader = new ServiceHeader() { ShippingSystemPlatform = "MyDHL API Test App", ShippingSystemPlatformVersion = Application.ProductVersion, Plugin = "MyDHL API C# Library", PluginVersion = api.GetVersion() } }, PickupDate = dtpPickupDate.Value, PickupCountry = txtPickupCountry.Text, RequestorName = txtRequestorName.Text, PickupRequestNumber = txtPickupRequestNumber.Text, Reason = (Enums.DeletePickupRequestReason)cmbReason.SelectedValue } }; DeletePickupResponse resp = api.RequestDeletePickupAsync(req).Result; if (null != resp) { txtResult.Text = Notification.GetAllNotifications(resp.Notifications, Environment.NewLine); } } catch (MyDHLAPIValidationException gvx) { txtResult.Text = MyDHLAPIValidationException.PrintResults(gvx.ExtractValidationResults(), 0); } catch (Exception ex) { txtResult.Text = ex.Message; } finally { this.Enabled = true; this.UseWaitCursor = false; Cursor.Current = Cursors.Default; _lastJsonRequest = api.LastDeletePickupJSONRequest; _lastJsonResponse = api.LastDeletePickupJSONResponse; } }