Exemple #1
0
        public void GetTransactionDetails(Orders order)
        {
            GetTransactionDetailsRequestType detailRequest = new GetTransactionDetailsRequestType();

            detailRequest.TransactionID = order.TransactionID;
            detailRequest.Version       = "2.0";
            GetTransactionDetailsReq request = new GetTransactionDetailsReq();

            request.GetTransactionDetailsRequest = detailRequest;

            GetTransactionDetailsResponseType response = service.GetTransactionDetails(request);

            string sErrors = this.CheckForErrors(response);

            if (sErrors == string.Empty)
            {
                PaymentInfoType payment = response.PaymentTransactionDetails.PaymentInfo;

                order.OrderTotal    = GetAmountValue(payment.GrossAmount);
                order.Tax           = GetAmountValue(payment.TaxAmount);
                IsSubmissionSuccess = true;
            }
            else
            {
                IsSubmissionSuccess = false;
            }
        }
Exemple #2
0
        private void AddBillShipperAccount(ShipmentType shipment)
        {
            var paymentInfo   = new PaymentInfoType();
            var shpmentCharge = new ShipmentChargeType();
            var billShipper   = new BillShipperType();

            billShipper.AccountNumber = BillShipperAccountNumber;
            shpmentCharge.BillShipper = billShipper;
            shpmentCharge.Type        = ShipmentChargeType;
            ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
            paymentInfo.ShipmentCharge  = shpmentChargeArray;
            shipment.PaymentInformation = paymentInfo;
        }
        private void AddPaymentInformation(ShipmentType shipment)
        {
            var paymentInfo = new PaymentInfoType();

            var paymentInfoType = new PaymentType();

            paymentInfoType.Code = "06";
            var shipper = new ShipperType();

            shipper.ShipperNumber = ShipperNumber;
            shipper.Name          = ShipperName;
            AddShipperAddress(shipper);
            shipment.Shipper = shipper;
        }
        private void AddBillShipperAccount(ShipmentType shipment)
        {
            var paymentInfo   = new PaymentInfoType();
            var shpmentCharge = new ShipmentChargeType();
            var billShipper   = new BillShipperType();

            log.Debug("<<<Billshipper payment information>>>");
            billShipper.AccountNumber = BillShipperAccountNumber;
            log.Debug("Bill shipper: " + BillShipperAccountNumber);
            shpmentCharge.BillShipper = billShipper;

            shpmentCharge.Type = ShipmentChargeType;
            log.Debug("Shipment charge type: " + ShipmentChargeType);
            ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
            paymentInfo.ShipmentCharge  = shpmentChargeArray;
            shipment.PaymentInformation = paymentInfo;
        }
