/**
         *
         */
        public PreapprovalResponse Preapproval(PreapprovalRequest PreapprovalRequest, string apiUsername)
        {
            string resp = call("Preapproval", PreapprovalRequest.toNVPString(""), apiUsername);

            NVPUtil util = new NVPUtil();
            return new PreapprovalResponse(util.parseNVPString(resp), "");
        }
 public PreapprovalResponse Preapproval(PreapprovalRequest PreapprovalRequest)
 {
     return Preapproval(PreapprovalRequest, null);
 }
	 	/// <summary>
		/// 
	 	/// </summary>
		///<param name="preapprovalRequest"></param>
		///<param name="credential">An explicit ICredential object that you want to authenticate this call against</param> 
	 	public PreapprovalResponse Preapproval(PreapprovalRequest preapprovalRequest, ICredential credential)
	 	{	 			 		
			IAPICallPreHandler apiCallPreHandler = new PlatformAPICallPreHandler(this.config, preapprovalRequest.ToNVPString(string.Empty), ServiceName, "Preapproval", credential);
	   	 	((PlatformAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
			((PlatformAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
			((PlatformAPICallPreHandler) apiCallPreHandler).PortName = "AdaptivePayments";

			NVPUtil util = new NVPUtil();
			return PreapprovalResponse.CreateInstance(util.ParseNVPString(Call(apiCallPreHandler)), string.Empty, -1);
			
	 	}
        /// <summary>
        /// Handle Preapproval API
        /// </summary>
        /// <param name="context"></param>
        private void Preapproval(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PreapprovalRequest req = new PreapprovalRequest(new RequestEnvelope("en_US"), parameters["cancelUrl"],
                    parameters["currencyCode"], parameters["returnUrl"], parameters["startingDate"]);
            // set optional parameters
            if(parameters["dateOfMonth"] != "")
            {
                req.dateOfMonth = Int32.Parse(parameters["dateOfMonth"]);
            }
            if(parameters["dayOfWeek"] != "" && parameters["dayOfWeek"] != "")
            {
                req.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }
            if(parameters["dateOfMonth"] != "")
            {
                req.dateOfMonth = Int32.Parse(parameters["dateOfMonth"]);
            }
            if(parameters["endingDate"] != "")
            {
                req.endingDate = parameters["endingDate"];
            }
            if(parameters["maxAmountPerPayment"] != "")
            {
                req.maxAmountPerPayment = Decimal.Parse(parameters["maxAmountPerPayment"]);
            }
            if(parameters["maxNumberOfPayments"] != "" )
            {
                req.maxNumberOfPayments = Int32.Parse(parameters["maxNumberOfPayments"]);
            }
            if(parameters["maxNumberOfPaymentsPerPeriod"] != "")
            {
                req.maxNumberOfPaymentsPerPeriod = Int32.Parse(parameters["maxNumberOfPaymentsPerPeriod"]);
            }
            if(parameters["maxTotalAmountOfAllPayments"] != "")
            {
                req.maxTotalAmountOfAllPayments = Decimal.Parse(parameters["maxTotalAmountOfAllPayments"]);
            }
            if(parameters["paymentPeriod"] != "" && parameters["paymentPeriod"] != "")
            {
                req.paymentPeriod = parameters["paymentPeriod"];
            }
            if(parameters["memo"] != "")
            {
                req.memo = parameters["memo"];
            }
            if(parameters["ipnNotificationUrl"] != "")
            {
                req.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }
            if(parameters["senderEmail"] != "")
            {
                req.senderEmail = parameters["senderEmail"];
            }
            if(parameters["pinType"] != "" && parameters["pinType"] != "")
            {
                req.pinType = parameters["pinType"];
            }
            if(parameters["feesPayer"] != "")
            {
                req.feesPayer = parameters["feesPayer"];
            }
            if (parameters["displayMaxTotalAmount"] != "")
            {
                req.displayMaxTotalAmount = Boolean.Parse(parameters["displayMaxTotalAmount"]);
            }

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            PreapprovalResponse resp = null;
            try
            {
                resp = service.Preapproval(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Preapproval key", resp.preapprovalKey);

                //Selenium Test Case
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"]
                                     + "_ap-preapproval&preapprovalkey=" + resp.preapprovalKey;
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
                keyResponseParams.Add("Redirect To PayPal", redirectUrl);
            }
            displayResponse(context, "Preapproval", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        /// <summary>
        /// Handle Preapproval API
        /// </summary>
        /// <param name="contextHttp"></param>
        private void Preapproval(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // error language : (Required) RFC 3066 language in which error messages are returned; by default it is en_US, which is the only language currently supported. 
            // cancel url : URL to redirect the sender's browser to after canceling the preapproval 
            // currency code : The code for the currency in which the payment is made; you can specify only one currency, regardless of the number of receivers 
            // return url : URL to redirect the sender's browser to after the sender has logged into PayPal and confirmed the preapproval 
            // starting date : First date for which the preapproval is valid. It cannot be before today's date or after the ending date. 
            PreapprovalRequest request = new PreapprovalRequest(new RequestEnvelope("en_US"), parameters["cancelUrl"], 
                    parameters["currencyCode"], parameters["returnUrl"], parameters["startingDate"]);
            
            // (Optional) The day of the month on which a monthly payment is to be made. 
            // Allowable values are numbers between 0 and 31. A number between 1 and 31 
            // indicates the date of the month. Specifying 0 indicates that payment can be 
            // made on any day of the month. 
            if(parameters["dateOfMonth"] != string.Empty) 
            {
	            request.dateOfMonth = Convert.ToInt32(parameters["dateOfMonth"]);
            }

            // (Optional) The day of the week that a weekly payment is to be made. 
            // Allowable values are:
            //   NO_DAY_SPECIFIED
            //   SUNDAY
            //   MONDAY
            //   TUESDAY
            //   WEDNESDAY
            //   THURSDAY
            //   FRIDAY
            //   SATURDAY

            if(parameters["dayOfWeek"] != string.Empty && parameters["dayOfWeek"] != string.Empty) 
            {
                request.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }

            //(Optional) The day of the month on which a monthly payment is to be made. 
            // Allowable values are numbers between 0 and 31. A number between 1 and 31 
            // indicates the date of the month. Specifying 0 indicates that payment 
            // can be made on any day of the month. 
            if(parameters["dateOfMonth"] != string.Empty) 
            {
	            request.dateOfMonth = Convert.ToInt32(parameters["dateOfMonth"]);
            }

            // xs:dateTime (Optional) Last date for which the preapproval is valid. 
            // It cannot be later than one year from the starting date.
            // Note: You must specify a value unless you have specific permission 
            // from PayPal to omit this value. 
            if(parameters["endingDate"] != string.Empty) 
            {
	            request.endingDate = parameters["endingDate"];
            }

            // (Optional) The preapproved maximum amount per payment. 
            // It cannot exceed the preapproved maximum total amount of all payments. 
            if(parameters["maxAmountPerPayment"] != string.Empty) 
            {
	            request.maxAmountPerPayment = Convert.ToDecimal(parameters["maxAmountPerPayment"]);
            }

            // (Optional) The preapproved maximum number of payments. 
            // It cannot exceed the preapproved maximum total number of all payments. 
            if(parameters["maxNumberOfPayments"] != string.Empty ) 
            {
	            request.maxNumberOfPayments = Convert.ToInt32(parameters["maxNumberOfPayments"]);
            }

            //(Optional) The preapproved maximum number of all payments per period. 
            // You must specify a value unless you have specific permission from PayPal. 
            if(parameters["maxNumberOfPaymentsPerPeriod"] != string.Empty) 
            {
	            request.maxNumberOfPaymentsPerPeriod = Convert.ToInt32(parameters["maxNumberOfPaymentsPerPeriod"]);
            }

            // The preapproved maximum total amount of all payments. 
            // It cannot exceed $2,000 USD or its equivalent in other currencies. 
            // Contact PayPal if you do not want to specify a maximum amount. 
            if(parameters["maxTotalAmountOfAllPayments"] != string.Empty) 
            {
	            request.maxTotalAmountOfAllPayments = Convert.ToDecimal(parameters["maxTotalAmountOfAllPayments"]);
            }

            //(Optional) The payment period. It is one of the following values:
            //    NO_PERIOD_SPECIFIED
            //    DAILY – Each day
            //    WEEKLY – Each week
            //    BIWEEKLY – Every other week
            //    SEMIMONTHLY – Twice a month
            //    MONTHLY – Each month
            //    ANNUALLY – Each year
            if(parameters["paymentPeriod"] != string.Empty && parameters["paymentPeriod"] != string.Empty) 
            {
	            request.paymentPeriod = parameters["paymentPeriod"];
            }

            // (Optional) A note about the preapproval. 
            // Maximum length: 1000 characters, including newline characters 
            if(parameters["memo"] != string.Empty) 
            {
	            request.memo = parameters["memo"];
            }

            // Optional) The URL to which you want all IPN messages for 
            // this preapproval to be sent. This URL supersedes the 
            // IPN notification URL in your profile. Maximum length: 1024 characters 
            if(parameters["ipnNotificationUrl"] != string.Empty) 
            {
	            request.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }

            // (Optional) Sender's email address. If not specified, the email address 
            // of the sender who logs in to approve the request becomes the email address 
            // associated with the preapproval key. Maximum length: 127 characters 
            if(parameters["senderEmail"] != string.Empty) 
            {
	            request.senderEmail = parameters["senderEmail"];
            }

            // (Optional) Whether a personal identification number (PIN) is required. 
            // It is one of the following values:

            //    NOT_REQUIRED – A PIN is not required (default)
            //    REQUIRED – A PIN is required; the sender must specify a PIN when setting up the preapproval on PayPal
            if(parameters["pinType"] != string.Empty && parameters["pinType"] != string.Empty) 
            {
	            request.pinType = parameters["pinType"];
            }

            // (Optional) The payer of PayPal fees. Allowable values are:
            //    SENDER – Sender pays all fees (for personal, implicit simple/parallel payments; do not use for chained or unilateral payments)
            //    PRIMARYRECEIVER – Primary receiver pays all fees (chained payments only)
            //    EACHRECEIVER – Each receiver pays their own fee (default, personal and unilateral payments)
            //    SECONDARYONLY – Secondary receivers pay all fees (use only for chained payments with one secondary receiver)
            if(parameters["feesPayer"] != string.Empty) 
            {
	            request.feesPayer = parameters["feesPayer"];
            }

            //(Optional) Whether to display the maximum total amount of this preapproval. It is one of the following values:
            // TRUE – Display the amount
            // FALSE – Do not display the amount (default)
            if (parameters["displayMaxTotalAmount"] != string.Empty)
            {
                request.displayMaxTotalAmount = Convert.ToBoolean(parameters["displayMaxTotalAmount"]);
            }
          
            AdaptivePaymentsService service = null;
            PreapprovalResponse response = null;
            try
            {
                // Configuration map containing signature credentials and other required configuration.
                // For a full list of configuration parameters refer in wiki page 
                // (https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters)
                Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);
                response = service.Preapproval(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //  A preapproval key that identifies the preapproval requested.
                responseValues.Add("Preapproval key", response.preapprovalKey);

                
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"]
                                     + "_ap-preapproval&preapprovalkey=" + response.preapprovalKey;
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
                responseValues.Add("Redirect To PayPal", redirectUrl);
            }
            Display(contextHttp, "Preapproval", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
	 	/// <summary> 
		/// 
	 	/// </summary>
		///<param name="preapprovalRequest"></param>
	 	
	 	public PreapprovalResponse Preapproval(PreapprovalRequest preapprovalRequest)
	 	{
	 		return Preapproval(preapprovalRequest,(string) null);
	 	}
 /**
   *AUTO_GENERATED
  	  */
 public PreapprovalResponse Preapproval(PreapprovalRequest preapprovalRequest, string apiUserName)
 {
     string response = Call("Preapproval", preapprovalRequest.ToNVPString(""), apiUserName);
     NVPUtil util = new NVPUtil();
     return PreapprovalResponse.CreateInstance(util.ParseNVPString(response), "", -1);
 }
        // # Preapproval API Operation
        // Use the Preapproval API operation to set up an agreement between yourself and a sender for making payments on the sender’s behalf. You set up a preapprovals for a specific maximum amount over a specific period of time and, optionally, by any of the following constraints: the number of payments, a maximum per-payment amount, a specific day of the week or the month, and whether or not a PIN is required for each payment request.
        public PreapprovalResponse GeneratePreapproval(Preapproval preapproval)
        {
            // Create the PreapprovalResponse object
            var responsePreapproval = new PreapprovalResponse();

            try
            {
                // # PreapprovalRequest
                // The code for the language in which errors are returned
                var envelopeRequest = new RequestEnvelope {errorLanguage = "en_US"};

                const string pattern = "yyyy-MM-dd";

                var requestPreapproval = new PreapprovalRequest(envelopeRequest, preapproval.CancelURL, "USD", preapproval.ReturnURL, "2013-07-15")
                    {ipnNotificationUrl = preapproval.IPNHost};

                // IPN URL
                //
                // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
                // * The transaction related IPN variables will be received on the call back URL specified in the request
                // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
                // * PayPal would continuously resend IPN if a wrong IPN is sent

                // Create the service wrapper object to make the API call
                var service = new AdaptivePaymentsService();

                // # API call
                // Invoke the Preapproval method in service wrapper object
                responsePreapproval = service.Preapproval(requestPreapproval);

                if (responsePreapproval != null)
                {
                    // Response envelope acknowledgement
                    string acknowledgement = "Preapproval API Operation - ";
                    acknowledgement += responsePreapproval.responseEnvelope.ack.ToString();
                    Console.WriteLine(acknowledgement + "\n");

                    // # Success values
                    if (responsePreapproval.responseEnvelope != null && responsePreapproval.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        var preApprovalDetails = PreapprovalDetailsAPIOperation(responsePreapproval.preapprovalKey);
                        _preApprovalService = DependencyResolver.Current.GetService<IPreApprovalService>();
                        _preApprovalService.SaveOrUpdate(new PreApproval
                            {
                                Approved =  preApprovalDetails.approved != null && preApprovalDetails.approved.Value,
                                ContractStartDate = DateTime.Parse(preApprovalDetails.startingDate),
                                ContractEndDate = DateTime.Parse(preApprovalDetails.endingDate),
                                PreApprovalKey = responsePreapproval.preapprovalKey,
                                Userd = UserProfile.Current.UserId
                            });
                    }
                    // # Error Values
                    else
                    {
                        List<ErrorData> errorMessages = responsePreapproval.error;
                        foreach (ErrorData error in errorMessages)
                        {
                            Console.WriteLine("API Error Message : " + error.message + "\n");
                        }
                    }
                }
            }
            // # Exception log
            catch (Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return responsePreapproval;
        }
        /// <summary>
        /// Handles Preapproval API calls
        /// </summary>
        /// <param name="contextHttp"></param>
        private void Preapproval(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            PreapprovalRequest request = new PreapprovalRequest();

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            request.requestEnvelope = requestEnvelope;

            // (Optional) Sender's email address. Maximum length: 127 characters
            if (parameters["senderEmail"] != null && parameters["senderEmail"].Trim() != string.Empty)
            {
                request.senderEmail = "*****@*****.**";
            }

            // (Optional) The day of the month on which a monthly payment is to be made.
            // Allowable values are numbers between 0 and 31.
            // A number between 1 and 31 indicates the date of the month.
            // Specifying 0 indicates that payment can be made on any day of the month. 
            if (parameters["dateOfMonth"] != null && parameters["dateOfMonth"].Trim() != string.Empty)
            {
                request.dateOfMonth = Convert.ToInt32(parameters["dateOfMonth"]);
            }

            // (Optional) The day of the week that a weekly payment is to be made. Allowable values are: 
            // NO_DAY_SPECIFIED
            // SUNDAY
            // MONDAY
            // TUESDAY
            // WEDNESDAY
            // THURSDAY
            // FRIDAY
            // SATURDAY
            if (parameters["dayOfWeek"] != null && parameters["dayOfWeek"].Trim() != string.Empty)
            {
                request.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }

            // (Optional) Whether to display the maximum total amount of this preapproval. It is one of the following values:
            // TRUE – Display the amount
            // FALSE – Do not display the amount (default)
            if (parameters["displayMaxTotalAmount"] != null && parameters["displayMaxTotalAmount"].Trim() != string.Empty)
            {
                request.displayMaxTotalAmount = Convert.ToBoolean(parameters["displayMaxTotalAmount"]);
            }

            // (Optional) The URL to which you want all IPN messages for this preapproval to be sent.
            // This URL supersedes the IPN notification URL in your profile.
            // Maximum length: 1024 characters
            if (parameters["ipnNotificationURL"] != null && parameters["ipnNotificationURL"].Trim() != string.Empty)
            {
                request.ipnNotificationUrl = parameters["ipnNotificationURL"];
            }

            // (Optional) The preapproved maximum amount per payment.
            // It cannot exceed the preapproved maximum total amount of all payments. 
            if (parameters["maxAmountPerPayment"] != null && parameters["maxAmountPerPayment"].Trim() != string.Empty)
            {
                request.maxAmountPerPayment = Convert.ToDecimal(parameters["maxAmountPerPayment"]);
            }

            // (Optional) The preapproved maximum number of payments.
            // It cannot exceed the preapproved maximum total number of all payments. 
            if (parameters["maxNumberOfPayments"] != null && parameters["maxNumberOfPayments"].Trim() != string.Empty)
            {
                request.maxNumberOfPayments = Convert.ToInt32(parameters["maxNumberOfPayments"]);
            }
            
            // (Optional) The preapproved maximum number of all payments per period. 
            // You must specify a value unless you have specific permission from PayPal.
            if (parameters["maxNumberOfPaymentsPerPeriod"] != null && parameters["maxNumberOfPaymentsPerPeriod"].Trim() != string.Empty)
            {
                request.maxNumberOfPaymentsPerPeriod = Convert.ToInt32(parameters["maxNumberOfPaymentsPerPeriod"]);
            }

            // (Optional) The preapproved maximum total amount of all payments.
            // It cannot exceed $2,000 USD or its equivalent in other currencies.
            if (parameters["totalAmountOfAllPayments"] != null && parameters["totalAmountOfAllPayments"].Trim() != string.Empty)
            {
                request.maxTotalAmountOfAllPayments = Convert.ToDecimal(parameters["totalAmountOfAllPayments"]);
            }

            // (Optional) The payment period. It is one of the following values:
            // NO_PERIOD_SPECIFIED
            // DAILY – Each day
            // WEEKLY – Each week
            // BIWEEKLY – Every other week
            // SEMIMONTHLY – Twice a month
            // MONTHLY – Each month
            // ANNUALLY – Each year
            if (parameters["paymentPeriod"] != null && parameters["paymentPeriod"].Trim() != string.Empty)
            {
                request.paymentPeriod = parameters["paymentPeriod"];
            }

            // (Optional) Sender's email address. If not specified,
            // the email address of the sender who logs in to approve
            // the request becomes the email address associated with the preapproval key.
            // Maximum length: 127 characters
            if (parameters["senderEmail"] != null && parameters["senderEmail"].Trim() != string.Empty)
            {
                request.senderEmail = parameters["senderEmail"];
            }

            // The code for the currency in which the payment is made; 
            // you can specify only one currency, regardless of the number of receivers.
            if (parameters["currencyCode"] != null && parameters["currencyCode"].Trim() != string.Empty)
            {
                request.currencyCode = parameters["currencyCode"];
            }

            // URL to redirect the sender's browser to after canceling the preapproval 
            if (parameters["cancelURL"] != null && parameters["cancelURL"].Trim() != string.Empty)
            {
                request.cancelUrl = parameters["cancelURL"];
            }
            
            // URL to redirect the sender's browser
            // to after the sender has logged into PayPal and confirmed the preapproval.
            if (parameters["returnURL"] != null && parameters["returnURL"].Trim() != string.Empty)
            {
                request.returnUrl = parameters["returnURL"];
            }

            request.requestEnvelope = requestEnvelope;

            // First date for which the preapproval is valid. 
            // It cannot be before today's date or after the ending date.
            if (parameters["startingDate"] != null && parameters["startingDate"].Trim() != string.Empty)
            {
                request.startingDate = parameters["startingDate"];
            }

            // Last date for which the preapproval is valid. 
            // It cannot be later than one year from the starting date. 
            // Contact PayPal if you do not want to specify an ending date.
            if (parameters["endingDate"] != null && parameters["endingDate"].Trim() != string.Empty)
            {
                request.endingDate = parameters["endingDate"];
            }

            AdaptivePaymentsService service = null;
            PreapprovalResponse response = null;
            try
            {
                // Configuration map containing signature credentials and other required configuration.
                // For a full list of configuration parameters refer in wiki page 
                // (https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters)
                Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);
                response = service.Preapproval(request);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;

            if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                // A preapproval key that identifies the preapproval requested.
                responseValues.Add("Preapproval Key", response.preapprovalKey);
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"] + "_ap-preapproval&preapprovalkey=" + response.preapprovalKey;
                Session["preapprovalKey"] = response.preapprovalKey;
            }

            responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString().Trim().ToUpper());

            Display(contextHttp, "Preapproval", "AdaptivePayments", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
    // # Preapproval API Operation 
    // Use the Preapproval API operation to set up an agreement between yourself and a sender for making payments on the sender’s behalf. You set up a preapprovals for a specific maximum amount over a specific period of time and, optionally, by any of the following constraints: the number of payments, a maximum per-payment amount, a specific day of the week or the month, and whether or not a PIN is required for each payment request. 
    public PreapprovalResponse PreapprovalAPIOperation()
    {
        // Create the PreapprovalResponse object
        PreapprovalResponse responsePreapproval = new PreapprovalResponse();

        try
        {
            // # PreapprovalRequest
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // PreapprovalRequest takes mandatory params:
            //      
            // * `RequestEnvelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            // * `Cancel URL` - URL to redirect the sender's browser to after
            // canceling the preapproval
            // * `Currency Code` - The code for the currency in which the payment is
            // made; you can specify only one currency, regardless of the number of
            // receivers
            // * `Return URL` - URL to redirect the sender's browser to after the
            // sender has logged into PayPal and confirmed the preapproval
            // * `Starting Date` - First date for which the preapproval is valid. It
            // cannot be before today's date or after the ending date.
            PreapprovalRequest requestPreapproval = new PreapprovalRequest(envelopeRequest, "http://localhost/cancel", "USD", "http://localhost/return", "2013-12-18");

            // IPN URL
            //  
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed        
            // * The transaction related IPN variables will be received on the call back URL specified in the request       
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"     
            // * PayPal would continuously resend IPN if a wrong IPN is sent        
            requestPreapproval.ipnNotificationUrl = "http://IPNhost";

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

            // # API call
            // Invoke the Preapproval method in service wrapper object
            responsePreapproval = service.Preapproval(requestPreapproval);

            if (responsePreapproval != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "Preapproval API Operation - ";
                acknowledgement += responsePreapproval.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responsePreapproval.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    logger.Info("Preapproval Key : " + responsePreapproval.preapprovalKey + "\n");
                    Console.WriteLine("Preapproval Key : " + responsePreapproval.preapprovalKey + "\n");

                    // Once you get success response, user has to redirect to PayPal
                    // to preapprove the payment. Construct redirectURL as follows,
                    // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-preapproval&preapprovalkey="
                    // + responsePreapproval.preapprovalKey;`                    
                }
                // # Error Values
                else
                {
                    List<ErrorData> errorMessages = responsePreapproval.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responsePreapproval;
    }
        public PreapprovalResponse PaypalPreapprovalRequest(paypal_preapproval obj)
        {
            var headers = PaypalHelper.GetHeader();

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");

            PreapprovalRequest payRequest = new PreapprovalRequest
            {
                requestEnvelope = requestEnvelope,
                returnUrl = ConfigurationManager.AppSettings["PAYPAL_CONFIRM_RETURN_URL"] + obj.flag,
                cancelUrl = ConfigurationManager.AppSettings["PAYPAL_CONFIRM_CANCEL_URL"],
                pinType = "NOT_REQUIRED",
                currencyCode = ConfigurationManager.AppSettings["DEFAULT_PAYPAL_CURRENCY"],
                maxAmountPerPayment = obj.max_amount_per_payment,
                maxNumberOfPayments = obj.max_number_of_payments,
                maxTotalAmountOfAllPayments = obj.max_total_amount_of_all_payments,
                senderEmail = obj.sender_email,
                startingDate = obj.starting_date.ToString("yyyy-MM-dd'T'HH:mm:ss.000zzz"),
                endingDate = obj.ending_date.ToString("yyyy-MM-dd'T'HH:mm:ss.000zzz")
            };


            AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(headers);
            PreapprovalResponse payResponse = adaptivePaymentsService.Preapproval(payRequest);
            return payResponse;
        }