/// <summary>
 /// Create a new AdvertiserHackedPDT object.
 /// </summary>
 /// <param name="pDTID">Initial value of the PDTID property.</param>
 /// <param name="grossTotal">Initial value of the GrossTotal property.</param>
 /// <param name="invoice">Initial value of the Invoice property.</param>
 /// <param name="paymentStatus">Initial value of the PaymentStatus property.</param>
 /// <param name="firstName">Initial value of the FirstName property.</param>
 /// <param name="lastName">Initial value of the LastName property.</param>
 /// <param name="paymentFee">Initial value of the PaymentFee property.</param>
 /// <param name="businessEmail">Initial value of the BusinessEmail property.</param>
 /// <param name="txToken">Initial value of the TxToken property.</param>
 /// <param name="receiverEmail">Initial value of the ReceiverEmail property.</param>
 /// <param name="itemName">Initial value of the ItemName property.</param>
 /// <param name="currencyCode">Initial value of the CurrencyCode property.</param>
 /// <param name="transactionId">Initial value of the TransactionId property.</param>
 /// <param name="custom">Initial value of the Custom property.</param>
 /// <param name="subscriberId">Initial value of the SubscriberId property.</param>
 /// <param name="adID">Initial value of the AdID property.</param>
 public static AdvertiserHackedPDT CreateAdvertiserHackedPDT(global::System.Int32 pDTID, global::System.Double grossTotal, global::System.Int32 invoice, global::System.String paymentStatus, global::System.String firstName, global::System.String lastName, global::System.Double paymentFee, global::System.String businessEmail, global::System.String txToken, global::System.String receiverEmail, global::System.String itemName, global::System.String currencyCode, global::System.String transactionId, global::System.String custom, global::System.String subscriberId, global::System.Int32 adID)
 {
     AdvertiserHackedPDT advertiserHackedPDT = new AdvertiserHackedPDT();
     advertiserHackedPDT.PDTID = pDTID;
     advertiserHackedPDT.GrossTotal = grossTotal;
     advertiserHackedPDT.Invoice = invoice;
     advertiserHackedPDT.PaymentStatus = paymentStatus;
     advertiserHackedPDT.FirstName = firstName;
     advertiserHackedPDT.LastName = lastName;
     advertiserHackedPDT.PaymentFee = paymentFee;
     advertiserHackedPDT.BusinessEmail = businessEmail;
     advertiserHackedPDT.TxToken = txToken;
     advertiserHackedPDT.ReceiverEmail = receiverEmail;
     advertiserHackedPDT.ItemName = itemName;
     advertiserHackedPDT.CurrencyCode = currencyCode;
     advertiserHackedPDT.TransactionId = transactionId;
     advertiserHackedPDT.Custom = custom;
     advertiserHackedPDT.SubscriberId = subscriberId;
     advertiserHackedPDT.AdID = adID;
     return advertiserHackedPDT;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the AdvertiserHackedPDTs EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToAdvertiserHackedPDTs(AdvertiserHackedPDT advertiserHackedPDT)
 {
     base.AddObject("AdvertiserHackedPDTs", advertiserHackedPDT);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // Used parts from https://www.paypaltech.com/PDTGen/
            // Visit above URL to auto-generate PDT script
            authToken = WebConfigurationManager.AppSettings["ADPDTToken"];

            //read in txn token from querystring
            txToken = Request.QueryString.Get("tx");

            query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, authToken);

            // Create the request back
            string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            //  Response.Write(req.ToString());
            // Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = query.Length;

            // Write the request back IPN strings
            StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            stOut.Write(query);
            stOut.Close();

            // Do the request to PayPal and get the response
            StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
            strResponse = stIn.ReadToEnd();
            stIn.Close();

            //string strResponse = "SUCCESS mc_gross=145.35 protection_eligibility=Ineligible address_status=confirmed payer_id=WJ3SRWX9PXP94 tax=0.00 address_street=1+Main+St payment_date=07%3A13%3A35+Sep+06%2C+2012+PDT payment_status=Pending terminal_id= charset=windows-1252 address_zip=95131 first_name=sdgsd receipt_reference_number= mc_fee=4.52 address_country_code=US address_name=sdgsd+sdgs custom=80%2C9b5dc3f5-54d2-413b-9803-1fbabe6770ac payer_status=verified business=sellpr_1346179874_biz%40yahoo.com address_country=United+States address_city=San+Jose quantity=1 payer_email=adver_1345188328_per%40yahoo.com txn_id=059835996R2655052 payment_type=instant last_name=sdgs address_state=CA receiver_email=sellpr_1346179874_biz%40yahoo.com store_id= payment_fee=4.52 receiver_id=EVBLGJGBR8RL8 pending_reason=paymentreview pos_transaction_type= txn_type=web_accept item_name=ewtwet num_offers=0 mc_currency=USD item_number=1 residence_country=US handling_amount=0.00 transaction_subject=80%2C9b5dc3f5-54d2-413b-9803-1fbabe6770ac payment_gross=145.35 shipping=0.00 ";
            // sanity check

            //Response.Write(strResponse);

            PDTHolder pdt = PDTHolder.Parse(strResponse);

            // If response was SUCCESS, parse response string and output details
            if (strResponse.StartsWith("SUCCESS"))
            {
                using (var context = new AdDatabaseModel.AdDatabaseEntities())
                {
                    try
                    {
                        var Custom = pdt.Custom.Split(',');
                        int AdID = int.Parse(Custom[0]);
                        var result2 = from c in context.AdGenerals
                                      where c.AdID == AdID
                                      select c.UserID;
                        Guid userID = Guid.Parse(result2.FirstOrDefault().ToString());
                        var result = from c in context.AdvertiserSuccessfulPDTs
                                     where (c.AdID == AdID && c.AdvertiserID == userID && c.GrossTotal.Equals(pdt.GrossTotal) && c.CurrencyCode == pdt.Currency)
                                     select c.TransactionId;
                        var resultQuery = result.FirstOrDefault();
                        if (resultQuery == null)
                        {
                            HiddenLabel.Text = string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!",
                                pdt.PayerFirstName, pdt.PayerLastName, pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);

                            //Insert into Successful PDT
                            var advertiserSuccessfulPDT = new AdDatabaseModel.AdvertiserSuccessfulPDT
                            {
                                PDTID = Admanagment.Helpers.Utility.GetNextSuccessfulPDTID(),
                                GrossTotal = pdt.GrossTotal,
                                Invoice = pdt.InvoiceNumber,
                                PaymentStatus = pdt.PaymentStatus,
                                FirstName = pdt.PayerFirstName,
                                LastName = pdt.PayerLastName,
                                PaymentFee = pdt.PaymentFee,
                                BusinessEmail = pdt.BusinessEmail,
                                TxToken = Request.QueryString.Get("tx"),
                                ReceiverEmail = pdt.ReceiverEmail,
                                ItemName = pdt.ItemName,
                                CurrencyCode = pdt.Currency,
                                TransactionId = pdt.TransactionId,
                                Custom = pdt.Custom,
                                subscriberId = "",
                                AdvertiserID = userID,
                                AdID = int.Parse(Custom[0])
                            };
                            var PaymentID = int.Parse(Custom[2]);
                            AdDatabaseModel.AdvertiserPaymentDue currentpaymentdue = (from c in context.AdvertiserPaymentDues
                                                                                      where c.PaymentDueID == PaymentID
                                                                                      select c).FirstOrDefault();
                            //Response.Write(pdt.PaymentStatus.ToString());
                            if (pdt.PaymentStatus == "Completed")
                            {
                                //Archived PDT
                                var archivedadvertiserSuccessfulPDT = new AdDatabaseModel.ArchivedAdvertiserSuccessfulPDT
                                {
                                    PDTID = Admanagment.Helpers.Utility.GetNextSuccessfulPDTID(),
                                    GrossTotal = pdt.GrossTotal,
                                    Invoice = pdt.InvoiceNumber,
                                    PaymentStatus = pdt.PaymentStatus,
                                    FirstName = pdt.PayerFirstName,
                                    LastName = pdt.PayerLastName,
                                    PaymentFee = pdt.PaymentFee,
                                    BusinessEmail = pdt.BusinessEmail,
                                    TxToken = Request.QueryString.Get("tx"),
                                    ReceiverEmail = pdt.ReceiverEmail,
                                    ItemName = pdt.ItemName,
                                    CurrencyCode = pdt.Currency,
                                    TransactionId = pdt.TransactionId,
                                    Custom = pdt.Custom,
                                    subscriberId = pdt.SubscriberId,
                                    AdvertiserID = userID,
                                    AdID = int.Parse(Custom[0])
                                };
                                context.AddToArchivedAdvertiserSuccessfulPDTs(archivedadvertiserSuccessfulPDT);
                                //Archived Payment Due
                                var archivedpaymentdue = new AdDatabaseModel.ArchivedAdvertiserPayment
                                {
                                    AdvertiserID = currentpaymentdue.AdvertiserID,
                                    PaymentDueID = currentpaymentdue.PaymentDueID,
                                    AdID = currentpaymentdue.AdID,
                                    AdAmount = currentpaymentdue.AdAmount,
                                    Date = currentpaymentdue.Date,
                                    CurrencyCode = currentpaymentdue.CurrencyCode,
                                    PaymentDue = currentpaymentdue.PaymentDue
                                };
                                context.AddToArchivedAdvertiserPayments(archivedpaymentdue);
                                //Update PaymentDue
                                context.AdvertiserPaymentDues.DeleteObject(currentpaymentdue);
                                context.SaveChanges();
                                //Approve Ad
                                ApproveAd(AdID);
                            }
                            else
                            {
                                currentpaymentdue.Status = pdt.PaymentStatus;
                                currentpaymentdue.PaymentProcess = true;
                            }
                            context.AddToAdvertiserSuccessfulPDTs(advertiserSuccessfulPDT);
                            context.SaveChanges();
                        }
                        else
                        {
                            HiddenLabel.Text = Resources.Resource.AlreadyPaid;

                        }
                    }
                    catch (Exception e1)
                    {

                        string failuremessage = pdt.PayerFirstName + " " +
                        pdt.PayerLastName + "<br/>";
                        failuremessage += Resources.Resource.FailedTransaction + "<br/>";
                        failuremessage += Resources.Resource.FailurePDT;
                        HiddenLabel.Text = failuremessage;
                    }

                }

            }
            else
            {
                using (var context = new AdDatabaseModel.AdDatabaseEntities())
                {
                    try
                    {
                        string[] Custom = pdt.Custom.Split(',');
                        int AdID = (int.Parse(Custom[0]));
                        var result2 = from c in context.AdGenerals
                                      where c.AdID == AdID
                                      select c.UserID;
                        Guid userID = Guid.Parse(result2.FirstOrDefault().ToString());

                        //Insert into HackedPDT
                        var advertiserHackedPDT = new AdDatabaseModel.AdvertiserHackedPDT
                        {
                            PDTID = Admanagment.Helpers.Utility.GetNextSuccessfulPDTID(),
                            GrossTotal = pdt.GrossTotal,
                            Invoice = pdt.InvoiceNumber,
                            PaymentStatus = pdt.PaymentStatus,
                            FirstName = pdt.PayerFirstName,
                            LastName = pdt.PayerLastName,
                            PaymentFee = pdt.PaymentFee,
                            BusinessEmail = pdt.BusinessEmail,
                            TxToken = Request.QueryString.Get("tx"),
                            ReceiverEmail = pdt.ReceiverEmail,
                            ItemName = pdt.ItemName,
                            CurrencyCode = pdt.Currency,
                            TransactionId = pdt.TransactionId,
                            Custom = pdt.Custom,
                            SubscriberId = pdt.SubscriberId,

                            AdvertiserID = userID,
                            AdID = int.Parse(pdt.Custom)
                        };
                        context.AddToAdvertiserHackedPDTs(advertiserHackedPDT);
                        context.SaveChanges();

                        //Email Admin
                        EmailAdmin("HackedPDT", Admanagment.Helpers.Utility.GetNextSuccessfulPDTID());
                        string failuremessage = pdt.PayerFirstName + " " +
                                                pdt.PayerFirstName + "<br/>";
                        failuremessage += Resources.Resource.FailedTransaction + "<br/>";
                        failuremessage += Resources.Resource.FailurePDT;
                        HiddenLabel.Text = failuremessage;
                    }
                    catch (Exception e1)
                    {
                        EmailAdmin("HackedPDT", Admanagment.Helpers.Utility.GetNextSuccessfulPDTID());
                        string failuremessage = pdt.PayerFirstName + " " +
                        pdt.PayerFirstName + "<br/>";
                        failuremessage += Resources.Resource.FailedTransaction + "<br/>";
                        failuremessage += Resources.Resource.FailurePDT;
                        HiddenLabel.Text = failuremessage;
                    }
                }
            }
        }
    }