Exemple #5
0
 static void Main()
 {
     try
     {
         ShipService     shpSvc          = new ShipService();
         ShipmentRequest shipmentRequest = new ShipmentRequest();
         UPSSecurity     upss            = new UPSSecurity();
         UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
         upssSvcAccessToken.AccessLicenseNumber = "Your Access License";
         upss.ServiceAccessToken = upssSvcAccessToken;
         UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
         upssUsrNameToken.Username = "******";
         upssUsrNameToken.Password = "******";
         upss.UsernameToken        = upssUsrNameToken;
         shpSvc.UPSSecurityValue   = upss;
         RequestType request       = new RequestType();
         String[]    requestOption = { "nonvalidate" };
         request.RequestOption   = requestOption;
         shipmentRequest.Request = request;
         ShipmentType shipment = new ShipmentType();
         shipment.Description = "Ship webservice example";
         ShipperType shipper = new ShipperType();
         shipper.ShipperNumber = "Your Shipper Number";
         PaymentInfoType    paymentInfo   = new PaymentInfoType();
         ShipmentChargeType shpmentCharge = new ShipmentChargeType();
         BillShipperType    billShipper   = new BillShipperType();
         billShipper.AccountNumber = "Your Account Number";
         shpmentCharge.BillShipper = billShipper;
         shpmentCharge.Type        = "01";
         ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
         paymentInfo.ShipmentCharge  = shpmentChargeArray;
         shipment.PaymentInformation = paymentInfo;
         ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
         String[] addressLine = { "480 Parkton Plaza" };
         shipperAddress.AddressLine       = addressLine;
         shipperAddress.City              = "Timonium";
         shipperAddress.PostalCode        = "21093";
         shipperAddress.StateProvinceCode = "MD";
         shipperAddress.CountryCode       = "US";
         shipperAddress.AddressLine       = addressLine;
         shipper.Address       = shipperAddress;
         shipper.Name          = "ABC Associates";
         shipper.AttentionName = "ABC Associates";
         ShipPhoneType shipperPhone = new ShipPhoneType();
         shipperPhone.Number = "1234567890";
         shipper.Phone       = shipperPhone;
         shipment.Shipper    = shipper;
         ShipFromType shipFrom = new ShipFromType();
         ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
         String[] shipFromAddressLine = { "Ship From Street" };
         shipFromAddress.AddressLine       = addressLine;
         shipFromAddress.City              = "Timonium";
         shipFromAddress.PostalCode        = "21093";
         shipFromAddress.StateProvinceCode = "MD";
         shipFromAddress.CountryCode       = "US";
         shipFrom.Address       = shipFromAddress;
         shipFrom.AttentionName = "Mr.ABC";
         shipFrom.Name          = "ABC Associates";
         shipment.ShipFrom      = shipFrom;
         ShipToType        shipTo        = new ShipToType();
         ShipToAddressType shipToAddress = new ShipToAddressType();
         String[]          addressLine1  = { "Some Street" };
         shipToAddress.AddressLine       = addressLine1;
         shipToAddress.City              = "Roswell";
         shipToAddress.PostalCode        = "30076";
         shipToAddress.StateProvinceCode = "GA";
         shipToAddress.CountryCode       = "US";
         shipTo.Address       = shipToAddress;
         shipTo.AttentionName = "DEF";
         shipTo.Name          = "DEF Associates";
         ShipPhoneType shipToPhone = new ShipPhoneType();
         shipToPhone.Number = "1234567890";
         shipTo.Phone       = shipToPhone;
         shipment.ShipTo    = shipTo;
         ServiceType service = new ServiceType();
         service.Code     = "01";
         shipment.Service = service;
         PackageType       package       = new PackageType();
         PackageWeightType packageWeight = new PackageWeightType();
         packageWeight.Weight = "10";
         ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
         uom.Code = "LBS";
         packageWeight.UnitOfMeasurement = uom;
         package.PackageWeight           = packageWeight;
         PackagingType packType = new PackagingType();
         packType.Code     = "02";
         package.Packaging = packType;
         PackageType[] pkgArray = { package };
         shipment.Package = pkgArray;
         LabelSpecificationType labelSpec      = new LabelSpecificationType();
         LabelStockSizeType     labelStockSize = new LabelStockSizeType();
         labelStockSize.Height    = "6";
         labelStockSize.Width     = "4";
         labelSpec.LabelStockSize = labelStockSize;
         LabelImageFormatType labelImageFormat = new LabelImageFormatType();
         labelImageFormat.Code              = "SPL";
         labelSpec.LabelImageFormat         = labelImageFormat;
         shipmentRequest.LabelSpecification = labelSpec;
         shipmentRequest.Shipment           = shipment;
         Console.WriteLine(shipmentRequest);
         System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
         ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
         Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
         Console.WriteLine("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
         Console.ReadKey();
     }
     catch (System.Web.Services.Protocols.SoapException ex)
     {
         Console.WriteLine("");
         Console.WriteLine("---------Ship Web Service returns error----------------");
         Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
         Console.WriteLine("SoapException Message= " + ex.Message);
         Console.WriteLine("");
         Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
         Console.WriteLine("");
         Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
         Console.WriteLine("");
         Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
         Console.WriteLine("-------------------------");
         Console.WriteLine("");
     }
     catch (System.ServiceModel.CommunicationException ex)
     {
         Console.WriteLine("");
         Console.WriteLine("--------------------");
         Console.WriteLine("CommunicationException= " + ex.Message);
         Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
         Console.WriteLine("-------------------------");
         Console.WriteLine("");
     }
     catch (Exception ex)
     {
         Console.WriteLine("");
         Console.WriteLine("-------------------------");
         Console.WriteLine(" General Exception= " + ex.Message);
         Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
         Console.WriteLine("-------------------------");
     }
     finally
     {
         Console.ReadKey();
     }
 }
Exemple #6
0
        private string PrintLabel()
        {
            try
            {
                ShipService     shpSvc          = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();
                UPSSecurity     upss            = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = hfLicense.Value;
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = hfUserName.Value;
                upssUsrNameToken.Password = hfPassword.Value;
                upss.UsernameToken        = upssUsrNameToken;
                shpSvc.UPSSecurityValue   = upss;
                RequestType request       = new RequestType();
                String[]    requestOption = { lblAddressValidation.Text.Trim() };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;
                ShipmentType shipment = new ShipmentType();
                shipment.Description = "CMS Label Printing";
                ShipperType shipper = new ShipperType();
                shipper.ShipperNumber = hfAccountNumber.Value;
                PaymentInfoType    paymentInfo   = new PaymentInfoType();
                ShipmentChargeType shpmentCharge = new ShipmentChargeType();
                BillShipperType    billShipper   = new BillShipperType();
                billShipper.AccountNumber = hfAccountNumber.Value;
                shpmentCharge.BillShipper = billShipper;
                shpmentCharge.Type        = lblChargeType.Text.Trim();
                ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
                paymentInfo.ShipmentCharge  = shpmentChargeArray;
                shipment.PaymentInformation = paymentInfo;
                UPSShipWebReference.ShipAddressType shipperAddress = new UPSShipWebReference.ShipAddressType();

                String[] addressLine = { lblFromStreet.Text.Trim() };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = lblFromCity.Text.Trim();
                shipperAddress.PostalCode        = lblFromZip.Text.Trim();
                shipperAddress.StateProvinceCode = hfFromStateUPSCode.Value;
                shipperAddress.CountryCode       = hfFromCountryUPSCode.Value;
                shipperAddress.AddressLine       = addressLine;
                shipper.Address       = shipperAddress;
                shipper.Name          = lblFromName.Text.Trim();
                shipper.AttentionName = lblFromName.Text.Trim();
                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = lblFromPhone.Text.Trim();
                shipper.Phone       = shipperPhone;
                shipment.Shipper    = shipper;

                ShipFromType shipFrom = new ShipFromType();
                UPSShipWebReference.ShipAddressType shipFromAddress = new UPSShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { lblFromStreet.Text.Trim() };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = lblFromCity.Text.Trim();
                shipFromAddress.PostalCode        = lblFromZip.Text.Trim();
                shipFromAddress.StateProvinceCode = hfFromStateUPSCode.Value;
                shipFromAddress.CountryCode       = hfFromCountryUPSCode.Value;
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = lblFromName.Text.Trim();
                shipFrom.Name          = lblFromName.Text.Trim();
                shipment.ShipFrom      = shipFrom;

                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { lblToStreet.Text.Trim() };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = lblToCity.Text.Trim();
                shipToAddress.PostalCode        = lblToZip.Text.Trim();
                shipToAddress.StateProvinceCode = hfToStateUPSCode.Value;
                shipToAddress.CountryCode       = hfToCountryUPSCode.Value;
                shipTo.Address       = shipToAddress;
                shipTo.AttentionName = lblToName.Text.Trim();
                shipTo.Name          = lblToName.Text.Trim();
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = lblToPhone.Text.Trim();
                shipTo.Phone       = shipToPhone;
                shipment.ShipTo    = shipTo;

                ServiceType service = new ServiceType();
                service.Code     = lblShipService.Text.Trim();
                shipment.Service = service;
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = lblWeight.Text.Trim();
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = lblMeasurementType.Text.Trim();
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = lblPackagingType.Text.Trim();
                package.Packaging = packType;
                PackageType[] pkgArray = { package };
                shipment.Package = pkgArray;
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "6";
                labelStockSize.Width     = "4";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                labelImageFormat.Code              = "GIF";
                labelSpec.LabelImageFormat         = labelImageFormat;
                shipmentRequest.LabelSpecification = labelSpec;
                shipmentRequest.Shipment           = shipment;
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

                ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);

                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                //Output to File
                string localPath = Server.MapPath("../Labels") + "\\" + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".pdf";
                PdfWriter.GetInstance(doc, new FileStream(localPath, FileMode.Create));
                doc.Open();
                Byte[]       labelBuffer = System.Convert.FromBase64String(shipmentResponse.ShipmentResults.PackageResults[0].ShippingLabel.GraphicImage);
                MemoryStream stream      = new MemoryStream(labelBuffer);

                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(stream);
                gif.RotationDegrees = -90f;
                gif.ScalePercent(50f);
                stream.Close();
                doc.NewPage();
                doc.Add(gif);
                doc.Close();

                MemoryStream output = new MemoryStream();
                doc = new iTextSharp.text.Document();
                PdfWriter.GetInstance(doc, output);
                doc.Open();
                doc.NewPage();
                doc.Add(gif);
                doc.Close();


                (new OrderEntryDAL()).UploadShippingLabel_DAL("Shipping Label", output.ToArray(), "application/pdf", shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".pdf", "", labelBuffer.Length, int.Parse(hfOrderId.Value), int.Parse(Session["UserID"].ToString()));

                output.Close();
                return(shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                lblErr.Text = ex.Message;
                MPEPrepare.Show();
                return("");
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
                MPEPrepare.Show();
                return("");
            }
        }
        // # DoExpressCheckoutPayment API Operation
        // The DoExpressCheckoutPayment API operation completes an Express Checkout transaction.
        // If you set up a billing agreement in your SetExpressCheckout API call,
        // the billing agreement is created when you call the DoExpressCheckoutPayment API operation.
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPaymentAPIOperation()
        {
            // Create the DoExpressCheckoutPaymentResponseType object
            DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType =
                new DoExpressCheckoutPaymentResponseType();

            try
            {
                // Create the DoExpressCheckoutPaymentReq object
                DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();

                DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails =
                    new DoExpressCheckoutPaymentRequestDetailsType();

                // The timestamped token value that was returned in the
                // `SetExpressCheckout` response and passed in the
                // `GetExpressCheckoutDetails` request.
                doExpressCheckoutPaymentRequestDetails.Token = "EC-3PG29673CT337061M";

                // Unique paypal buyer account identification number as returned in
                // `GetExpressCheckoutDetails` Response
                doExpressCheckoutPaymentRequestDetails.PayerID = "WJ3Q38FZ9FDYS";

                // # Payment Information
                // list of information about the payment
                List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

                // information about the first payment
                PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

                // Total cost of the transaction to the buyer. If shipping cost and tax
                // charges are known, include them in this value. If not, this value
                // should be the current sub-total of the order.
                //
                // If the transaction includes one or more one-time purchases, this field must be equal to
                // the sum of the purchases. Set this field to 0 if the transaction does
                // not include a one-time purchase such as when you set up a billing
                // agreement for a recurring payment that is not immediately charged.
                // When the field is set to 0, purchase-specific fields are ignored.
                //
                // * `Currency Code` - You must set the currencyID attribute to one of the
                // 3-character currency codes for any of the supported PayPal
                // currencies.
                // * `Amount`
                BasicAmountType orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00");
                paymentDetails1.OrderTotal = orderTotal1;

                // How you want to obtain payment. When implementing parallel payments,
                // this field is required and must be set to `Order`. When implementing
                // digital goods, this field is required and must be set to `Sale`. If the
                // transaction does not include a one-time purchase, this field is
                // ignored. It is one of the following values:
                //
                // * `Sale` - This is a final sale for which you are requesting payment
                // (default).
                // * `Authorization` - This payment is a basic authorization subject to
                // settlement with PayPal Authorization and Capture.
                // * `Order` - This payment is an order authorization subject to
                // settlement with PayPal Authorization and Capture.
                // Note:
                // You cannot set this field to Sale in SetExpressCheckout request and
                // then change the value to Authorization or Order in the
                // DoExpressCheckoutPayment request. If you set the field to
                // Authorization or Order in SetExpressCheckout, you may set the field
                // to Sale.
                paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                SellerDetailsType sellerDetails1 = new SellerDetailsType();
                sellerDetails1.PayPalAccountID = "*****@*****.**";
                paymentDetails1.SellerDetails  = sellerDetails1;

                // A unique identifier of the specific payment request, which is
                // required for parallel payments.
                paymentDetails1.PaymentRequestID = "PaymentRequest1";

                // information about the second payment
                PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
                // Total cost of the transaction to the buyer. If shipping cost and tax
                // charges are known, include them in this value. If not, this value
                // should be the current sub-total of the order.
                //
                // If the transaction includes one or more one-time purchases, this field must be equal to
                // the sum of the purchases. Set this field to 0 if the transaction does
                // not include a one-time purchase such as when you set up a billing
                // agreement for a recurring payment that is not immediately charged.
                // When the field is set to 0, purchase-specific fields are ignored.
                //
                // * `Currency Code` - You must set the currencyID attribute to one of the
                // 3-character currency codes for any of the supported PayPal
                // currencies.
                // * `Amount`
                BasicAmountType orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00");
                paymentDetails2.OrderTotal = orderTotal2;

                // How you want to obtain payment. When implementing parallel payments,
                // this field is required and must be set to `Order`. When implementing
                // digital goods, this field is required and must be set to `Sale`. If the
                // transaction does not include a one-time purchase, this field is
                // ignored. It is one of the following values:
                //
                // * `Sale` - This is a final sale for which you are requesting payment
                // (default).
                // * `Authorization` - This payment is a basic authorization subject to
                // settlement with PayPal Authorization and Capture.
                // * `Order` - This payment is an order authorization subject to
                // settlement with PayPal Authorization and Capture.
                // `Note:
                // You cannot set this field to Sale in SetExpressCheckout request and
                // then change the value to Authorization or Order in the
                // DoExpressCheckoutPayment request. If you set the field to
                // Authorization or Order in SetExpressCheckout, you may set the field
                // to Sale.`
                paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                SellerDetailsType sellerDetails2 = new SellerDetailsType();
                sellerDetails2.PayPalAccountID = "*****@*****.**";
                paymentDetails2.SellerDetails  = sellerDetails2;

                // A unique identifier of the specific payment request, which is
                // required for parallel payments.
                paymentDetails2.PaymentRequestID = "PaymentRequest2";
                paymentDetailsList.Add(paymentDetails1);
                paymentDetailsList.Add(paymentDetails2);
                doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

                DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest =
                    new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
                doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;

                var config = new Dictionary <string, string>
                {
                    { "mode", "sandbox" },
                    { "account1.apiUsername", "konstantin_merchant_api1.scandiaconsulting.com" },
                    { "account1.apiPassword", "1398157263" },
                    { "account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AlRjlcug7qV.VXWV14E1KtmQPsPL" }
                };

                // Create the service wrapper object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);

                // # API call
                // Invoke the DoExpressCheckoutPayment method in service wrapper object
                responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);

                if (responseDoExpressCheckoutPaymentResponseType != null)
                {
                    // Response envelope acknowledgement
                    string acknowledgement = "DoExpressCheckoutPayment API Operation - ";
                    acknowledgement += responseDoExpressCheckoutPaymentResponseType.Ack.ToString();
                    Console.WriteLine(acknowledgement + "\n");

                    // # Success values
                    if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Transaction identification number of the transaction that was
                        // created.
                        // This field is only returned after a successful transaction
                        // for DoExpressCheckout has occurred.
                        if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                        {
                            IEnumerator <PaymentInfoType> paymentInfoIterator =
                                responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                            while (paymentInfoIterator.MoveNext())
                            {
                                PaymentInfoType paymentInfo = paymentInfoIterator.Current;
                                Console.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n");
                            }
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        }
                    }
                }

                return(responseDoExpressCheckoutPaymentResponseType);
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseDoExpressCheckoutPaymentResponseType);
        }
