/// <summary>
        /// Returns decoded pdf file
        /// </summary>
        /// <param name="shipmentNumber"></param>
        /// <param name="printerName"></param>
        /// <returns></returns>
        public byte[] PrintLabel(string shipmentNumber)
        {
            shippingAPIPortTypeClient client = GetProxy();
            var request = new printLabelRequest();

            request.integrationHeader = GetIntegrationHeader();
            request.shipmentNumber    = shipmentNumber;
            request.outputFormat      = "PDF";

            // http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-sharp-web-service-client-consuming-axis-1-4
            //XmlHelper.Serialise<createShipmentRequest>(request, @"C:\test\createShipmentRequest.xml");
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {
                var httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add(@"X-IBM-Client-Id", _credentials.HttpSecurity.ClientId);
                httpRequestProperty.Headers.Add(@"X-IBM-Client-Secret", _credentials.HttpSecurity.ClientSecret);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                printLabelResponse response = client.printLabel(GetSecurityHeaderType(), request);

                CheckErrorsAndWarnings(response.integrationFooter);
                var labelBytes = response.label;
                return(labelBytes);
            }
        }
        private shippingAPIPortTypeClient GetProxy()
        {
            // binding comes from configuration file
            var shippingClient = new shippingAPIPortTypeClient();

            // TODOP is it even needed at this point?
            shippingClient.ClientCredentials.UserName.UserName = _credentials.SoapSecurity.Username;
            shippingClient.ClientCredentials.UserName.Password = _credentials.SoapSecurity.Password;

            shippingClient.ClientCredentials.UseIdentityConfiguration = true;

            foreach (OperationDescription od in shippingClient.Endpoint.Contract.Operations)
            {
                od.Behaviors.Add(new RoyalMailIEndpointBehavior());
            }

            return(shippingClient);
        }
        public createShipmentResponse CreateShipment(PPLabel labelData)
        {
            shippingAPIPortTypeClient client = GetProxy();

            try
            {
                createShipmentRequest request = new createShipmentRequest();
                request.integrationHeader = GetIntegrationHeader();

                requestedShipment shipment = new requestedShipment();

                // Shipment Type Code (Delivery or Return)
                shipment.shipmentType = new referenceDataType()
                {
                    code = SHIPMENT_TYPE
                };;

                // Service Occurence (Identifies Agreement on Customers Account) Default to 1. Not Required If There Is There Is Only 1 On Account
                shipment.serviceOccurrence = SERVICE_OCCURANCE;

                // Service Type Code (1:24H 1st Class, 2: 48H 2nd Class, D: Special Delivery Guaranteed, H: HM Forces (BFPO), I: International, R: Tracked Returns, T: Tracked Domestic)
                referenceDataType serviceType = new referenceDataType();
                serviceType.code     = labelData.IntegrationCode1;
                shipment.serviceType = serviceType;

                // Service Offering (See Royal Mail Service Offering Type Codes. Too Many To List)
                serviceOfferingType serviceOfferingTypeContainer = new serviceOfferingType();
                referenceDataType   serviceOffering = new referenceDataType()
                {
                    code = labelData.IntegrationCode2
                };
                serviceOfferingTypeContainer.serviceOfferingCode = serviceOffering;
                shipment.serviceOffering = serviceOfferingTypeContainer;

                // Service Format Code
                serviceFormatType serviceFormatTypeContainer = new serviceFormatType();
                referenceDataType serviceFormat = new referenceDataType();
                serviceFormat.code = labelData.IntegrationCode3;
                serviceFormatTypeContainer.serviceFormatCode = serviceFormat;
                shipment.serviceFormat = serviceFormatTypeContainer;

                // Shipping Date
                shipment.shippingDate          = DateTime.ParseExact(labelData.ShippingDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);;
                shipment.shippingDateSpecified = true;

                //Signature Required (Only Available On Tracked Services)
                shipment.signature          = labelData.IntegrationCode4;
                shipment.signatureSpecified = true;

                // Leave In Safe Place (Available On Tracked Non Signature Service Offerings)
                shipment.safePlace = labelData.Address.SafePlace;

                // Sender Reference Number (e.g. Invoice Number or RA Number)
                shipment.senderReference = labelData.OrderReference;

                /*
                 * Service Enhancements
                 */

                //List<serviceEnhancementType> serviceEnhancements = new List<serviceEnhancementType>();

                //List<dataObjects.ServiceEnhancement> selectedEnhancements = shippingForm.GetServiceEnhancements();

                //for (int i = 0; i < selectedEnhancements.Count; i++)
                //{
                //    serviceEnhancementType enhancement = new serviceEnhancementType();
                //    referenceDataType enhancementCode = new referenceDataType();
                //    enhancementCode.code = selectedEnhancements.ElementAt(i).GetEnhancementType().ToString();
                //    enhancement.serviceEnhancementCode = enhancementCode;
                //    serviceEnhancements.Add(enhancement);
                //}

                //shipment.serviceEnhancements = serviceEnhancements.ToArray();


                /*
                 * Recipient Contact Details
                 */

                contact recipientContact = new contact()
                {
                    name = labelData.Address.ContactName,
                    complementaryName = labelData.Address.CompanyName
                };

                if (string.IsNullOrWhiteSpace(labelData.Address.Email) == false)
                {
                    digitalAddress email = new digitalAddress();
                    email.electronicAddress            = labelData.Address.Email;
                    recipientContact.electronicAddress = email;
                }

                if (string.IsNullOrWhiteSpace(labelData.Address.Phone) == false)
                {
                    telephoneNumber tel = new telephoneNumber();

                    Regex phoneRegex = new Regex(@"[^\d]");
                    tel.telephoneNumber1 = phoneRegex.Replace(labelData.Address.Phone, "");
                    // TODOP unhardcode dialing code
                    //tel.countryCode = "00" + shippingForm.GetCountry().GetDialingCode();
                    tel.countryCode = "00" + "44";
                    recipientContact.telephoneNumber = tel;
                }

                shipment.recipientContact = recipientContact;

                /*
                 * Recipient Address
                 *
                 */
                address recipientAddress = new address();
                recipientAddress.addressLine1 = labelData.Address.AddLine1;
                recipientAddress.addressLine2 = labelData.Address.AddLine2;
                //recipientAddress.addressLine3 = shippingForm.GetAddressLine3();
                //recipientAddress.addressLine4 = shippingForm.GetCounty();
                recipientAddress.postTown = labelData.Address.Town;
                countryType       country     = new countryType();
                referenceDataType countryCode = new referenceDataType();
                countryCode.code          = labelData.Address.CountryCodeIso2;
                country.countryCode       = countryCode;
                recipientAddress.country  = country;
                recipientAddress.postcode = labelData.Address.Postcode;

                //recipientAddress.stateOrProvince = new stateOrProvinceType();
                //recipientAddress.stateOrProvince.stateOrProvinceCode = new referenceDataType();

                shipment.recipientAddress = recipientAddress;

                // Shipment Items

                if ("I".Equals(labelData.IntegrationCode1)) // International shipment
                {
                    internationalInfo InternationalInfo = new internationalInfo();
                    InternationalInfo.shipperExporterVatNo = "GB945777273";
                    InternationalInfo.documentsOnly        = false;
                    InternationalInfo.shipmentDescription  = "Invoice Number: " + labelData.OrderReference;
                    InternationalInfo.invoiceDate          = DateTime.Now;
                    //InternationalInfo.termsOfDelivery = "EXW"; // TODOP don't know what it is
                    InternationalInfo.invoiceDateSpecified = true;
                    InternationalInfo.purchaseOrderRef     = labelData.OrderReference;

                    List <parcel> parcels = new List <parcel>();
                    foreach (var i in labelData.Items)
                    {
                        parcel Parcel = new parcel();
                        Parcel.weight               = new dimension();
                        Parcel.weight.value         = (float)(i.Weight);
                        Parcel.weight.unitOfMeasure = new unitOfMeasureType();
                        Parcel.weight.unitOfMeasure.unitOfMeasureCode      = new referenceDataType();
                        Parcel.weight.unitOfMeasure.unitOfMeasureCode.code = "g";

                        Parcel.invoiceNumber          = labelData.OrderReference;
                        Parcel.purposeOfShipment      = new referenceDataType();
                        Parcel.purposeOfShipment.code = "31";

                        List <contentDetail> Contents = new List <contentDetail>();

                        // Harcoded all these values according to my circumstances
                        contentDetail ContentDetail = new contentDetail();
                        ContentDetail.articleReference                      = "O";
                        ContentDetail.countryOfManufacture                  = new countryType();
                        ContentDetail.countryOfManufacture.countryCode      = new referenceDataType();
                        ContentDetail.countryOfManufacture.countryCode.code = "GB";

                        ContentDetail.currencyCode             = new referenceDataType();
                        ContentDetail.currencyCode.code        = "GBP";
                        ContentDetail.description              = "Printed goods";
                        ContentDetail.unitQuantity             = "1";
                        ContentDetail.unitValue                = Convert.ToDecimal(i.Price / 100.00m);
                        ContentDetail.unitWeight               = new dimension();
                        ContentDetail.unitWeight.value         = Convert.ToSingle(i.Weight);
                        ContentDetail.unitWeight.unitOfMeasure = new unitOfMeasureType();
                        ContentDetail.unitWeight.unitOfMeasure.unitOfMeasureCode      = new referenceDataType();
                        ContentDetail.unitWeight.unitOfMeasure.unitOfMeasureCode.code = "g";


                        Contents.Add(ContentDetail);

                        Parcel.contentDetails = Contents.ToArray();

                        parcels.Add(Parcel);
                    }

                    InternationalInfo.parcels = parcels.ToArray();

                    shipment.internationalInfo = InternationalInfo;
                }
                else
                {
                    List <RoyalMailApiWsdl.item> items = new List <RoyalMailApiWsdl.item>();

                    foreach (var i in labelData.Items)
                    {
                        RoyalMailApiWsdl.item item = new RoyalMailApiWsdl.item();
                        item.numberOfItems = "1";
                        item.weight        = new dimension();
                        item.weight.value  = (float)(i.Weight);

                        item.weight.unitOfMeasure = new unitOfMeasureType();
                        item.weight.unitOfMeasure.unitOfMeasureCode      = new referenceDataType();
                        item.weight.unitOfMeasure.unitOfMeasureCode.code = "g";

                        items.Add(item);
                    }
                    shipment.items = items.ToArray();
                }

                request.requestedShipment = shipment;
                // http://stackoverflow.com/questions/897782/how-to-add-custom-http-header-for-c-sharp-web-service-client-consuming-axis-1-4
                //XmlHelper.Serialise<createShipmentRequest>(request, @"C:\test\createShipmentRequest.xml");
                using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                {
                    var httpRequestProperty = new HttpRequestMessageProperty();
                    httpRequestProperty.Headers.Add(@"X-IBM-Client-Id", _credentials.HttpSecurity.ClientId);
                    httpRequestProperty.Headers.Add(@"X-IBM-Client-Secret", _credentials.HttpSecurity.ClientSecret);
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                    createShipmentResponse response = client.createShipment(GetSecurityHeaderType(), request);
                    CheckErrorsAndWarnings(response.integrationFooter);
                    //XmlHelper.Serialise(request, @"c:\test\createShipmentRequest.xml");
                    //XmlHelper.Serialise(response, @"c:\test\createShipmentResponse.xml");
                    return(response);
                }
            }
            catch (TimeoutException e)
            {
                client.Abort();
                _log.Error("Request timed out", e);
            }
            catch (FaultException e)
            {
                client.Abort();
                LogSoapException(e);
            }
            catch (CommunicationException e)
            {
                client.Abort();
                _log.Error("A communication error has occured", e);
            }
            catch (Exception e)
            {
                client.Abort();
                _log.Error("Royal Mail Api error", e);
            }

            return(null);
        }