Exemple #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext CurrContext = HttpContext.Current;

        // Create the DoExpressCheckoutPaymentResponseType object
        DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType();

        try
        {
            // Create the DoExpressCheckoutPaymentReq object
            DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            // The timestamped token value that was returned in the
            // `SetExpressCheckout` response and passed in the
            // `GetExpressCheckoutDetails` request.
            doExpressCheckoutPaymentRequestDetails.Token = (string)(Session["EcToken"]);
            // Unique paypal buyer account identification number as returned in
            // `GetExpressCheckoutDetails` Response
            doExpressCheckoutPaymentRequestDetails.PayerID = (string)(Session["PayerId"]);

            // # Payment Information
            // list of information about the payment
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();
            // information about the payment
            PaymentDetailsType    paymentDetails      = new PaymentDetailsType();
            CurrencyCodeType      currency_code_type  = (CurrencyCodeType)(Session["currency_code_type"]);
            PaymentActionCodeType payment_action_type = (PaymentActionCodeType)(Session["payment_action_type"]);
            //Pass the order total amount which was already set in session
            string          total_amount = (string)(Session["Total_Amount"]);
            BasicAmountType orderTotal   = new BasicAmountType(currency_code_type, total_amount);
            paymentDetails.OrderTotal    = orderTotal;
            paymentDetails.PaymentAction = payment_action_type;

            //BN codes to track all transactions
            paymentDetails.ButtonSource = BNCode;

            // Unique identifier for the merchant.
            SellerDetailsType sellerDetails = new SellerDetailsType();
            sellerDetails.PayPalAccountID = (string)(Session["SellerEmail"]);
            paymentDetails.SellerDetails  = sellerDetails;

            paymentDetailsList.Add(paymentDetails);
            doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

            DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
            doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;
            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            // # API call
            // Invoke the DoExpressCheckoutPayment method in service wrapper object
            responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);
            if (responseDoExpressCheckoutPaymentResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "DoExpressCheckoutPayment API Operation - ";
                acknowledgement += responseDoExpressCheckoutPaymentResponseType.Ack.ToString();
                //logger.Info(acknowledgement + "\n");
                System.Diagnostics.Debug.WriteLine(acknowledgement + "\n");
                // # Success values
                if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Transaction identification number of the transaction that was
                    // created.
                    // This field is only returned after a successful transaction
                    // for DoExpressCheckout has occurred.
                    if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                    {
                        IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                        while (paymentInfoIterator.MoveNext())
                        {
                            PaymentInfoType paymentInfo = paymentInfoIterator.Current;
                            //logger.Info("Transaction ID : " + paymentInfo.TransactionID + "\n");

                            Session["Transaction_Id"]       = paymentInfo.TransactionID;
                            Session["Transaction_Type"]     = paymentInfo.TransactionType;
                            Session["Payment_Status"]       = paymentInfo.PaymentStatus;
                            Session["Payment_Type"]         = paymentInfo.PaymentType;
                            Session["Payment_Total_Amount"] = paymentInfo.GrossAmount.value;

                            System.Diagnostics.Debug.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n");
                        }
                    }
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                    string           errorMessage  = "";
                    foreach (ErrorType error in errorMessages)
                    {
                        //logger.Debug("API Error Message : " + error.LongMessage);
                        System.Diagnostics.Debug.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        errorMessage = errorMessage + error.LongMessage;
                    }
                    //Redirect to error page in case of any API errors
                    CurrContext.Items.Add("APIErrorMessage", errorMessage);
                    Server.Transfer("~/Response.aspx");
                }
            }
        }
        catch (System.Exception ex)
        {
            // Log the exception message
            //logger.Debug("Error Message : " + ex.Message);
            System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message);
        }
    }
Exemple #9
0
        static void Main()
        {
            try
            {
                ShipService     shpSvc          = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();
                UPSSecurity     upss            = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "Your Access License";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = "******";
                upssUsrNameToken.Password = "******";
                upss.UsernameToken        = upssUsrNameToken;
                shpSvc.UPSSecurityValue   = upss;
                RequestType request       = new RequestType();
                String[]    requestOption = { "nonvalidate" };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;
                ShipmentType shipment = new ShipmentType();
                shipment.Description = "Ship webservice example";
                ShipperType shipper = new ShipperType();
                shipper.ShipperNumber = "Your Shipper Number";
                PaymentInfoType    paymentInfo   = new PaymentInfoType();
                ShipmentChargeType shpmentCharge = new ShipmentChargeType();
                BillShipperType    billShipper   = new BillShipperType();
                billShipper.AccountNumber = "Your Account Number";
                shpmentCharge.BillShipper = billShipper;
                shpmentCharge.Type        = "01";
                ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
                paymentInfo.ShipmentCharge  = shpmentChargeArray;
                shipment.PaymentInformation = paymentInfo;
                ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] addressLine = { "480 Parkton Plaza" };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = "Timonium";
                shipperAddress.PostalCode        = "21093";
                shipperAddress.StateProvinceCode = "MD";
                shipperAddress.CountryCode       = "US";
                shipperAddress.AddressLine       = addressLine;
                shipper.Address       = shipperAddress;
                shipper.Name          = "ABC Associates";
                shipper.AttentionName = "ABC Associates";
                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = "1234567890";
                shipper.Phone       = shipperPhone;
                shipment.Shipper    = shipper;
                ShipFromType shipFrom = new ShipFromType();
                ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { "Ship From Street" };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = "Timonium";
                shipFromAddress.PostalCode        = "21093";
                shipFromAddress.StateProvinceCode = "MD";
                shipFromAddress.CountryCode       = "US";
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = "Mr.ABC";
                shipFrom.Name          = "ABC Associates";
                shipment.ShipFrom      = shipFrom;
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { "GOERLITZER STR.1" };
                shipToAddress.AddressLine = addressLine1;
                shipToAddress.City        = "Neuss";
                shipToAddress.PostalCode  = "41456";
                shipToAddress.CountryCode = "DE";
                shipTo.Address            = shipToAddress;
                shipTo.AttentionName      = "DEF";
                shipTo.Name = "DEF Associates";
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = "1234567890";
                shipTo.Phone       = shipToPhone;
                shipment.ShipTo    = shipTo;
                ServiceType service = new ServiceType();
                service.Code     = "08";
                shipment.Service = service;

                ShipmentTypeShipmentServiceOptions shpServiceOptions = new ShipmentTypeShipmentServiceOptions();

                /** **** International Forms ***** */
                InternationalFormType internationalForms = new InternationalFormType();

                /** **** Commercial Invoice ***** */
                String[] formTypeList = { "01" };
                internationalForms.FormType = formTypeList;

                /** **** Contacts and Sold To ***** */
                ContactType contacts = new ContactType();

                SoldToType soldTo = new SoldToType();
                soldTo.Option        = "1";
                soldTo.AttentionName = "Sold To Attn Name";
                soldTo.Name          = "Sold To Name";
                PhoneType soldToPhone = new PhoneType();
                soldToPhone.Number    = "1234567890";
                soldToPhone.Extension = "1234";
                soldTo.Phone          = soldToPhone;
                AddressType soldToAddress     = new AddressType();
                String[]    soldToAddressLine = { "34 Queen St" };
                soldToAddress.AddressLine = soldToAddressLine;
                soldToAddress.City        = "Frankfurt";
                soldToAddress.PostalCode  = "60547";
                soldToAddress.CountryCode = "DE";
                soldTo.Address            = soldToAddress;
                contacts.SoldTo           = soldTo;

                internationalForms.Contacts = contacts;

                /** **** Product ***** */
                ProductType product1    = new ProductType();
                String[]    description = { "Product 1" };
                product1.Description       = description;
                product1.CommodityCode     = "111222AA";
                product1.OriginCountryCode = "US";
                UnitType unit = new UnitType();
                unit.Number = "147";
                unit.Value  = "478";
                UnitOfMeasurementType uomProduct = new UnitOfMeasurementType();
                uomProduct.Code        = "BOX";
                uomProduct.Description = "BOX";
                unit.UnitOfMeasurement = uomProduct;
                product1.Unit          = unit;
                ProductWeightType productWeight = new ProductWeightType();
                productWeight.Weight = "10";
                UnitOfMeasurementType uomForWeight = new UnitOfMeasurementType();
                uomForWeight.Code               = "LBS";
                uomForWeight.Description        = "LBS";
                productWeight.UnitOfMeasurement = uomForWeight;
                product1.ProductWeight          = productWeight;
                ProductType[] productList = { product1 };
                internationalForms.Product = productList;

                /** **** InvoiceNumber, InvoiceDate, PurchaseOrderNumber, TermsOfShipment, ReasonForExport, Comments and DeclarationStatement  ***** */
                internationalForms.InvoiceNumber        = "asdf123";
                internationalForms.InvoiceDate          = "20151225";
                internationalForms.PurchaseOrderNumber  = "999jjj777";
                internationalForms.TermsOfShipment      = "CFR";
                internationalForms.ReasonForExport      = "Sale";
                internationalForms.Comments             = "Your Comments";
                internationalForms.DeclarationStatement = "Your Declaration Statement";

                /** **** Discount, FreightCharges, InsuranceCharges, OtherCharges and CurrencyCode  ***** */
                IFChargesType discount = new IFChargesType();
                discount.MonetaryValue      = "100";
                internationalForms.Discount = discount;
                IFChargesType freight = new IFChargesType();
                freight.MonetaryValue             = "50";
                internationalForms.FreightCharges = freight;
                IFChargesType insurance = new IFChargesType();
                insurance.MonetaryValue             = "200";
                internationalForms.InsuranceCharges = insurance;
                OtherChargesType otherCharges = new OtherChargesType();
                otherCharges.MonetaryValue      = "50";
                otherCharges.Description        = "Misc";
                internationalForms.OtherCharges = otherCharges;
                internationalForms.CurrencyCode = "USD";


                shpServiceOptions.InternationalForms = internationalForms;
                shipment.ShipmentServiceOptions      = shpServiceOptions;

                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = "10";
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = "LBS";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = "02";
                package.Packaging = packType;
                PackageType[] pkgArray = { package };
                shipment.Package = pkgArray;
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "6";
                labelStockSize.Width     = "4";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                labelImageFormat.Code              = "GIF";
                labelSpec.LabelImageFormat         = labelImageFormat;
                shipmentRequest.LabelSpecification = labelSpec;
                shipmentRequest.Shipment           = shipment;
                Console.WriteLine(shipmentRequest);
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
                ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
                Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
                Console.WriteLine("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Ship Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" General Exception= " + ex.Message);
                Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Exemple #10
0
        /// <summary>
        /// Charges the specified payment info.
        /// </summary>
        /// <param name="financialGateway">The financial gateway.</param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Charge(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (!(paymentInfo is PayPalExpress.PayPalPaymentInfo))
            {
                errorMessage = "PaymentInfo object must be of type PayPalPaymentInfo in order to charge a PayPal Express transaction.";
                return(null);
            }
            PayPalPaymentInfo payPalPaymentInfo = (PayPalPaymentInfo)paymentInfo;

            // Create the DoExpressCheckoutPaymentResponseType object
            DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType();

            try
            {
                // Create the DoExpressCheckoutPaymentReq object
                DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();

                DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

                // The timestamped token value that was returned in the
                // `SetExpressCheckout` response and passed in the
                // `GetExpressCheckoutDetails` request.
                doExpressCheckoutPaymentRequestDetails.Token = payPalPaymentInfo.Token;

                // Unique paypal buyer account identification number as returned in
                // `GetExpressCheckoutDetails` Response
                doExpressCheckoutPaymentRequestDetails.PayerID = payPalPaymentInfo.PayerId;

                // # Payment Information
                // list of information about the payment
                List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

                // information about the first payment
                PaymentDetailsType paymentDetails = new PaymentDetailsType();

                BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, paymentInfo.Amount.ToString());
                paymentDetails.OrderTotal = orderTotal;

                // We are actually capturing this payment now.
                paymentDetails.PaymentAction = PaymentActionCodeType.SALE;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                String            apiUsername   = Encryption.DecryptString(financialGateway.GetAttributeValue("PayPalAPIUsername"));
                SellerDetailsType sellerDetails = new SellerDetailsType();
                sellerDetails.PayPalAccountID = apiUsername;

                paymentDetailsList.Add(paymentDetails);
                doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

                DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
                doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;

                // Create the service wrapper object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(GetCredentials(financialGateway));

                // # API call
                // Invoke the DoExpressCheckoutPayment method in service wrapper object
                responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);

                if (responseDoExpressCheckoutPaymentResponseType != null)
                {
                    // # Success values
                    if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Transaction identification number of the transaction that was
                        // created.
                        // This field is only returned after a successful transaction
                        // for DoExpressCheckout has occurred.
                        if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                        {
                            IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                            while (paymentInfoIterator.MoveNext())
                            {
                                PaymentInfoType ppPaymentInfo = paymentInfoIterator.Current;

                                var transaction = new FinancialTransaction();
                                transaction.TransactionCode = ppPaymentInfo.TransactionID;
                                return(transaction);
                            }
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            errorMessage += "API Error Message : " + error.LongMessage + "\n";
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                errorMessage += "Error Message : " + ex.Message;
            }

            return(null);
        }
Exemple #11
0
        public void CreateShipmentRequest()
        {
            try
            {
                ShipService     shipService     = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();

                // Security
                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken
                {
                    AccessLicenseNumber = "1CBF3AD5FB29C105"
                };
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                if (radioButton_PLZFT.Checked == true)
                {
                    upssUsrNameToken.Username = "******";
                    upssUsrNameToken.Password = "******";
                }
                else
                {
                    upssUsrNameToken.Username = "******";   // AAC
                    upssUsrNameToken.Password = "******"; // AAC
                }
                upss.UsernameToken           = upssUsrNameToken;
                shipService.UPSSecurityValue = upss;

                // Request
                RequestType request = new RequestType();
                shipmentRequest.Request = request;

                // Request Option
                String[] requestOption = { "nonvalidate" };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;

                // Shipment
                ShipmentType shipment = new ShipmentType();
                shipment.Description = "Amazon Gift Card";

                // Shipper
                ShipperType shipper = new ShipperType();
                //shipper.ShipperNumber = "9E6741";
                //if (radioButton_PLZFT.Checked == true)
                shipper.ShipperNumber = "9E6741";     // <- gleich dem im AccessToken !?
                //else
                // 9E6741
                //    shipper.ShipperNumber = "9E6741"; // <- gleich dem im AccessToken !?

                // Payment Info
                PaymentInfoType paymentInfo = new PaymentInfoType();


                ShipmentChargeType shipmentCharge = new ShipmentChargeType();
                shipmentCharge.Type = "01";

                //Payment Info -> BillShipper
                BillShipperType billShipper = new BillShipperType();
                //billShipper.AccountNumber = "9E6741";
                billShipper.AccountNumber  = "587997";
                shipmentCharge.BillShipper = billShipper;


                ShipmentChargeType shipmentCharge2 = new ShipmentChargeType();
                shipmentCharge2.Type = "02";

                // Payment Info -> BillReceiver
                BillReceiverType billReceiver = new BillReceiverType();
                billReceiver.AccountNumber   = "9E6741";
                shipmentCharge2.BillReceiver = billReceiver;

                // Payment Info -> Bill3rdParty
                //BillThirdPartyChargeType bill3rdParty = new BillThirdPartyChargeType();
                //bill3rdParty.AccountNumber = "9E6741";
                //AccountAddressType thirdPartyAddress = new AccountAddressType
                //{
                //    PostalCode = "94032",
                //    CountryCode = "DE"
                //};
                //bill3rdParty.Address = thirdPartyAddress;
                //shipmentCharge2.BillThirdParty = bill3rdParty;



                ShipmentChargeType[] shpmentChargeArray = { shipmentCharge, shipmentCharge2 };
                //ShipmentChargeType[] shpmentChargeArray = { shipmentCharge2 };
                //ShipmentChargeType[] shpmentChargeArray = { shipmentCharge2 };
                paymentInfo.ShipmentCharge = shpmentChargeArray;


                // Shipment -> Payment Information
                shipment.PaymentInformation = paymentInfo;

                // Shipper
                UPS_API.ShipWebReference.ShipAddressType shipperAddress = new UPS_API.ShipWebReference.ShipAddressType();
                String[] addressLine = { textBox_Shipper_AddressLine.Text };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = textBox_Shipper_City.Text;
                shipperAddress.PostalCode        = textBox_Shipper_PostalCode.Text;
                shipperAddress.StateProvinceCode = textBox_Shipper_StateProvince.Text;
                shipperAddress.CountryCode       = textBox_Shipper_CountryCode.Text;
                shipperAddress.AddressLine       = addressLine;
                shipper.Address       = shipperAddress;
                shipper.Name          = textBox_Shipper_Name.Text;
                shipper.AttentionName = textBox_Shipper_AttentionName.Text;

                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = textBox_Shipper_PhoneNumber.Text;
                shipper.Phone       = shipperPhone;

                // Shipment -> Shipper
                shipment.Shipper = shipper;

                // ShipFrom
                ShipFromType shipFrom = new ShipFromType();
                UPS_API.ShipWebReference.ShipAddressType shipFromAddress = new UPS_API.ShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { textBox_ShipFrom_AddressLine.Text };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = textBox_ShipFrom_City.Text;
                shipFromAddress.PostalCode        = textBox_ShipFrom_PostalCode.Text;
                shipFromAddress.StateProvinceCode = textBox_ShipFrom_StateProvince.Text;
                shipFromAddress.CountryCode       = textBox_ShipFrom_CountryCode.Text;
                shipFrom.Address       = shipFromAddress;
                shipFrom.Name          = textBox_ShipFrom_Name.Text;
                shipFrom.AttentionName = textBox_ShipFrom_AttentionName.Text;
                ShipPhoneType shipFromPhone = new ShipPhoneType();
                shipFromPhone.Number = textBox_ShipFrom_PhoneNumber.Text;
                shipFrom.Phone       = shipFromPhone;

                // Shipment -> ShipFrom
                shipment.ShipFrom = shipFrom;

                // ShipTo
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { textBox_ShipTo_AddressLine1.Text };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = textBox_ShipTo_City.Text;
                shipToAddress.PostalCode        = textBox_ShipTo_PostalCode.Text;
                shipToAddress.StateProvinceCode = textBox_ShipTo_StateProvince.Text;
                shipToAddress.CountryCode       = textBox_ShiptTo_CountryCode.Text;
                shipTo.Address       = shipToAddress;
                shipTo.Name          = textBox_ShipTo_Name.Text;
                shipTo.AttentionName = textBox_ShipTo_AttentionName.Text;
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = textBox_ShipTo_PhoneNumber.Text;
                shipTo.Phone       = shipToPhone;

                // Shipment -> ShipTo
                shipment.ShipTo = shipTo;

                // Services
                ServiceType service = new ServiceType();
                service.Code = "11";

                //ShipmentServiceOptionsType shipmentServiceOptions = new ShipmentServiceOptionsType();


                // Shipment -> Services
                shipment.Service = service;

                // Package
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = textBox_Package_Weight.Text;
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = textBox_Package_MeasurementCode.Text;
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = textBox_Package_TypeCode.Text;
                package.Packaging = packType;
                PackageType[] pkgArray = { package };

                // Shipment -> Package
                shipment.Package = pkgArray;

                // Label
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "6";
                labelStockSize.Width     = "4";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                labelImageFormat.Code      = "PNG";
                labelSpec.LabelImageFormat = labelImageFormat;

                // Shipment Request -> Label
                shipmentRequest.LabelSpecification = labelSpec;

                // Shipment Request -> Shipment
                shipmentRequest.Shipment = shipment;

                // Request -> Execute
                richTextBox1.Text += shipmentRequest + "\r\n";
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; //This line will ensure the latest security protocol for consuming the web service call.
                ShipmentResponse shipmentResponse = shipService.ProcessShipment(shipmentRequest);

                string shipmentIdentificationNumber = shipmentResponse.ShipmentResults.ShipmentIdentificationNumber;

                richTextBox1.Text += "The transaction was a " + shipmentResponse.Response.ResponseStatus.Description + "\r\n";
                richTextBox1.Text += "The 1Z number of the new shipment is " + shipmentIdentificationNumber + "\r\n";
                textBox_ShipmentIdentificationNumber.Text = shipmentIdentificationNumber;

                // Save label as PNG
                string base64Label = shipmentResponse.ShipmentResults.PackageResults[0].ShippingLabel.GraphicImage;
                byte[] data        = Convert.FromBase64String(base64Label);
                using (var stream = new MemoryStream(data, 0, data.Length))
                {
                    Image imageLabel = Image.FromStream(stream);
                    pictureBox_Label.Image = imageLabel;
                    pictureBox_Label.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    imageLabel.Save(Path.Combine(@Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ups_" + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber + ".png"));
                }

                textBox_ErrorLog.ForeColor = Color.LimeGreen;
                textBox_ErrorLog.Text      = "OK";
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                textBox_ErrorLog.ForeColor = Color.Salmon;
                textBox_ErrorLog.Text      = ex.Detail.LastChild.InnerText;

                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "---------Ship Web Service returns error----------------\r\n";
                richTextBox1.Text += "---------\"Hard\" is user error \"Transient\" is system error----------------\r\n";
                richTextBox1.Text += "SoapException Message= " + ex.Message;
                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText;
                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "SoapException XML String for all= " + ex.Detail.LastChild.OuterXml;
                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "SoapException StackTrace= " + ex.StackTrace;
                richTextBox1.Text += "-------------------------\r\n";
                richTextBox1.Text += "\r\n";
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                textBox_ErrorLog.ForeColor = Color.Salmon;
                textBox_ErrorLog.Text      = ex.Message;

                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "--------------------\r\n";
                richTextBox1.Text += "CommunicationException= " + ex.Message;
                richTextBox1.Text += "CommunicationException-StackTrace= " + ex.StackTrace;
                richTextBox1.Text += "-------------------------\r\n";
                richTextBox1.Text += "\r\n";
            }
            catch (Exception ex)
            {
                textBox_ErrorLog.ForeColor = Color.Salmon;
                textBox_ErrorLog.Text      = ex.Message;

                richTextBox1.Text += "\r\n";
                richTextBox1.Text += "-------------------------\r\n";
                richTextBox1.Text += " General Exception= " + ex.Message;
                richTextBox1.Text += " General Exception-StackTrace= " + ex.StackTrace;
                richTextBox1.Text += "-------------------------\r\n";
            }
            finally
            {
            }
        }
Exemple #12
0
        private static void ScheduleShipment()
        {
            try
            {
                ShipService     shpSvc          = new ShipService();
                ShipmentRequest shipmentRequest = new ShipmentRequest();


                // security
                UPSSecurity upss = new UPSSecurity();
                UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                upssSvcAccessToken.AccessLicenseNumber = "4CF6E9703C30E4B6";
                upss.ServiceAccessToken = upssSvcAccessToken;
                UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                upssUsrNameToken.Username = "******";
                upssUsrNameToken.Password = "******";
                upss.UsernameToken        = upssUsrNameToken;
                shpSvc.UPSSecurityValue   = upss;

                RequestType request       = new RequestType();
                String[]    requestOption = { "nonvalidate" };
                request.RequestOption   = requestOption;
                shipmentRequest.Request = request;

                ShipmentType shipment = new ShipmentType();
                shipment.Description = "New shipment ...";

                // payment
                PaymentInfoType    paymentInfo   = new PaymentInfoType();
                ShipmentChargeType shpmentCharge = new ShipmentChargeType();
                BillShipperType    billShipper   = new BillShipperType();
                billShipper.AccountNumber = "1YA077";
                shpmentCharge.BillShipper = billShipper;
                shpmentCharge.Type        = "01";
                ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
                paymentInfo.ShipmentCharge  = shpmentChargeArray;
                shipment.PaymentInformation = paymentInfo;

                // shipper
                ShipperType shipper = new ShipperType();
                shipper.ShipperNumber = "1YA077";
                ShipWSSample.ShipWebReference.ShipAddressType shipperAddress =
                    new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] addressLine = { "88 Foster Crescent" };
                shipperAddress.AddressLine       = addressLine;
                shipperAddress.City              = "Mississauga";
                shipperAddress.PostalCode        = "L5R4A2";
                shipperAddress.StateProvinceCode = "ON";
                shipperAddress.CountryCode       = "CA";
                shipper.Address       = shipperAddress;
                shipper.Name          = "CATO";
                shipper.AttentionName = "Ingram Micro - Mississauga";
                ShipPhoneType shipperPhone = new ShipPhoneType();
                shipperPhone.Number = "1234567890";
                shipper.Phone       = shipperPhone;
                shipment.Shipper    = shipper;

                // ship from
                ShipFromType shipFrom = new ShipFromType();
                ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress =
                    new ShipWSSample.ShipWebReference.ShipAddressType();
                String[] shipFromAddressLine = { "135 Liberty St. Suite 101" };
                shipFromAddress.AddressLine       = addressLine;
                shipFromAddress.City              = "Toronto";
                shipFromAddress.PostalCode        = "M6K1A7";
                shipFromAddress.StateProvinceCode = "ON";
                shipFromAddress.CountryCode       = "CA";
                shipFrom.Address       = shipFromAddress;
                shipFrom.AttentionName = "Mr. Andy Feng";
                shipFrom.Name          = "Kobo Inc.";
                shipment.ShipFrom      = shipFrom;

                // ship to
                ShipToType        shipTo        = new ShipToType();
                ShipToAddressType shipToAddress = new ShipToAddressType();
                String[]          addressLine1  = { "403 Burr Oak Drive" };
                shipToAddress.AddressLine       = addressLine1;
                shipToAddress.City              = "Oswego";
                shipToAddress.PostalCode        = "60543";
                shipToAddress.StateProvinceCode = "IL";
                shipToAddress.CountryCode       = "US";
                shipTo.Address       = shipToAddress;
                shipTo.AttentionName = "Mr. John Smith";
                shipTo.Name          = "DEF Associates";
                ShipPhoneType shipToPhone = new ShipPhoneType();
                shipToPhone.Number = "(905) 123-1234";
                shipTo.Phone       = shipToPhone;
                shipment.ShipTo    = shipTo;

                //service
                ServiceType service = new ServiceType();
                //service.Code = "01"; // next day air
                service.Code     = "11";//ups standard
                shipment.Service = service;


                // package
                PackageType       package       = new PackageType();
                PackageWeightType packageWeight = new PackageWeightType();
                packageWeight.Weight = "10";
                ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
                uom.Code = "LBS";
                packageWeight.UnitOfMeasurement = uom;
                package.PackageWeight           = packageWeight;
                PackagingType packType = new PackagingType();
                packType.Code     = "02";
                package.Packaging = packType;
                // package 2
                PackageType       package2       = new PackageType();
                PackageWeightType packageWeight2 = new PackageWeightType();
                packageWeight2.Weight = "9";
                ShipUnitOfMeasurementType uom2 = new ShipUnitOfMeasurementType();
                uom2.Code = "LBS";
                packageWeight2.UnitOfMeasurement = uom2;
                package2.PackageWeight           = packageWeight2;
                PackagingType packType2 = new PackagingType();
                packType2.Code     = "02";
                package2.Packaging = packType2;

                PackageType[] pkgArray = { package, package2 };
                shipment.Package = pkgArray;

                // add delivery confirmation for package level
                //PackageServiceOptionsType packageServiceOptions = new PackageServiceOptionsType();
                //package.PackageServiceOptions = packageServiceOptions;
                //package2.PackageServiceOptions = packageServiceOptions;
                //DeliveryConfirmationType deliveryConfirmation = new DeliveryConfirmationType();
                ////Service DCIS Type, The type of confirmation required upon delivery of the package.
                //deliveryConfirmation.DCISType = "2"; //Delivery Confirmation Signature Required
                //// The delivery confirmation control number that confirms the package's delivery.
                ////deliveryConfirmation.DCISNumber = "xxxxxxxx";
                //packageServiceOptions.DeliveryConfirmation = deliveryConfirmation;

                // label
                LabelSpecificationType labelSpec      = new LabelSpecificationType();
                LabelStockSizeType     labelStockSize = new LabelStockSizeType();
                labelStockSize.Height    = "1";
                labelStockSize.Width     = "1";
                labelSpec.LabelStockSize = labelStockSize;
                LabelImageFormatType labelImageFormat = new LabelImageFormatType();
                //// for zpl
                //labelStockSize.Height = "6";
                //labelStockSize.Width = "4";
                //labelImageFormat.Code = "ZPL";
                // for gif
                labelImageFormat.Code              = "GIF";
                labelSpec.LabelImageFormat         = labelImageFormat;
                shipmentRequest.LabelSpecification = labelSpec;

                shipmentRequest.Shipment = shipment;

                // label
                ShipmentTypeShipmentServiceOptions options = new ShipmentTypeShipmentServiceOptions();
                //options.LabelDelivery = new LabelDeliveryType();
                shipment.ShipmentServiceOptions = options;

                // international form for paperless invoice
                InternationalFormType internationalForm = new InternationalFormType();
                internationalForm.AdditionalDocumentIndicator = null;
                internationalForm.ReasonForExport             = "SALE";
                internationalForm.ExportDate       = DateTime.Now.ToString("yyyyMMdd");
                internationalForm.ExportingCarrier = "UPS";
                internationalForm.InvoiceDate      = DateTime.Now.ToString("yyyyMMdd");
                internationalForm.CurrencyCode     = "CAD";
                internationalForm.FormType         = new String[] { "01" };
                internationalForm.Contacts         = new ContactType()
                {
                    SoldTo = new SoldToType()
                    {
                        Name    = "andy",
                        Address = new AddressType()
                        {
                            AddressLine = new String[] { "box 40" }, City = "Tornnn", CountryCode = "US", PostalCode = "M1S2S5", StateProvinceCode = "ON"
                        }
                    }
                };

                internationalForm.Product = new ProductType[]
                {
                    new ProductType()
                    {
                        ProducerInfo = "product1", Description = new String[] { "1233" }, Unit = new UnitType()
                        {
                            Number = "1", UnitOfMeasurement = new UnitOfMeasurementType()
                            {
                                Code = "BG"
                            }, Value = "1"
                        }, OriginCountryCode = "CA", CommodityCode = "123456", NumberOfPackagesPerCommodity = "1", ProductWeight = new ProductWeightType()
                        {
                            UnitOfMeasurement = new UnitOfMeasurementType()
                            {
                                Code = "LBS"
                            }, Weight = "12"
                        }
                    }
                };
                options.InternationalForms = internationalForm;
                // delivery confirmation for shipment level
                DeliveryConfirmationType deliveryConfirmation = new DeliveryConfirmationType();
                deliveryConfirmation.DCISType = "2";
                options.DeliveryConfirmation  = deliveryConfirmation;

                Console.WriteLine(shipmentRequest);
                System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

                // response
                ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);

                Console.WriteLine("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);

                // output label base64 characters
                string byteFileName = @"c:\Users\afeng\Pictures\label.txt";
                using (FileStream fs = new FileStream(byteFileName, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (BinaryWriter sw = new BinaryWriter(fs))
                    {
                        sw.Write(shipmentResponse.ShipmentResults.PackageResults.FirstOrDefault().ShippingLabel.GraphicImage);
                    }
                }

                // output label image
                string filename = @"c:\Users\afeng\Pictures\label.gif";
                byte[] byteLabel;

                using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (BinaryWriter writer = new BinaryWriter(fs))
                    {
                        byteLabel =
                            Convert.FromBase64String(
                                shipmentResponse.ShipmentResults.PackageResults.FirstOrDefault().ShippingLabel.GraphicImage);
                        writer.Write(byteLabel);
                    }
                }


                // output label html page
                string htmlFilename = @"c:\Users\afeng\Pictures\label.html";
                byte[] htmlByteLabel;

                using (FileStream fs = new FileStream(htmlFilename, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (BinaryWriter writer = new BinaryWriter(fs))
                    {
                        htmlByteLabel =
                            Convert.FromBase64String(
                                shipmentResponse.ShipmentResults.PackageResults.FirstOrDefault().ShippingLabel.HTMLImage);
                        writer.Write(htmlByteLabel);
                    }
                }

                // binary serialize
                Stream          stream     = File.Open(@"c:\Users\afeng\Pictures\data.dat", FileMode.Create);
                BinaryFormatter bformatter = new BinaryFormatter();
                Console.WriteLine("Writing binary serialize Information");
                bformatter.Serialize(stream, shipmentResponse);
                stream.Close();

                // xml serialize
                Stream        requetStream      = File.Open(@"c:\Users\afeng\Pictures\request.xml", FileMode.Create);
                XmlSerializer requestSerializer = new XmlSerializer(shipment.GetType());
                Console.WriteLine("Writing xml serialize Information");
                requestSerializer.Serialize(requetStream, shipment);
                requetStream.Close();
                Stream        responseStream = File.Open(@"c:\Users\afeng\Pictures\response.xml", FileMode.Create);
                XmlSerializer serializer     = new XmlSerializer(shipmentResponse.GetType());
                Console.WriteLine("Writing xml serialize Information");
                serializer.Serialize(responseStream, shipmentResponse);
                responseStream.Close();

                // resize picture
                int width  = (int)(8.25 * 72);
                int height = (int)(4.25 * 72);

                // resize picture 1
                Bitmap imgIn  = new Bitmap(filename);
                double y      = imgIn.Height;
                double x      = imgIn.Width;
                double factor = 1;
                if (width > 0)
                {
                    factor = width / x;
                }
                else if (height > 0)
                {
                    factor = height / y;
                }
                System.IO.MemoryStream outStream = new System.IO.MemoryStream();
                Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));

                // Set DPI of image (xDpi, yDpi)
                //imgOut.SetResolution(72, 72);
                imgOut.SetResolution(96, 96);

                Graphics g = Graphics.FromImage(imgOut);
                g.Clear(Color.White);
                g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)),
                            new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

                imgOut.Save(outStream, ImageFormat.Gif);
                string       filename2 = @"c:\Users\afeng\Pictures\label2.gif";
                FileStream   fs2       = new FileStream(filename2, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter writer2   = new BinaryWriter(fs2);
                writer2.Write(outStream.ToArray());
                writer2.Close();


                // resize picture 2
                //Creates a new Bitmap as the size of the window
                Bitmap bmp = new Bitmap(width, height);
                //Creates a new graphics to handle the image that is coming from the stream
                Graphics g2 = Graphics.FromImage((Image)bmp);
                g2.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                //Resizes the image from the stream to fit our windows
                Bitmap imgIn2 = new Bitmap(filename);
                g2.DrawImage(imgIn2, 0, 0, width, height);
                string                 filename3  = @"c:\Users\afeng\Pictures\label3.gif";
                FileStream             fs3        = new FileStream(filename3, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter           writer3    = new BinaryWriter(fs3);
                System.IO.MemoryStream outStream2 = new System.IO.MemoryStream();
                bmp.Save(outStream2, ImageFormat.Gif);
                writer3.Write(outStream2.ToArray());
                writer3.Close();

                // resize picture 3
                Bitmap newImage = new Bitmap(width, height);
                using (Graphics gr = Graphics.FromImage(newImage))
                {
                    gr.SmoothingMode = SmoothingMode.HighQuality;
                    //gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    gr.InterpolationMode = InterpolationMode.NearestNeighbor;
                    gr.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    gr.DrawImage(new Bitmap(filename), new Rectangle(0, 0, width, height));
                    string     filename4 = @"c:\Users\afeng\Pictures\label4.gif";
                    FileStream fs4       = new FileStream(filename4, FileMode.Create, FileAccess.ReadWrite);
                    //newImage.Save(filename4, System.Drawing.Imaging.ImageFormat.Gif);
                    BinaryWriter           writer4    = new BinaryWriter(fs4);
                    System.IO.MemoryStream outStream4 = new System.IO.MemoryStream();
                    newImage.Save(outStream4, ImageFormat.Gif);
                    writer4.Write(outStream4.ToArray());
                    writer4.Close();
                }

                // resize picture 4
                ImageHandler ih        = new ImageHandler();
                string       filename5 = @"c:\Users\afeng\Pictures\label5.jpg";
                MemoryStream stream5   = new MemoryStream();
                stream5.Write(byteLabel, 0, byteLabel.Length);
                //Bitmap b = new Bitmap(filename);
                Bitmap b = new Bitmap(stream5);
                ih.Save(b, width, height, 100, filename5);


                Console.WriteLine("The 1Z number of the new shipment is " +
                                  shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
                Console.ReadKey();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("---------Ship Web Service returns error----------------");
                Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------");
                Console.WriteLine("SoapException Message= " + ex.Message);
                Console.WriteLine("");
                Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText);
                Console.WriteLine("");
                Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml);
                Console.WriteLine("");
                Console.WriteLine("SoapException StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (System.ServiceModel.CommunicationException ex)
            {
                Console.WriteLine("");
                Console.WriteLine("--------------------");
                Console.WriteLine("CommunicationException= " + ex.Message);
                Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" General Exception= " + ex.Message);
                Console.WriteLine(" General Exception-StackTrace= " + ex.StackTrace);
                Console.WriteLine("-------------------------");
            }
            finally
            {
                Console.ReadKey();
            }
        }
Exemple #13
0
        public string GetTransactionDetail(string transactionID, string delimiter)
        {
            string sReturn = "";
            GetTransactionDetailsRequestType detailRequest = new GetTransactionDetailsRequestType();

            detailRequest.TransactionID = transactionID;
            detailRequest.Version       = PayPalServiceUtility.PayPalAPIVersionNumber;
            GetTransactionDetailsReq request = new GetTransactionDetailsReq();

            request.GetTransactionDetailsRequest = detailRequest;

            GetTransactionDetailsResponseType response = service.GetTransactionDetails(request);

            sReturn = response.Ack.ToString() + "\n";

            string sErrors = this.CheckErrors(response);

            if (sErrors == string.Empty)
            {
                //build out the response
                StringBuilder sb = new StringBuilder();
                sb.Append("************** Payment Information ******************" + delimiter);

                //payment info
                PaymentInfoType payment = response.PaymentTransactionDetails.PaymentInfo;
                sb.Append("ReceiptID: " + payment.ReceiptID + delimiter);
                sb.Append("TransactionID: " + payment.TransactionID + delimiter);
                sb.Append("PaymentDate: " + payment.PaymentDate + delimiter);
                sb.Append("GrossAmount: " + GetAmountValue(payment.GrossAmount) + delimiter);
                sb.Append("SettleAmount: " + GetAmountValue(payment.SettleAmount) + delimiter);
                sb.Append("FeeAmount: " + GetAmountValue(payment.FeeAmount) + delimiter);
                sb.Append("TaxAmount: " + GetAmountValue(payment.TaxAmount) + delimiter);
                sb.Append("PaymentStatus: " + payment.PaymentStatus + delimiter);
                sb.Append("PaymentType: " + payment.PaymentType + delimiter);
                sb.Append("TransactionType: " + payment.TransactionType + delimiter);
                sb.Append(delimiter);
                //sReturn+=response.PaymentTransactionDetails.PaymentInfo.ToString();
                sb.Append("************** Buyer Information ******************" + delimiter);

                //receiver info
                ReceiverInfoType receiver = response.PaymentTransactionDetails.ReceiverInfo;
                sb.Append("Business: " + receiver.Business + delimiter);
                sb.Append("Receiver: " + receiver.Receiver + delimiter);
                sb.Append("ReceiverID: " + receiver.ReceiverID + delimiter);

                /*
                 * --- Uncomment this to report Auction and Subscription info
                 * sb.Append("************** Auction Information ******************"+delimiter);
                 *
                 * AuctionInfoType auction=new AuctionInfoType();
                 * sb.Append("BuyerID: "+auction.BuyerID+delimiter);
                 * sb.Append("ClosingDate: "+auction.ClosingDate+delimiter);
                 * sb.Append("ClosingDateSpecified: "+auction.ClosingDateSpecified+delimiter);
                 * sb.Append("multiItem: "+auction.multiItem+delimiter);
                 *
                 * sb.Append("************** Subscription Information ******************"+delimiter);
                 *
                 * SubscriptionInfoType sub=new SubscriptionInfoType();
                 *
                 * sb.Append("EffectiveDate: "+sub.EffectiveDate+delimiter);
                 * sb.Append("EffectiveDateSpecified: "+sub.EffectiveDateSpecified+delimiter);
                 * sb.Append("Password: "******"reattempt: "+sub.reattempt+delimiter);
                 * sb.Append("Recurrences: "+sub.Recurrences+delimiter);
                 * sb.Append("recurring: "+sub.recurring+delimiter);
                 * sb.Append("RetryTime: "+sub.RetryTime+delimiter);
                 * sb.Append("RetryTimeSpecified: "+sub.RetryTimeSpecified+delimiter);
                 * sb.Append("SubscriptionDate: "+sub.SubscriptionDate+delimiter);
                 * sb.Append("SubscriptionDateSpecified: "+sub.SubscriptionDateSpecified+delimiter);
                 * sb.Append("SubscriptionID: "+sub.SubscriptionID+delimiter);
                 * sb.Append("Terms: "+sub.Terms+delimiter);
                 * sb.Append("Username: "+sub.Username+delimiter);
                 */
                sReturn = sb.ToString();
            }
            else
            {
                sReturn = sErrors;
            }
            return(sReturn);
        }
        public ExpressCheckoutResult DoExpressCheckout()
        {
            HttpContext            context       = HttpContext.Current;
            TraceContext           trace         = context.Trace;
            string                 traceCategory = this.GetType().ToString();
            ExpressCheckoutSession paypalSession = ExpressCheckoutSession.Current;

            if (paypalSession == null)
            {
                //EXIT WITH EXCEPTION
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "SESSION";
                customError.ShortMessage = "Missing Token";
                customError.LongMessage  = "The PayPal session token was expired or unavailable.  Please try again.";
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }
            trace.Write(traceCategory, "Detected PayPal Token:" + paypalSession.Token);
            trace.Write(traceCategory, "Token Expiration:" + paypalSession.TokenExpiration.ToLongDateString());

            if (string.IsNullOrEmpty(paypalSession.PayerID))
            {
                //EXIT WITH EXCEPTION
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "SESSION";
                customError.ShortMessage = "Missing Payer ID";
                customError.LongMessage  = "The PayPal Payer ID is not present.";
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }
            trace.Write(traceCategory, "Detected PayPal Payer ID:" + paypalSession.PayerID);

            //GET THE CURRENCY FOR THE TRANSACTION
            string           storeCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode;
            CurrencyCodeType baseCurrencyCode  = PayPalProvider.GetPayPalCurrencyType(storeCurrencyCode);

            //CREATE THE EXPRESS CHECKOUT
            DoExpressCheckoutPaymentRequestType expressCheckoutRequest = new DoExpressCheckoutPaymentRequestType();

            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails                        = new DoExpressCheckoutPaymentRequestDetailsType();
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.Token                  = paypalSession.Token;
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentAction          = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization;
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentActionSpecified = true;
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PayerID                = paypalSession.PayerID;
            expressCheckoutRequest.Version = "1.0";

            //SET THE ORDER TOTAL AMOUNTS
            Basket basket = Token.Instance.User.Basket;

            trace.Write(traceCategory, "Set Order Totals");
            LSDecimal curOrderTotal    = basket.Items.TotalPrice();
            LSDecimal curShippingTotal = basket.Items.TotalPrice(OrderItemType.Shipping) + GetShippingCouponTotal(basket.Items);
            LSDecimal curHandlingTotal = basket.Items.TotalPrice(OrderItemType.Handling);
            LSDecimal curTaxTotal      = basket.Items.TotalPrice(OrderItemType.Tax);
            LSDecimal curItemTotal     = curOrderTotal - (curShippingTotal + curHandlingTotal + curTaxTotal);

            //MAKE SURE OUR BREAKDOWN IS VALID
            if ((curShippingTotal < 0) || (curHandlingTotal < 0) || (curTaxTotal < 0) || (curItemTotal < 0))
            {
                //THE BREAKDOWN IS INVALID, DO NOT INCLUDE IT IN THE REQUEST
                curShippingTotal = 0;
                curHandlingTotal = 0;
                curTaxTotal      = 0;
                curItemTotal     = curOrderTotal;
            }

            //SET THE PAYMENT DETAILS
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails    = new PaymentDetailsType[1];
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0] = new PaymentDetailsType();
            PaymentDetailsType paymentDetails = expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0];

            paymentDetails.OrderTotal            = new BasicAmountType();
            paymentDetails.OrderTotal.currencyID = baseCurrencyCode;
            paymentDetails.OrderTotal.Value      = string.Format("{0:##,##0.00}", curOrderTotal);

            paymentDetails.ItemTotal            = new BasicAmountType();
            paymentDetails.ItemTotal.currencyID = baseCurrencyCode;
            paymentDetails.ItemTotal.Value      = string.Format("{0:##,##0.00}", curItemTotal);

            paymentDetails.ShippingTotal            = new BasicAmountType();
            paymentDetails.ShippingTotal.currencyID = baseCurrencyCode;
            paymentDetails.ShippingTotal.Value      = string.Format("{0:##,##0.00}", curShippingTotal);

            paymentDetails.HandlingTotal            = new BasicAmountType();
            paymentDetails.HandlingTotal.currencyID = baseCurrencyCode;
            paymentDetails.HandlingTotal.Value      = string.Format("{0:##,##0.00}", curHandlingTotal);

            paymentDetails.TaxTotal            = new BasicAmountType();
            paymentDetails.TaxTotal.currencyID = baseCurrencyCode;
            paymentDetails.TaxTotal.Value      = string.Format("{0:##,##0.00}", curTaxTotal);

            trace.Write(traceCategory, "Order Total: " + curOrderTotal);
            trace.Write(traceCategory, "Item Total: " + curItemTotal);
            trace.Write(traceCategory, "Shipping Total: " + curShippingTotal);
            trace.Write(traceCategory, "Handling Total: " + curHandlingTotal);
            trace.Write(traceCategory, "Tax Total: " + curTaxTotal);

            //SET THE BUTTON SOURCE
            trace.Write(traceCategory, "Set Button Source");
            paymentDetails.ButtonSource = "ablecommerce-EC";

            //SET THE NOTIFY URL
            string notifyUrl = GetStoreUrl() + "/ProcessPayPal.ashx";

            trace.Write(traceCategory, "IPN Callback URL: " + notifyUrl);
            paymentDetails.NotifyURL = notifyUrl;

            //WE HAVE ALL NECESSARY INFORMATION TO DO EXPRESS CHECKOUT
            //COMMIT THE ORDER BEFORE SUBMITTING THE PAYPAL TRANSACTION

            //CREATE THE ABLECOMMERCE PAYMENT ITEM
            Payment checkoutPayment = new Payment();

            checkoutPayment.PaymentMethodId = GetPayPalPaymentMethodId(false);
            checkoutPayment.Amount          = curOrderTotal;
            checkoutPayment.CurrencyCode    = baseCurrencyCode.ToString();

            //AT THIS POINT, EXECUTE THE CHECKOUT TO SUBMIT THE ORDER
            CheckoutRequest  checkoutRequest  = new CheckoutRequest(checkoutPayment);
            CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest);
            int orderId = checkoutResponse.OrderId;

            //LOAD THE ORDER AND RE-OBTAIN THE PAYMENT RECORD TO AVOID DATA INCONSISTENCIES
            Order order = OrderDataSource.Load(orderId);

            if (order == null)
            {
                //EXIT WITH EXCEPTION
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "ORDER";
                customError.ShortMessage = "Your order could not be completed at this time.";
                customError.LongMessage  = "Your order could not be completed at this time and payment was not processed. " + string.Join(" ", checkoutResponse.WarningMessages.ToArray());
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }

            int findPaymentId = checkoutPayment.PaymentId;

            foreach (Payment payment in order.Payments)
            {
                if (payment.PaymentId == findPaymentId)
                {
                    checkoutPayment = payment;
                }
            }

            //SET THE DESCRIPTION
            paymentDetails.OrderDescription = "Order #" + order.OrderNumber.ToString();
            paymentDetails.Custom           = orderId.ToString();

            //EXECUTE PAYPAL REQUEST
            trace.Write(traceCategory, "Do Request");
            DoExpressCheckoutPaymentResponseType expressCheckoutResponse = (DoExpressCheckoutPaymentResponseType)SoapCall("DoExpressCheckoutPayment", expressCheckoutRequest);

            ErrorType[]   responseErrors     = null;
            PaymentStatus finalPaymentStatus = PaymentStatus.Unprocessed;
            bool          isPendingeCheck    = false;

            if (expressCheckoutResponse != null)
            {
                if (expressCheckoutResponse.Errors == null)
                {
                    //CREATE THE PAYPAL TRANSACTION RECORD
                    Transaction     checkoutTransaction = new Transaction();
                    PaymentInfoType paymentInfo         = expressCheckoutResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0];
                    isPendingeCheck = (paymentInfo.PaymentStatus == PaymentStatusCodeType.Pending && paymentInfo.PendingReason == PendingStatusCodeType.echeck);
                    PaymentStatusCodeType paymentStatus = paymentInfo.PaymentStatus;
                    switch (paymentStatus)
                    {
                    case PaymentStatusCodeType.Completed:
                    case PaymentStatusCodeType.Processed:
                    case PaymentStatusCodeType.Pending:
                        if (isPendingeCheck)
                        {
                            finalPaymentStatus = PaymentStatus.CapturePending;
                            checkoutTransaction.ResponseCode    = "PENDING";
                            checkoutTransaction.ResponseMessage = "echeck";
                        }
                        else
                        {
                            finalPaymentStatus = (paymentStatus != PaymentStatusCodeType.Pending) ? PaymentStatus.Captured : PaymentStatus.Authorized;
                        }
                        checkoutTransaction.TransactionStatus = TransactionStatus.Successful;
                        break;

                    default:
                        finalPaymentStatus = PaymentStatus.Unprocessed;
                        checkoutTransaction.TransactionStatus = TransactionStatus.Failed;
                        checkoutTransaction.ResponseCode      = expressCheckoutResponse.Ack.ToString();
                        checkoutTransaction.ResponseMessage   = paymentStatus.ToString().ToUpperInvariant();
                        break;
                    }
                    checkoutTransaction.TransactionType       = this.UseAuthCapture ? TransactionType.Capture : TransactionType.Authorize;
                    checkoutTransaction.Amount                = AlwaysConvert.ToDecimal(paymentInfo.GrossAmount.Value, (Decimal)curOrderTotal);
                    checkoutTransaction.AuthorizationCode     = paymentInfo.TransactionID;
                    checkoutTransaction.AVSResultCode         = "U";
                    checkoutTransaction.ProviderTransactionId = paymentInfo.TransactionID;
                    checkoutTransaction.Referrer              = context.Request.ServerVariables["HTTP_REFERER"];
                    checkoutTransaction.PaymentGatewayId      = this.PaymentGatewayId;
                    checkoutTransaction.RemoteIP              = context.Request.ServerVariables["REMOTE_ADDR"];
                    checkoutPayment.Transactions.Add(checkoutTransaction);

                    //FIND THE WAITING FOR IPN TRANSACTION AND REMOVE
                    int i = checkoutPayment.Transactions.Count - 1;
                    while (i >= 0)
                    {
                        if (string.IsNullOrEmpty(checkoutPayment.Transactions[i].AuthorizationCode))
                        {
                            checkoutPayment.Transactions.DeleteAt(i);
                        }
                        i--;
                    }
                }
                else
                {
                    //SOME SORT OF ERROR ATTEMPTING CHECKOUT
                    responseErrors = expressCheckoutResponse.Errors;
                }
            }
            else
            {
                //NO RESPONSE, GENERATE CUSTOM ERROR
                responseErrors = new ErrorType[1];
                ErrorType customError = new ErrorType();
                customError.ErrorCode    = "NORESP";
                customError.ShortMessage = "No Response From Server";
                customError.LongMessage  = "The PayPal service is unavailable at this time.";
                responseErrors[0]        = customError;
            }
            trace.Write(traceCategory, "Do Request Done");

            //ERRORS IN RESPONSE?
            if ((responseErrors != null) && (responseErrors.Length > 0))
            {
                //CREATE THE PAYPAL TRANSACTION RECORD FOR ERROR
                Transaction checkoutTransaction = new Transaction();
                finalPaymentStatus = PaymentStatus.Unprocessed;
                checkoutTransaction.TransactionStatus = TransactionStatus.Failed;
                checkoutTransaction.Amount            = curOrderTotal;
                checkoutTransaction.AuthorizationCode = string.Empty;
                checkoutTransaction.Referrer          = context.Request.ServerVariables["HTTP_REFERER"];
                checkoutTransaction.PaymentGatewayId  = this.PaymentGatewayId;
                checkoutTransaction.RemoteIP          = context.Request.ServerVariables["REMOTE_ADDR"];
                checkoutTransaction.ResponseCode      = responseErrors[0].ShortMessage;
                checkoutTransaction.ResponseMessage   = responseErrors[0].LongMessage;
                checkoutPayment.Transactions.Add(checkoutTransaction);
            }

            //MAKE SURE PAYMENT STATUS IS CORRECT
            checkoutPayment.ReferenceNumber = paypalSession.Payer;
            checkoutPayment.PaymentStatus   = finalPaymentStatus;
            if (isPendingeCheck)
            {
                checkoutPayment.PaymentStatusReason = "echeck";
            }

            //RECALCULATE THE ORDER STATUS (BUG 6384) AND TRIGGER PAYMENT EVENTS (BUG 8650)
            order.Save(true, true);

            //CLEAR THE TOKENS SET IN SESSION
            paypalSession.Delete();
            return(new ExpressCheckoutResult(orderId, string.Empty, responseErrors));
        }
Exemple #15
0
        private static void DoStaffingOrganization()
        {
            StaffingOrganizationType staffingOrganization = new StaffingOrganizationType();

            // type organisatie, pattern extensie dus vrij, maar Customer, Intermediary en Supplier zijn gedefinieerd.
            staffingOrganization.typeOfOrganization = "Customer";

            #region Organization

            // nieuwe organisatie, toevoegen. Maar één per bericht, dat is wat setu aanbeveelt.
            var organization = new Organization();
            staffingOrganization.Organization.Add(organization);

            // nieuw referenceIDType

            var referenceIDType = new StaffingReferenceIdType();
            staffingOrganization.ReferenceIdInfo.Add(referenceIDType);

            #region Identifier van StaffingOrganization in Flex2GO

            // maken van eigen identifier Flex2GO
            var entityIDFlex2GO = new EntityIdType();
            // wij zijn eigenaar
            entityIDFlex2GO.idOwner = "Flex2GO";
            // waardeobject
            var entityIdTypeIdFlex2GO = new EntityIdTypeIdValue();
            // Flex2GO gebruikt guids
            entityIdTypeIdFlex2GO.Value = "F020D955-A2A8-4371-A57F-BB9E5012CEDD";
            // toevoegen waarde object aan entityId object
            entityIDFlex2GO.IdValue.Add(entityIdTypeIdFlex2GO);
            // toevoegen van EntityId object aan de lijst met HumanResourceId's, dit is die van Flex2GO

            organization.OrganizationId.Add(entityIDFlex2GO);
            #endregion

            #region Identifier van StaffingOrganization in Nocore

            // maken van eigen identifier Nocore
            var entityIDNocore = new EntityIdType();
            // wij zijn eigenaar
            entityIDNocore.idOwner = "SEDIS";
            // waardeobject
            var entityIdTypeIdNocore = new EntityIdTypeIdValue();
            // Nocore gebruikt integers, personeelsnummer
            entityIdTypeIdNocore.Value = "12345";
            // toevoegen waarde object aan entityId object
            entityIDNocore.IdValue.Add(entityIdTypeIdNocore);
            // toevoegen van EntityId object aan de lijst met HumanResourceId's, dit is die van Nocore
            organization.OrganizationId.Add(entityIDNocore);

            #endregion
            // naam organisatie
            organization.OrganizationName = "Birdseyeview B.V.";
            // omschrijving organisatie
            organization.Description = "Makers van Flex2GO, internetplatform voor de uitzend- en payrollbranche";
            // kvk
            var dunsNumber = new DunsNumberDataType();
            dunsNumber.dunsNumberType = DunsNumberDataTypeDunsNumberType.standardDuns;
            dunsNumber.Value          = "039087461";
            organization.DunsNumber.Add(dunsNumber);

            // SBI-code 2008 voor VPO marktmonitor
            var industryCode = new IndustryCodeType();
            industryCode.Value = "62.01";
            organization.IndustryCode.Add(industryCode);

            var internetAdres = new InternetDomainNameType();
            internetAdres.Value = "http://www.birdseyeview.nl/";
            organization.InternetDomainName.Add(internetAdres);

            #endregion

            #region contactpersonen

            var organizationContactInfo = new OrganizationContactType();

            // id van de contactpersoon in Flex2GO en/of NoCore

            #region Identifier van OrganizationContactType in Flex2GO

            // maken van eigen identifier Flex2GO
            EntityIdType entityIDContactFlex2GO = new EntityIdType();
            // wij zijn eigenaar
            entityIDContactFlex2GO.idOwner = "Flex2GO";
            // waardeobject
            EntityIdTypeIdValue entityIdContactTypeIdFlex2GO = new EntityIdTypeIdValue();
            // Flex2GO gebruikt guids
            entityIdContactTypeIdFlex2GO.Value = "F020D955-A2A8-4371-A57F-BB9E5012CEDD";
            // toevoegen waarde object aan entityId object
            entityIDContactFlex2GO.IdValue.Add(entityIdTypeIdFlex2GO);
            // toevoegen van EntityId object aan de lijst met HumanResourceId's, dit is die van Flex2GO
            organizationContactInfo.ContactId = entityIDContactFlex2GO;

            #endregion

            // Soort contactpersoon, met x: zelf te definieren, of één van de standaardwaarden
            organizationContactInfo.purpose = "x:Ontwikkelaar";
            // Naam
            var personName = new PersonNameType();
            SetName(personName, "", "Jansen", "Jan", "Jan");
            organizationContactInfo.ContactName = personName;
            // ContactMethodes

            ContactMethodType contactInfo = new ContactMethodType();
            contactInfo.Mobile               = CreateMobileNumber("0612341234", TelcomItemsChoiceType.FormattedNumber);
            contactInfo.Telephone            = CreateNumber("0306561563", TelcomItemsChoiceType.FormattedNumber);
            contactInfo.InternetEmailAddress = "*****@*****.**";

            organizationContactInfo.ContactMethod = contactInfo;

            organization.ContactInfo.Add(organizationContactInfo);

            #endregion

            #region Adres

            var workSite = new WorkSiteType();

            // nieuw HR-XML adres object
            PostalAddressType postalAddress = new PostalAddressType();
            // landcode van Nederland in ISO2
            postalAddress.CountryCode = "NL";

            // nieuw HR-XML PostalAddressTypeDeliveryAddress object

            PostalAddressTypeDeliveryAddress deliveryAddress = new PostalAddressTypeDeliveryAddress();
            // eigenschappen op object plakken
            deliveryAddress.StreetName     = "Groeneweg";
            deliveryAddress.BuildingNumber = "21";
            deliveryAddress.Unit           = "G";
            deliveryAddress.AddressLine.Add("Groeneweg 21G");
            postalAddress.DeliveryAddress = deliveryAddress;
            postalAddress.PostalCode      = "3981 CK";
            // type = streetAddress = Huisadres
            postalAddress.type          = PostalAddressTypeType.streetAddress;
            postalAddress.typeSpecified = true;

            // zet adres op ResourceInformation object
            workSite.PostalAddress = postalAddress;

            organization.WorkSite.Add(workSite);

            #endregion

            #region NocoreSpecific

            staffingOrganization.UserArea = new UserAreaType();

            var nocoreStaffingOrganization = new NocoreStaffingOrganizationType();

            var cla = new CLAReferenceType();
            cla.CLAId       = "1045";
            cla.Description = "THUISZORG";
            nocoreStaffingOrganization.CLA            = cla;
            nocoreStaffingOrganization.AccountManager = "Gert Dingemans";
            nocoreStaffingOrganization.Location       = new NocoreLocationType();
            nocoreStaffingOrganization.Location.Code  = "1";
            nocoreStaffingOrganization.Location.Name  = "Hoofdvestiging";
            nocoreStaffingOrganization.Status         = "Actief";
            nocoreStaffingOrganization.Modified       = DateTime.Now;

            staffingOrganization.UserArea.NocoreStaffingOrganization          = nocoreStaffingOrganization;
            staffingOrganization.UserArea.NocoreStaffingOrganizationSpecified = true;

            #endregion

            var paymentInfo = new PaymentInfoType();

            paymentInfo.BankAccountInfo = new BankAccountInfoType();
            paymentInfo.BankAccountInfo.BankAccountForeign = "592177424";

            paymentInfo.PaymentCondition             = new PaymentInfoTypePaymentCondition();
            paymentInfo.PaymentCondition.Description = "14 dagen";
            // 19 voor 19%, 0 VOOR btw Verlegd
            paymentInfo.VATRate          = 19;
            paymentInfo.VATRateSpecified = true;
            staffingOrganization.PaymentInfo.Add(paymentInfo);

            staffingOrganization.SaveToFile("StaffingOrganization.xml");

            // Laad weer uit bestand

            StaffingOrganizationType loadedStaffingOrganization =
                EntityBase <StaffingOrganizationType> .LoadFromFile("StaffingOrganization.xml");

            // druk naam af.

            Console.WriteLine(loadedStaffingOrganization.Organization[0].OrganizationName);
        }