public CGError loadDBAtPath(String path)
        {
            CGError ret = CGError.OK;

            // check if exists
            if (!File.Exists(path))
            {
                ret = CGError.NOFILE;
            }
            else
            {
                // start with database
                openDBFile(path);
            }

            return(ret);
        }
        public CGError createDBAtPath(String path)
        {
            CGError ret = CGError.OK;

            // check if exists
            if (File.Exists(path))
            {
                ret = CGError.FILEEXISTS;
            }
            else
            {
                // create database file
                openDBFile(path);
                WriteDefaultTable();
            }

            return(ret);
        }
    protected void CancelSubscriptionsButton_Click(object sender, EventArgs e)
    {
        try
            {
                bool cancelconfirmation = false;

                if (String.IsNullOrEmpty(AppCGCustomerCode) == false)
                {

                    //Cancel native
                    CGError servererror = new CGError();
                    cancelconfirmation = CheddarGetter.CancelSubscription(AppCGCustomerCode, servererror);

                    //FAILURE
                    if (String.IsNullOrEmpty(servererror.Code) == false)
                    {
                        //CG.InnerHtml += "<li>ERROR:" + servererror.Message;
                        RadNotification1.Title = "WARNING";
                        RadNotification1.Text = servererror.Message;
                        RadNotification1.Visible = true;
                        RadNotification1.Show();

                        return;
                    }

                }

                if (cancelconfirmation)    //SUCCESSFUL CANCELLATION
                {
                    Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
                    BillingUtil billingutil = new BillingUtil();
                    billingutil.CancelPaidServicesDB(State);

                    CGResponseFlag.Text = cancelconfirmation.ToString();
                }
            }
            catch (Exception)
            {
                throw;
            }
    }
    /// <summary>
    /// Update a customer's subscription
    /// </summary>
    /// <param name="customer">A CustomerPost object with the subscription details to update</param>
    /// <returns>A Customer object with the applied changes</returns>
    public static Customer UpdateSubscription(CustomerPost customer, CGError error)
    {
        Customers customers = new Customers();
            Customer updatedCustomer = new Customer();

            try
            {
                // Create the web request
                string urlBase = "https://cheddargetter.com/xml";
                string urlPath = string.Format("/customers/edit-subscription/productCode/{0}/code/{1}", _ProductCode, customer.Code);

                //note: expiration date must be in MM/YYYY format
                StringBuilder postParamsSB = new StringBuilder();
                postParamsSB.Append(string.Format("planCode={0}", HttpUtility.UrlEncode(customer.PlanCode.ToString().ToUpper())));
                postParamsSB.Append(string.Format("&ccFirstName={0}", HttpUtility.UrlEncode(customer.CCFirstName)));
                postParamsSB.Append(string.Format("&ccLastName={0}", HttpUtility.UrlEncode(customer.CCLastName)));

                if (!string.IsNullOrEmpty(customer.CCNumber))
                {
                    postParamsSB.Append(string.Format("&ccNumber={0}", HttpUtility.UrlEncode(customer.CCNumber)));
                }

                //postParamsSB.Append(string.Format("&ccExpiration={0}", HttpUtility.UrlEncode(string.Format("{0}/{1}", formatMonth(customer.CCExpMonth), customer.CCExpYear))));
                postParamsSB.Append(string.Format("&ccExpiration={0}", HttpUtility.UrlEncode(customer.CCExpiration)));
                if (!string.IsNullOrEmpty(customer.CCCardCode))
                {
                    postParamsSB.Append(string.Format("&ccCardCode={0}", HttpUtility.UrlEncode(customer.CCCardCode)));
                }

                postParamsSB.Append(string.Format("&ccZip={0}", HttpUtility.UrlEncode(customer.CCZip)));

                string result = postRequest(urlBase, urlPath, postParamsSB.ToString());
                XDocument newCustomerXML = XDocument.Parse(result);

                customers = getCustomerList(newCustomerXML);

                if (customers.CustomerList.Count > 0)
                {
                    updatedCustomer = customers.CustomerList[0];
                }
            }

            //shyam
            catch (System.Net.WebException ex)
            {
                processWebException(ex, error);
            }
            //shyam

            catch (Exception ex)
            {
                throw ex;
            }

            return updatedCustomer;
    }
    /// <summary>
    /// Update a customer and their subscription
    /// </summary>
    /// <param name="customer">A CustomerPost object that represents the changes to be updated</param>
    /// <returns>An updated Customer object with the changes applied</returns>
    public static Customer UpdateCustomerAndSubscription(CustomerPost customer, CGError error)
    {
        Customers customers = new Customers();
            Customer updatedCustomer = new Customer();

            try
            {
                // Create the web request
                string urlBase = "https://cheddargetter.com/xml";
                string urlPath = string.Format("/customers/edit/productCode/{0}/code/{1}", _ProductCode, customer.Code);

                if (customer.strPlanCode == null)
                    customer.strPlanCode = customer.PlanCode.ToString().ToUpper();

                string postParams = string.Format(
                    "firstName={0}" +
                    "&lastName={1}" +
                    "&email={2}" +
                    "&company={3}" +
                    "&subscription[planCode]={4}" +
                    "&subscription[ccFirstName]={5}" +
                    "&subscription[ccLastName]={6}" +
                    "&subscription[ccNumber]={7}" +
                    "&subscription[ccExpiration]={8}" +
                    "&subscription[ccCardCode]={9}" +
                    "&subscription[ccZip]={10}" +
                    "&subscription[changeBillDate]={11}",
                    HttpUtility.UrlEncode(customer.FirstName),
                    HttpUtility.UrlEncode(customer.LastName),
                    HttpUtility.UrlEncode(customer.Email),
                    HttpUtility.UrlEncode(customer.Company),
                    HttpUtility.UrlEncode(customer.strPlanCode),
                    HttpUtility.UrlEncode(customer.CCFirstName),
                    HttpUtility.UrlEncode(customer.CCLastName),
                    HttpUtility.UrlEncode(customer.CCNumber),
                    HttpUtility.UrlEncode(customer.CCExpiration),
                    HttpUtility.UrlEncode(customer.CCCardCode),
                    HttpUtility.UrlEncode(customer.CCZip),
                    HttpUtility.UrlEncode(customer.changeBillDate));

                //                    HttpUtility.UrlEncode(string.Format("{0}/{1}", formatMonth(customer.CCExpMonth), customer.CCExpYear)),

                string result = postRequest(urlBase, urlPath, postParams);
                XDocument newCustomerXML = XDocument.Parse(result);

                customers = getCustomerList(newCustomerXML);

                if (customers.CustomerList.Count > 0)
                {
                    updatedCustomer = customers.CustomerList[0];
                }
            }

            //shyam
            catch (System.Net.WebException ex)
            {
                processWebException(ex, error);
            }
            //shyam

            catch (Exception ex)
            {
                throw ex;
            }

            return updatedCustomer;
    }
    /// <summary>
    /// Get a particular customer based on a passed in customer code and your product code
    /// </summary>
    /// <param name="customerCode">A string representing a customer's code in CG </param>
    /// <returns>A associated Customer object for the passed in customer code</returns>
    public static Customer GetCustomer(string customerCode, CGError error)
    {
        Customers customers = new Customers();
            Customer customer = new Customer();

            string urlBase = "https://cheddargetter.com/xml";
            string urlPath = string.Format("/customers/get/productCode/{0}/code/{1}", _ProductCode, customerCode);
            try
            {
                string result = getRequest(urlBase, urlPath);

                XDocument customersXML = XDocument.Parse(result);

                customers = getCustomerList(customersXML);

                if (customers.CustomerList.Count > 0)
                {
                    customer = customers.CustomerList[0];
                }
            }

            catch (WebException ex)
            {
                processWebException(ex, error);

            }

            catch (Exception ex)
            {
                throw ex;
            }

            return customer;
    }
    //shyam
    public static Customer CreateOneTimeInvoice(OneTimeInvoicePost onetimeinvoice, CGError error)
    {
        Customers customers = new Customers();
            Customer editCustomer = new Customer();

            try
            {
                string urlBase = "https://cheddargetter.com/xml";

                string urlPath = string.Format("/invoices/new/productCode/{0}/code/{1}", _ProductCode, onetimeinvoice.InvoiceCharges[0].CustomerCode);
                string postParams = "";

                int i = 0;
                foreach (CustomChargePost charge in onetimeinvoice.InvoiceCharges)
                {
                    if (charge != null)
                    {
                        string tmp = string.Format("&charges[{0}][chargeCode]={1}&charges[{0}][quantity]={2}&charges[{0}][eachAmount]={3}&charges[{0}][description]={4}",
                                                   i++,
                                                   HttpUtility.UrlEncode(charge.ChargeCode),
                                                   HttpUtility.UrlEncode(charge.Quantity.ToString()),
                                                   HttpUtility.UrlEncode(charge.EachAmount.ToString()),
                                                   HttpUtility.UrlEncode(charge.Description));
                        postParams += tmp;
                    }
                }

                System.Diagnostics.Debug.WriteLine(postParams);

                string result = postRequest(urlBase, urlPath, postParams);
                XDocument newCustomerXML = XDocument.Parse(result);

                customers = getCustomerList(newCustomerXML);

                if (customers.CustomerList.Count > 0)
                {
                    editCustomer = customers.CustomerList[0];
                }

            }

            //shyam
            catch (System.Net.WebException ex)
            {
                processWebException(ex, error);
            }
            //shyam

            catch (Exception ex)
            {
                throw ex;
            }

            return editCustomer;
    }
    /// <summary>
    /// Cancel a customer's subscription
    /// </summary>
    /// <param name="customerCode">The customer code of the customer to cancel</param>
    /// <returns>A bool representing the success of the cancel</returns>
    public static bool CancelSubscription(string customerCode, CGError error)
    {
        Customers customers = new Customers();
            Customer editCustomer = new Customer();
            bool canceled = false;

            try
            {
                string urlBase = "https://cheddargetter.com/xml";
                string urlPath = string.Format("/customers/cancel/productCode/{0}/code/{1}", _ProductCode, customerCode);

                string result = getRequest(urlBase, urlPath);
                XDocument newCustomerXML = XDocument.Parse(result);

                customers = getCustomerList(newCustomerXML);

                if (customers.CustomerList.Count > 0)
                {
                    editCustomer = customers.CustomerList[0];
                }

                canceled = true;
            }

            //shyam
            catch (System.Net.WebException ex)
            {
                processWebException(ex, error);
            }
            //shyam

            catch (Exception ex)
            {
                throw ex;
            }

            return canceled;
    }
    /// <summary>
    /// Add an item and set the quantity for a customer
    /// Note: if no quantity is specified then it will increment by 1 by default
    /// </summary>
    /// <param name="customerCode">The customer's code to associate the item with</param>
    /// <param name="itemCode">The item code of the item which we are adding</param>
    /// <param name="quantityToAdd">The number of units to add of this item</param>
    /// <returns>A Customer object reflecting the updated item and quantity</returns>
    public static Customer AddItem(string customerCode, string itemCode, int quantityToAdd, CGError error)
    {
        Customers customers = new Customers();
            Customer editCustomer = new Customer();

            try
            {
                string urlBase = "https://cheddargetter.com/xml";
                string urlPath = string.Format("/customers/add-item-quantity/productCode/{0}/code/{1}/itemCode/{2}", _ProductCode, customerCode, itemCode);
                string postParams = "";

                if (quantityToAdd > 1)
                {
                    postParams = string.Format("quantity={0}", HttpUtility.UrlEncode(quantityToAdd.ToString()));
                }

                string result = postRequest(urlBase, urlPath, postParams);
                XDocument newCustomerXML = XDocument.Parse(result);

                customers = getCustomerList(newCustomerXML);

                //Shyam
                if (customers.ErrorList.Count > 0)
                {
                    foreach (CGError e in customers.ErrorList)
                    {
                        System.Diagnostics.Debug.WriteLine("\n" + e.Code);
                        System.Diagnostics.Debug.WriteLine("\n" + e.AuxCode);
                        System.Diagnostics.Debug.WriteLine("\n" + e.Message);
                    }

                }
                //end Shyam

                if (customers.CustomerList.Count > 0)
                {
                    editCustomer = customers.CustomerList[0];
                }
            }
            catch (System.Net.WebException ex)
            {
                String responseFromServer = ex.Message.ToString() + " ";
                if (ex.Response != null)
                {
                    using (WebResponse response = ex.Response)
                    {
                        Stream data = response.GetResponseStream();
                        using (StreamReader reader = new StreamReader(data))
                        {
                            responseFromServer += reader.ReadToEnd();

                            string[] words = responseFromServer.Split(new char[] { '<' }, 2);
                            System.Diagnostics.Debug.WriteLine("\n\n");
                            responseFromServer = "<" + words[1];
                            System.Diagnostics.Debug.WriteLine(responseFromServer);

                            //System.Diagnostics.Debug.WriteLine(responseFromServer);
                            using (XmlReader xmlreader = XmlReader.Create(new StringReader(responseFromServer)))
                            {
                                XDocument doc = XDocument.Load(xmlreader);
                                String ID = doc.Element("error").Attribute("id").Value;
                                String Code = doc.Element("error").Attribute("code").Value;
                                String AuxCode = doc.Element("error").Attribute("auxCode").Value;
                                String Message = doc.Element("error").Value;

                                error.ID = ID;
                                error.Code = Code;
                                error.AuxCode = AuxCode;
                                error.Message = Message;

                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }

            return editCustomer;
    }
    private void TickAndSelect_CurrentPlan()
    {
        try
        {
            if ((AppType.Contains("native") || AppType.Contains("hybrid")) && (String.IsNullOrEmpty(AppID) == false))
            {
                CGError servererror = new CGError();
                //Get the Native and Web Plan Code for the Customer from CG first.
                Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);
                if (customer_details != null)
                {
                    //Split the code which is number_NATIVE_MONTHLY_BASIC
                    string[] words = customer_details.Subscriptions[0].SubscriptionsPlans[0].Code.Split(new char[] { '_' }, 3);

                    if (words.Length < 2)
                        return;

                    HideAllNativeTicks();

                    if (String.Compare("MONTHLY", words[1], true) == 0)
                    {
                        NativePricingMultiPage.SelectedIndex = 0;
                        RadTabStripNative.SelectedIndex = 0;

                        if (String.Compare("BASIC", words[2], true) == 0)
                        {
                            Tick1.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_MONTHLY_BASIC;
                            System.Diagnostics.Debug.WriteLine("NATIVE_MONTHLY_BASIC");
                        }

                        if (String.Compare("PRO", words[2], true) == 0)
                        {
                            Tick2.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_MONTHLY_PRO;
                            System.Diagnostics.Debug.WriteLine("NATIVE_MONTHLY_PRO");
                        }

                        if (String.Compare("PREMIUM", words[2], true) == 0)
                        {
                            Tick3.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_MONTHLY_PREMIUM;
                            System.Diagnostics.Debug.WriteLine("NATIVE_MONTHLY_PREMIUM");
                        }

                    }

                    if (String.Compare("YEARLY", words[1], true) == 0)
                    {
                        NativePricingMultiPage.SelectedIndex = 1;
                        RadTabStripNative.SelectedIndex = 1;

                        if (String.Compare("BASIC", words[2], true) == 0)
                        {
                            Tick4.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_YEARLY_BASIC;
                            System.Diagnostics.Debug.WriteLine("NATIVE_YEARLY_BASIC");
                        }

                        if (String.Compare("PRO", words[2], true) == 0)
                        {
                            Tick5.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_YEARLY_PRO;
                            System.Diagnostics.Debug.WriteLine("NATIVE_YEARLY_PRO");
                        }

                        if (String.Compare("PREMIUM", words[2], true) == 0)
                        {
                            Tick6.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_YEARLY_PREMIUM;
                            System.Diagnostics.Debug.WriteLine("NATIVE_YEARLY_PREMIUM");
                        }

                    }

                    if (String.Compare("NONPROFIT", words[1], true) == 0)
                    {
                        NativePricingMultiPage.SelectedIndex = 2;
                        RadTabStripNative.SelectedIndex = 2;

                        if (String.Compare("BASIC", words[2], true) == 0)
                        {
                            Tick7.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_NONPROFIT_BASIC;
                            System.Diagnostics.Debug.WriteLine("NATIVE_NONPROFIT_BASIC");
                        }

                        if (String.Compare("PRO", words[2], true) == 0)
                        {
                            Tick8.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_NONPROFIT_PRO;
                            System.Diagnostics.Debug.WriteLine("NATIVE_NONPROFIT_PRO");
                        }

                        if (String.Compare("PREMIUM", words[2], true) == 0)
                        {
                            Tick9.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.NATIVE_NONPROFIT_PREMIUM;
                            System.Diagnostics.Debug.WriteLine("NATIVE_NONPROFIT_PREMIUM");
                        }

                    }
                } //(customer_details != null)
            }

            if (AppType.Contains("web") && (String.IsNullOrEmpty(AppID) == false))
            {
                CGError servererror = new CGError();
                Customer web_customer_details = CheddarGetter.GetCustomer(AppID, servererror);
                if (web_customer_details != null)
                {
                    string[] words = web_customer_details.Subscriptions[0].SubscriptionsPlans[0].Code.Split(new char[] { '_' }, 3);

                    if (words.Length < 2)
                        return;

                    HideAllWebTicks();

                    if (String.Compare("MONTHLY", words[1], true) == 0)
                    {
                        WebPricingMultiPage.SelectedIndex = 0;
                        RadTabStrip1.SelectedIndex = 0;

                        if (String.Compare("BASIC", words[2], true) == 0)
                        {
                            WTick1.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_MONTHLY_BASIC;
                            System.Diagnostics.Debug.WriteLine("WEB_MONTHLY_BASIC");
                        }

                        if (String.Compare("PRO", words[2], true) == 0)
                        {
                            WTick2.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_MONTHLY_PRO;
                            System.Diagnostics.Debug.WriteLine("WEB_MONTHLY_PRO");
                        }

                        if (String.Compare("PREMIUM", words[2], true) == 0)
                        {
                            WTick3.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_MONTHLY_PREMIUM;
                            System.Diagnostics.Debug.WriteLine("WEB_MONTHLY_PREMIUM");
                        }
                    }

                    if (String.Compare("YEARLY", words[1], true) == 0)
                    {
                        WebPricingMultiPage.SelectedIndex = 1;
                        RadTabStrip1.SelectedIndex = 1;

                        if (String.Compare("BASIC", words[2], true) == 0)
                        {
                            WTick4.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_YEARLY_BASIC;
                            System.Diagnostics.Debug.WriteLine("WEB_YEARLY_BASIC");
                        }

                        if (String.Compare("PRO", words[2], true) == 0)
                        {
                            WTick5.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_YEARLY_PRO;
                            System.Diagnostics.Debug.WriteLine("WEB_YEARLY_PRO");
                        }

                        if (String.Compare("PREMIUM", words[2], true) == 0)
                        {
                            WTick6.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_YEARLY_PREMIUM;
                            System.Diagnostics.Debug.WriteLine("WEB_YEARLY_PREMIUM");
                        }

                    }

                    if (String.Compare("NONPROFIT", words[1], true) == 0)
                    {
                        WebPricingMultiPage.SelectedIndex = 2;
                        RadTabStrip1.SelectedIndex = 2;

                        if (String.Compare("BASIC", words[2], true) == 0)
                        {
                            WTick7.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_NONPROFIT_BASIC;
                            System.Diagnostics.Debug.WriteLine("WEB_NONPROFIT_BASIC");
                        }

                        if (String.Compare("PRO", words[2], true) == 0)
                        {
                            WTick8.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_NONPROFIT_PRO;
                            System.Diagnostics.Debug.WriteLine("WEB_NONPROFIT_PRO");
                        }

                        if (String.Compare("PREMIUM", words[2], true) == 0)
                        {
                            WTick9.Visible = true;
                            SelectedPlanCode = PlanCodeEnum.WEB_NONPROFIT_PREMIUM;
                            System.Diagnostics.Debug.WriteLine("WEB_NONPROFIT_PREM");
                        }

                    }

                }
            }

        }
        catch (Exception)
        {

            throw;
        }
    }
    private Boolean CG_CreateFreeCustomerAndInvoices()
    {
        try
        {
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];

            //Create a new customer
            CustomerPost newCustomer = new CustomerPost();

            newCustomer.Company = CompanyTextBox.Text;
            newCustomer.FirstName = FirstNameTextBox.Text;
            newCustomer.LastName = LastNameTextBox.Text;
            newCustomer.Email = EmailTextBox.Text;
            newCustomer.CCFirstName = CCFirstNameTextbox.Text;
            newCustomer.CCLastName = CCLastNameTextBox.Text;
            newCustomer.CCNumber = CCNumberTextBox.Text;
            newCustomer.CCExpiration = CCExpirationTextBox.Text;
            newCustomer.CCZip = CCZipTextBox.Text;
            newCustomer.CCCardCode = CCCardCodeTextBox.Text;
            newCustomer.Code = State["application_id"].ToString();

           //For Branding purposes create appropriate branding code.
            if (State["SelectedDeviceType"].ToString() == Constants.ANDROID_PHONE)
            {
                newCustomer.PlanCode =  PlanCodeEnum.ANDROID_BRANDING;
            }
            else
            {
                if (State["SelectedDeviceType"].ToString() == Constants.IPHONE)
                {
                    newCustomer.PlanCode = PlanCodeEnum.IOS_BRANDING;
                }
                else
                {
                    RadNotification1.Title = "WARNING";
                    RadNotification1.Text = "This application has no device type.";
                    RadNotification1.Visible = true;
                    RadNotification1.Show();
                    return false;
                }
            }

            //Send it to the server
            CGError servererror = new CGError();
            Customer returnCustomer = CheddarGetter.CreateCustomer(newCustomer, servererror);

            //FAILURE
            if (String.IsNullOrEmpty(servererror.Code) == false)
            {

                //string clickHandler = "this.disabled = false; this.value=\'Submit\'; ";
                // SubmitButton.Attributes.Add("onclick", clickHandler);

                SubmitButton.Enabled = true;
                SubmitButton.Text = "Submit";

                //CG.InnerHtml += "<li>ERROR:" + servererror.Message;
                RadNotification1.Title = "WARNING";
                RadNotification1.Text = servererror.Message;
                RadNotification1.Visible = true;
                RadNotification1.Show();

                return false;
            }

            //SUCCESS
            if (String.IsNullOrEmpty(returnCustomer.Code) == false)
            {
                AppCGCustomerCode = returnCustomer.Code;
            }

            // IF SUCCESSFULLY ABLE TO CREATE THE FREE NATIVE CUSTOMER THEN KICK OFF A ONE TIME INVOICE FOR BRANDING

            OneTimeInvoicePost myonetimeinvoice = new OneTimeInvoicePost();

            myonetimeinvoice.InvoiceCharges = new CustomChargePost[1];

            int number_of_charges = 0;
            CustomChargePost mycustom1 = new CustomChargePost();

            mycustom1.CustomerCode = AppCGCustomerCode;
            mycustom1.Description = "Branding";
            mycustom1.ChargeCode = "BRANDING ";
            mycustom1.EachAmount = 0;
            mycustom1.Quantity = 0;

            if ((State["SelectedDeviceType"].ToString() == Constants.ANDROID_PHONE || State["SelectedDeviceType"].ToString() == Constants.ANDROID_TABLET) && (String.IsNullOrEmpty(AppCGCustomerCode) == false))
            {
                mycustom1.ChargeCode += "- ANRDOID";
                mycustom1.CustomerCode = AppCGCustomerCode;
                mycustom1.Quantity = 1;
                mycustom1.EachAmount += 99;
                mycustom1.Description += "- Android";
            }

            if ((State["SelectedDeviceType"].ToString() == Constants.IPHONE || State["SelectedDeviceType"].ToString() == Constants.IPAD) && (String.IsNullOrEmpty(AppCGCustomerCode) == false))
            {
                mycustom1.ChargeCode += "- iOS";
                mycustom1.Quantity = 1;
                mycustom1.EachAmount += 99;
                mycustom1.Description += "- iOS";
            }

            myonetimeinvoice.InvoiceCharges[number_of_charges] = new CustomChargePost();
            myonetimeinvoice.InvoiceCharges[number_of_charges] = mycustom1;

            CGError servererror2 = new CGError();
            //SERVER CALL TO THE ONE TIME INVOICE for both charges at once.
            Customer returnCustomer2 = CheddarGetter.CreateOneTimeInvoice(myonetimeinvoice, servererror2);

            if (String.IsNullOrEmpty(servererror2.Code) == false)
            {
                //CG.InnerHtml += "<li>ERROR:" + servererror2.Message;

                SubmitButton.Enabled = true;
                SubmitButton.Text = "Submit";

                //string clickHandler = "this.disabled = false; this.value=\'Submit\'; ";
                //SubmitButton.Attributes.Add("onclick", clickHandler);

                RadNotification1.Title = "WARNING";
                RadNotification1.Text = servererror2.Message;
                RadNotification1.Visible = true;
                RadNotification1.Show();

                return false;
            }

            //Store in the PaidServicesDB
            BillingUtil billingutil = new BillingUtil();

            //Record the new SKU but do not turn on the 'paid' field as yet.

            string confirm = returnCustomer2.Subscriptions[0].Invoices[1].PaidTransactionId.ToString();

            string sku = returnCustomer2.Subscriptions[0].SubscriptionsPlans[0].Code.ToString();
            billingutil.StorePaidServicesDB(confirm,sku,State,false);

            //Enable 10 day grace for App store Approval.
            Util util = new Util();
            util.SetFreeProductionExpiration(State, DateTime.Now.ToUniversalTime().AddDays(10.0D));

            //Send Email to Support.
            System.Text.StringBuilder body = new System.Text.StringBuilder("Customer Username: "******"Username"].ToString() + "\n");
            body.Append("App Name: " + State["SelectedApp"].ToString() + "\n");
            body.Append("\n-- ViziApps Support");
            Email email = new Email();
            string status = email.SendEmail(State,  HttpRuntime.Cache["TechSupportEmail"].ToString(),  HttpRuntime.Cache["TechSupportEmail"].ToString(),"", "", "Customer submitted App for App Store Preparation", body.ToString(), "", false);

            return true;

        }//end try

        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message.ToString() + ex.StackTrace.ToString());

        }

        return false;
    }
    /// <summary>
    /// Add a customer charge for a customer
    /// </summary>
    /// <param name="customCharge">A CustomerChargePost object with the customer charge and customer code</param>
    /// <returns>A Customer object with the reflected custom charge</returns>
    public static Customer AddCustomCharge(CustomChargePost customCharge, CGError error)
    {
        Customers customers = new Customers();
            Customer editCustomer = new Customer();

            try
            {
                string urlBase = "https://cheddargetter.com/xml";
                //string urlPath = string.Format("/customers/set-item-quantity/productCode/{0}/code/{1}/itemCode/{2}", _ProductCode, customCharge.CustomerCode, customCharge.ItemCode);
                string urlPath = string.Format("/customers/add-charge/productCode/{0}/code/{1}", _ProductCode, customCharge.CustomerCode);
                string postParams = string.Format(
                  "chargeCode={0}" +
                  "&quantity={1}" +
                  "&eachAmount={2}" +
                  "&description={3}",
                  HttpUtility.UrlEncode(customCharge.ChargeCode),
                  HttpUtility.UrlEncode(customCharge.Quantity.ToString()),
                  HttpUtility.UrlEncode(customCharge.EachAmount.ToString()),
                  HttpUtility.UrlEncode(customCharge.Description));

                string result = postRequest(urlBase, urlPath, postParams);
                XDocument newCustomerXML = XDocument.Parse(result);

                customers = getCustomerList(newCustomerXML);

                if (customers.CustomerList.Count > 0)
                {
                    editCustomer = customers.CustomerList[0];
                }

            }

            //shyam
            catch (System.Net.WebException ex)
            {
                processWebException(ex, error);
            }
            //shyam

            catch (Exception ex)
            {
                new Exception(ex.Message + ": " + ex.StackTrace);
            }

            return editCustomer;
    }
    private void page_refresh()
    {
        try
        {
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
            //All three are Null then nothing to show.
            if (State["application_id"] == null)
            {
                showhistory.Visible = false;
            }
            else
            {
                BillingHistoryData BillingHistory = new BillingHistoryData();
                BillingHistory.Subscriptions = new SortedList();
                BillingHistory.Invoices = new SortedList();

                    showhistory.Visible = false;
                    AppID = State["application_id"].ToString();
                    CGError servererror = new CGError();
                    Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);

                    if (String.IsNullOrEmpty(servererror.Code) == false)
                    {
                        RadNotification1.Title = "WARNING";

                        if (servererror.Code.IndexOf("NotFound") >= 0)
                            RadNotification1.Text = "No billing history found for the App";
                        else
                            RadNotification1.Text = servererror.Message;

                        RadNotification1.Visible = true;
                        RadNotification1.Show();

                        return;
                    }

                    if ((DateTime.Compare(customer_details.CreatedDateTime, BillingHistory.CreatedDateTime) > 0))
                    {
                        BillingHistory.CreatedDateTime = customer_details.CreatedDateTime;
                    }

                    BillingHistory.FirstName = customer_details.FirstName;
                    BillingHistory.LastName = customer_details.LastName;
                    BillingHistory.CreatedDateTime = customer_details.CreatedDateTime;
                    BillingHistory.ModifiedDateTime = customer_details.ModifiedDateTime;
                    BillingHistory.Email = customer_details.Email;

                    if ((DateTime.Compare(customer_details.CreatedDateTime, BillingHistory.CreatedDateTime) > 0))
                    {
                        BillingHistory.CreatedDateTime = customer_details.CreatedDateTime;
                    }

                    BillingHistory.ModifiedDateTime = customer_details.ModifiedDateTime;
                    BillingHistory.Email = customer_details.Email;
                    int sub = 0;
                    int delta_time = 30;

                    foreach (Subscription s in customer_details.Subscriptions)
                    {
                        if (sub == 0)
                        {
                            BillingHistory.CCType = s.CCType;
                            BillingHistory.CCLastFour = s.CCLastFour;
                            BillingHistory.CCFirstName = s.CCFirstName;
                            BillingHistory.CCLastName = s.CCLastName;
                            BillingHistory.CCZip = s.CCZip;
                        }

                        if (BillingHistory.Subscriptions.Contains(s.CreatedDateTime) == false)
                            BillingHistory.Subscriptions.Add(s.CreatedDateTime, s);
                        else
                        {
                            s.CreatedDateTime = s.CreatedDateTime.AddSeconds(delta_time);
                            BillingHistory.Subscriptions.Add(s.CreatedDateTime, s);
                        }

                        foreach (Invoice i in s.Invoices)
                        {
                            if (BillingHistory.Invoices.Contains(i.CreatedDateTime) == false)
                                BillingHistory.Invoices.Add(i.CreatedDateTime, i);
                            else
                            {
                                i.CreatedDateTime = i.CreatedDateTime.AddSeconds(delta_time++);
                                BillingHistory.Invoices.Add(i.CreatedDateTime, i);
                            }

                        }

                        sub++;
                    }

                //Start acinfo table
                string tempInnerHTML = "";
                tempInnerHTML += "<tr><td colspan=4 class=\"table_headrow\">Billing History for " + BillingHistory.FirstName + "  " + BillingHistory.LastName + "</td></tr>";
                tempInnerHTML += "<tr><td class=\"table_itemtitle\">Customer Since:</td><td class=\"table_item\">" + BillingHistory.CreatedDateTime + "</td>";
                tempInnerHTML += "<td class=\"table_itemtitle\">Last Modified:</td><td class=\"table_item\">" + BillingHistory.ModifiedDateTime + "</td></tr>";
                acinfo.InnerHtml = tempInnerHTML;
                //End acinfo table

                //Build the CCDetails table
                tempInnerHTML = "";
                tempInnerHTML += "<tr><td colspan=5 class=\"table_headrow\">Credit Card on File</td></tr>";
                tempInnerHTML += "<tr class=\"table_itemtitle\"><td>Name</td><td>Type<td>Last 4 Digits</td><td>Zip Code </td><td>Most Recent Bill</td></tr>";
                tempInnerHTML += "<tr class=\"table_item\"><td>" + BillingHistory.CCFirstName + " " + BillingHistory.CCLastName + "</td>";
                tempInnerHTML += "<td>" + BillingHistory.CCType.ToUpper() + "</td>";
                tempInnerHTML += "<td>" + BillingHistory.CCLastFour + "</td>";
                tempInnerHTML += "<td>" + BillingHistory.CCZip + "</td>";
                tempInnerHTML += "<td >" + BillingHistory.CreatedDateTime + "</td></tr>";
                ccdetails.InnerHtml = tempInnerHTML;
                //End the CCDetails table

                //Build the Invoices Table
                tempInnerHTML = "";
                tempInnerHTML += "<tr><td colspan=6 class=\"table_headrow\">Invoices</td></tr>";
                tempInnerHTML += "<tr class=\"table_itemtitle\"><td>Invoice No.</td><td>Created Date</td><td>Billing Date</td><td>Type</td><td>Transaction Id</td><td>Total Charges</td></tr>";

                for (int c = 0; c < BillingHistory.Invoices.Count; c++)
                {
                    Boolean freeinvoice = false;
                    float totalcharge = 0;
                    string mycharges = "";
                    string str_item = "";

                    Invoice inv = (Invoice)BillingHistory.Invoices.GetByIndex(c);

                    mycharges = "<table class=\"singleinvoicetable\"><tr><td><h2> INVOICE " + inv.Number + "</h2></td><td class=\"small_gap\"></td><td class=\"small_gap\"></td><td class=\"small_gap\"></td><td>Billed on " + inv.BillingDateTime + "<br></td></tr></table>";
                    mycharges += "<table class=\"singleinvoicetable\">";
                    mycharges += "<caption> Charges </caption>";
                    mycharges += "<tr class=\"table_headrow\"><td>Item</td><td>Type</td><td>Code</td><td>Date</td><td>Quantity</td><td>Each</td><td>Amount</td></tr>";

                    foreach (Charge ch in inv.Charges)
                    {

                        if (ch.Code.Contains("BRANDING")  && ch.EachAmount == 0.00)
                            freeinvoice = true;

                        if (!freeinvoice)
                        {
                            if (ch.EachAmount < 0)
                                str_item = "Credit";
                            else
                                str_item = "Subscription";

                            mycharges += "<tr><td class=\"singleinvoicetableitem\">" + str_item + "<td class=\"singleinvoicetableitem\">" + ch.Type + "</td><td class=\"singleinvoicetableitem\">" + ch.Code + "</td><td class=\"singleinvoicetableitem\">" + ch.CreatedDateTime + "</td><td class=\"singleinvoicetableitem\">" + ch.Quantity + "</td><td class=\"singleinvoicetableitem\">" + ch.EachAmount + "</td><td class=\"singleinvoicetableitem\">" + (ch.EachAmount * ch.Quantity) + "</td></tr>";

                            if (String.IsNullOrEmpty(ch.Description) == false)
                                mycharges += "<tr class=\"singleinvoicedescription\"><td colspan=6>" + ch.Description + "</td></tr>";

                            totalcharge += ch.EachAmount;
                        }
                    }

                    if (!freeinvoice)
                    {
                        mycharges += "<tr><td colspan=7><hr></td></tr>";
                        mycharges += "<tr><td></td><td></td><td></td><td></td><td></td><td class=\"singleinvoicetableitem\">Total </td><td class=\"singleinvoicetableitem\">" + totalcharge + "</td>";
                        mycharges += "</table>";

                        if (inv.Transactions.Count > 0)
                        {
                            mycharges += "<table class=\"singleinvoicetable\">";
                            mycharges += "<caption> Transactions</caption>";
                            mycharges += "<tr class=\"table_headrow\"><td>Transaction ID</td><td>Type</td><td>Time</td><td>Response</td><td>Amount</td></tr>";
                            //Transactions
                            string tr_type = "";
                            foreach (Transaction tr in inv.Transactions)
                            {
                                if (tr.amount < 0)
                                {
                                    tr_type = "Refund";
                                    mycharges += "<tr><td class=\"singleinvoicetableitem\">" + tr.ID + "<td class=\"cancelwarning\">" + tr_type + "<td class=\"singleinvoicetableitem\">" + tr.transactedDatetime + "</td><td class=\"singleinvoicetableitem\">" + tr.response + "</td><td class=\"singleinvoicetableitem\">" + tr.amount + "</td></tr>";
                                }
                                else
                                {
                                    tr_type = "Charge";
                                    mycharges += "<tr><td class=\"singleinvoicetableitem\">" + tr.ID + "<td class=\"singleinvoicetableitem\">" + tr_type + "<td class=\"singleinvoicetableitem\">" + tr.transactedDatetime + "</td><td class=\"singleinvoicetableitem\">" + tr.response + "</td><td class=\"singleinvoicetableitem\">" + tr.amount + "</td></tr>";
                                }
                            }
                            mycharges += "</table>";
                        }

                        tempInnerHTML += "<tr class=\"table_item\"><td> <a href=\"#\" id=\"trigger" + inv.Number + "\">" + inv.Number + "</a></td><td>" + inv.CreatedDateTime.ToString("MM/dd/yyyy hh:mm tt") + "</td><td>" + inv.BillingDateTime.ToString("MM/dd/yyyy hh:mm tt") + "</td><td>" + inv.Type + "</td><td>" + inv.PaidTransactionId + "</td><td>" + totalcharge.ToString("0.00") + "</td><td><div class=\"invoicepopup\"  id=\"popup" + inv.Number + "\">" + mycharges + "</div>";
                        tempInnerHTML += "<script type=\"text/javascript\"> $(function () {  var moveLeft = 30; var moveDown = -120; $('a#trigger" + inv.Number + "').hover(function (e) {  $('div#popup" + inv.Number + "').show();}, function () { $('div#popup" + inv.Number + "').hide(); }); $('a#trigger" + inv.Number + "').mousemove(function (e) {$(\"div#popup" + inv.Number + "\").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft); }); }); </script>";
                    }

                }
                invoices.InnerHtml = tempInnerHTML;
                //End the Invoices Table

                //Build Subscriptions Table
                tempInnerHTML = "";
                tempInnerHTML += "<tr><td colspan=5 class=\"table_headrow\">Subscriptions</td></tr>";
                tempInnerHTML += "<tr class=\"table_itemtitle\"><td>Created On</td><td>Plan Name<td>Description</td><td>Recurring Charge</td><td>Status</td></tr>";
                string SubStatus = "";
                for (int s = 0; s < BillingHistory.Subscriptions.Count; s++)
                {
                    Subscription subs = (Subscription)BillingHistory.Subscriptions.GetByIndex(s);

                    SubStatus = "-";

                    if ((s == (BillingHistory.Subscriptions.Count - 1)))
                        SubStatus = "Active";

                    if (subs.CanceledDateTime.HasValue)
                        SubStatus = "Cancelled on " + subs.CanceledDateTime.ToString();

                    //if (subs.SubscriptionsPlans[0].Name.IndexOf("FREE") < 0)

                    if (subs.SubscriptionsPlans[0].RecurringChargeCode.Contains("BRANDING") == false)
                        tempInnerHTML += "<tr class=\"table_item\"><td >" + subs.CreatedDateTime + "</td><td>" + subs.SubscriptionsPlans[0].Name + "</td><td>" + subs.SubscriptionsPlans[0].Description + "</td><td>" + subs.SubscriptionsPlans[0].RecurringChargeAmount + "</td><td>" + SubStatus + "</td></tr>";

                }
                subscriptions.InnerHtml = tempInnerHTML;
                //End Subscriptions Table

            }//else

            //Make Visible the history DIV
            showhistory.Visible = true;

        }//try
        catch (ArgumentException argex)
        {
            //Ignore it
        }
        catch (global::System.Exception)
        {
            throw;
        }
    }
    private void page_refresh()
    {
        try
            {
                Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
                string tempInnerHTML = "";
                string CancelInfo = "";

                AppID = State["application_id"].ToString();

                if (String.IsNullOrEmpty(AppID) == false)
                {
                    CGError servererror = new CGError();
                    Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);

                    if (String.IsNullOrEmpty(servererror.Code) == false)
                    {
                        cgbilling.Visible = false;
                        CancelSubscriptionsButton.Visible = false;

                        RadNotification1.Title = "WARNING";

                        if (servererror.Code.IndexOf("NotFound") >= 0)
                            RadNotification1.Text = "No publishing service found for the App";
                        else
                            RadNotification1.Text = servererror.Message;

                        RadNotification1.Visible = true;
                        RadNotification1.Show();

                        return;
                    }

                    cgbilling.Visible = true;

                    AppCGCustomerCode = customer_details.Code;

                    int sub = 0;
                    foreach (Subscription s in customer_details.Subscriptions)
                    {
                        if (sub == 0)
                        {
                            if (s.CanceledDateTime != null)
                            {
                                plancancelled = true;
                                CancelInfo = s.CanceledDateTime.ToString();
                            }

                            tempInnerHTML += "<table class=\"cancelpagemaintable\">";
                            foreach (SubscriptionPlan p in s.SubscriptionsPlans)
                            {
                                if (p.Name.IndexOf("FREE") < 0)    //Only if not FREE
                                {
                                    tempInnerHTML += "<tr><td colspan=2 class=\"table_headrow\">Current Publishing Service</td></tr>";
                                    tempInnerHTML += "<tr><td class=\"table_itemtitle\">Publishing Service: </td><td class=\"table_item\">" + p.Name + "</td></tr>";
                                    tempInnerHTML += "<tr><td class=\"table_itemtitle\">Recurring Charge: </td><td class=\"table_item\">" + p.RecurringChargeAmount + "</td></tr>";
                                }
                                else
                                {
                                    cgbilling.Visible = false;
                                    CancelSubscriptionsButton.Visible = false;

                                    RadNotification1.Title = "WARNING";
                                    RadNotification1.Text = "No publishing service found for the App";
                                    RadNotification1.Visible = true;
                                    RadNotification1.Show();
                                    return;
                                }

                            }
                            sub++;

                            if (plancancelled == true)
                            {
                                tempInnerHTML += "<tr><td colspan=4 class=\"cancelwarning\">Cancelled on:" + CancelInfo + "<br><br></td></tr>";

                                CancelSubscriptionsButton.Visible = false;
                            }
                            else
                                CancelSubscriptionsButton.Visible = true;

                            tempInnerHTML += "</table>";
                        }
                        cgbilling.InnerHtml = tempInnerHTML;
                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
    }
    private void page_refresh()
    {
        try
        {
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
            Util util = new Util();

            USERINFO.Visible = true;
            HideAllNativeTicks();
            HideAllWebTicks();
            SelectedPlanCode = 0;

            RadTabStripNative.SelectedIndex = 0;
            RadTabStrip1.SelectedIndex = 0;

            if (State["SelectedAppType"].ToString() == Constants.WEB_APP_TYPE)
            {
                RadMultiPageMaster.Visible = true;
                RadMultiPageMaster.SelectedIndex = 1;
                RadPageNativeSection.Visible = false;
                RadPageWebSection.Visible = true;
                WebPricingMultiPage.SelectedIndex = 0;
                RadTabStrip1.SelectedIndex = 0;
            }
            else
            {
                RadMultiPageMaster.Visible = true;
                RadMultiPageMaster.SelectedIndex = 0;
                RadPageNativeSection.Visible = true;
                RadPageWebSection.Visible = false;
                NativePricingMultiPage.SelectedIndex = 0;
                RadTabStripNative.SelectedIndex = 0;
            }

            if (String.IsNullOrEmpty(AppID) == false)
            {

                CGError servererror = new CGError();
                Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);  // IF BRANDING WAS DONE THIS SHOULD RETURN FINE

                if ((String.IsNullOrEmpty(servererror.Code) == true) && (customer_details.Subscriptions[0].SubscriptionsPlans[0].Code.Contains("BRANDING") == false))
                {
                    //There is already a NON FREE PLAN for this App
                    USERINFO.Visible = false;
                    RadMultiPageMaster.Visible = false;
                    RadNotification1.Title = "WARNING";
                    RadNotification1.Text = "This application has already been subscribed to a publishing service";
                    RadNotification1.Visible = true;
                    RadNotification1.Show();
                    return;
                }

                if (String.Compare(customer_details.Code, AppID, false) == 0)
                {
                    CompanyTextBox.Text = customer_details.Company;
                    EmailTextBox.Text = customer_details.Email;
                    FirstNameTextBox.Text = customer_details.FirstName;
                    LastNameTextBox.Text = customer_details.LastName;

                    foreach (Subscription s in customer_details.Subscriptions)
                    {
                        CCFirstNameTextbox.Text = s.CCFirstName;
                        CCLastNameTextBox.Text = s.CCLastName;
                        CCZipTextBox.Text = s.CCZip;
                    }
                }

            }

            PreFillBillingFormDetails();

        }
        catch (Exception)
        {

            throw;
        }
    }
    private Boolean CG_ModifyCustomer()
    {
        try
        {
            //Create a new customer
            CustomerPost newCustomer = new CustomerPost();

            newCustomer.Company = CompanyTextBox.Text;
            newCustomer.FirstName = FirstNameTextBox.Text;
            newCustomer.LastName = LastNameTextBox.Text;
            newCustomer.Email = EmailTextBox.Text;

            //Extra fields required for nonFREE plans
            newCustomer.CCFirstName = CCFirstNameTextbox.Text;
            newCustomer.CCLastName = CCLastNameTextBox.Text;
            newCustomer.CCNumber = CCNumberTextBox.Text;
            newCustomer.CCExpiration = CCExpirationTextBox.Text;
            newCustomer.CCZip = CCZipTextBox.Text;
            newCustomer.CCCardCode = CCCardCodeTextBox.Text;

            if (SelectedPlanCode != 0)
            {
                    newCustomer.PlanCode = SelectedPlanCode;                 //The updated plan code goes here
                    newCustomer.Code = AppID;                           //existing customer code
                    System.Diagnostics.Debug.WriteLine("using customer code" + newCustomer.Code + "To modifyplan to " + newCustomer.PlanCode);

                    //Send it to the server
                    CGError servererror = new CGError();
                    Customer returnCustomer = CheddarGetter.UpdateCustomerAndSubscription(newCustomer, servererror);

                    //FAILURE
                    if (String.IsNullOrEmpty(servererror.Code) == false)
                    {
                        //CG.InnerHtml += "<li>ERROR:" + servererror.Message;
                        RadNotification1.Title = "WARNING";
                        RadNotification1.Text = servererror.Message;
                        RadNotification1.Visible = true;
                        RadNotification1.Show();
                        return false;
                    }

                    //SUCCESS
                    if (String.IsNullOrEmpty(returnCustomer.Code) == false)
                    {
                        AppCGCustomerCode = returnCustomer.Code;
                        CGResponseFlag.Text = AppCGCustomerCode;

                        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
                        BillingUtil billingutil = new BillingUtil();
                        string confirm = returnCustomer.Subscriptions[0].Invoices[1].PaidTransactionId.ToString();

                        string sku = returnCustomer.Subscriptions[0].SubscriptionsPlans[0].Code.ToString();

                        billingutil.UpdatePaidServicesDB(confirm,sku,State);
                    }
                }

            return true;

        }//end try
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
            throw;
        }
    }
    private void CG_CreateCustomer()
    {
        try
        {
            //Create a new customer
            CustomerPost newCustomer = new CustomerPost();

            newCustomer.Company = CompanyTextBox.Text;
            newCustomer.FirstName = FirstNameTextBox.Text;
            newCustomer.LastName = LastNameTextBox.Text;
            newCustomer.Email = EmailTextBox.Text;

            //Extra fields required for nonFREE plans
            newCustomer.CCFirstName = CCFirstNameTextbox.Text;
            newCustomer.CCLastName = CCLastNameTextBox.Text;
            newCustomer.CCNumber = CCNumberTextBox.Text;
            newCustomer.CCExpiration = CCExpirationTextBox.Text;
            newCustomer.CCZip = CCZipTextBox.Text;
            newCustomer.CCCardCode = CCCardCodeTextBox.Text;

             if (SelectedPlanCode != 0)
             {
                 newCustomer.PlanCode = SelectedPlanCode;
                    newCustomer.Code = AppID;

                    //Send it to the server
                    CGError servererror = new CGError();
                    Customer returnCustomer = CheddarGetter.CreateCustomer(newCustomer, servererror);

                    //FAILURE
                    if (String.IsNullOrEmpty(servererror.Code) == false)
                    {
                        //CG.InnerHtml += "<li>ERROR:" + servererror.Message;
                        RadNotification1.Title = "WARNING";
                        RadNotification1.Text = servererror.Message;
                        RadNotification1.Visible = true;
                        RadNotification1.Show();

                        string clickHandler = "this.disabled = false; this.value=\'Submit\'; ";
                        SubmitButton.Attributes.Add("onclick", clickHandler);

                        return;
                    }

                    //SUCCESS
                    if (String.IsNullOrEmpty(returnCustomer.Code) == false)
                    {
                        AppCGCustomerCode = returnCustomer.Code;

                        CGResponseFlag.Text = AppCGCustomerCode;

                        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];

                        //If the App was submitted to a store [native & hybrid] then just update the paid_services table entry with status to paid.
                        //If not [web apps] create a new entry in paid_services and update status to paid.
                        String app_name = State["SelectedApp"].ToString();
                        BillingUtil billingutil = new BillingUtil();
                        if (billingutil.IsAppStoreSubmissionPaid(State, app_name))
                        {
                            string confirm = returnCustomer.Subscriptions[0].Invoices[1].PaidTransactionId.ToString();

                            string sku = returnCustomer.Subscriptions[0].SubscriptionsPlans[0].Code.ToString();

                            billingutil.UpdatePaidServicesDB(confirm,sku, State);
                        }
                        else
                        {
                            string confirm = returnCustomer.Subscriptions[0].Invoices[1].PaidTransactionId.ToString();
                            string sku = returnCustomer.Subscriptions[0].SubscriptionsPlans[0].Code.ToString();
                            billingutil.StorePaidServicesDB(confirm, sku, State, true);
                        }

                    }
                }

        }//end try
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
            throw;
        }
    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        Util util = new Util();

        try
        {
            System.Diagnostics.Debug.WriteLine("SelectedPlanCode={0} ", SelectedPlanCode);

            if (SelectedPlanCode == 0)  //Nothing selected at all
            {

                RadNotification1.Title = "WARNING";
                RadNotification1.Text = "Please select atleast one publishing service";
                RadNotification1.Visible = true;
                RadNotification1.Show();
            }
            else
            {
                Page.Validate();
                if (Page.IsValid) //ALL VALIDATORS VALIDATED FINE
                {
                    AppID = State["application_id"].ToString();

                    if (String.IsNullOrEmpty(AppID) == false)
                    {
                        CGError servererror = new CGError();
                        Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);

                        if (String.Compare(customer_details.Code, AppID, false) == 0)
                            CG_ModifyCustomer();
                        else
                            CG_CreateCustomer(); //Connect to CG and create a new CG customer

                        CGResponseFlag.Text = AppCGCustomerCode;

                    }
                }
                else
                {
                    //Validate Failed.
                    string clickHandler = "this.disabled = false; this.value=\'Submit\'; ";
                    SubmitButton.Attributes.Add("onclick", clickHandler);

                }

            }
        }
        catch (Exception)
        {

            throw;
        }
    }
    protected void RadComboAppSelector_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        BillingUtil billingutil = new BillingUtil();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        try
        {
            if (ApplicationInit(State,RadComboAppSelector,AppID,AppCGCustomerCode) == true)
            {

                //Secondary check with CheddarGettar -to check if this ApplicationID was already used to create a CGCustomer => atleast branding step was done.
                CGError servererror = new CGError();
                Customer native_customer_details = CheddarGetter.GetCustomer(AppID, servererror);
                if (String.Compare(native_customer_details.Code, AppID, false) == 0)
                {
                    USERINFO.Visible = false;
                    RadNotification1.Title = "WARNING";
                    RadNotification1.Text = "This application has already been submitted to the App Store.";
                    RadNotification1.Visible = true;
                    RadNotification1.Show();
                }
                else
                {
                    USERINFO.Visible = true;
                    PageRefresh();
                }
            }
            else
            {
                RadNotification1.Title = "WARNING";
                RadNotification1.Text = "Problem initializing the App.";
                RadNotification1.Visible = true;
                RadNotification1.Show();
                return;
            }
        }
        catch (Exception)
        {

            throw;
        }
    }
    private static void processWebException(System.Net.WebException ex, CGError error)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
            {
                var resp = (HttpWebResponse)ex.Response;
                if (resp.StatusCode == HttpStatusCode.NotFound)
                {
                    error.ID = resp.StatusCode.ToString();
                    error.Code = resp.StatusCode.ToString();
                    error.AuxCode = "";
                    error.Message = resp.StatusDescription;
                }
                else
                {
                    String responseFromServer = ex.Message.ToString() + " ";
                    if (ex.Response != null)
                    {
                        using (WebResponse response = ex.Response)
                        {
                            Stream data = response.GetResponseStream();
                            using (StreamReader reader = new StreamReader(data))
                            {
                                responseFromServer += reader.ReadToEnd();

                                string[] words = responseFromServer.Split(new char[] { '<' }, 2);
                                System.Diagnostics.Debug.WriteLine("\n\n");
                                responseFromServer = "<" + words[1];
                                System.Diagnostics.Debug.WriteLine(responseFromServer);

                                //System.Diagnostics.Debug.WriteLine(responseFromServer);
                                using (XmlReader xmlreader = XmlReader.Create(new StringReader(responseFromServer)))
                                {
                                    XDocument doc = XDocument.Load(xmlreader);
                                    String ID = doc.Element("error").Attribute("id").Value;
                                    String Code = doc.Element("error").Attribute("code").Value;
                                    String AuxCode = doc.Element("error").Attribute("auxCode").Value;
                                    String Message = doc.Element("error").Value;

                                    error.ID = ID;
                                    error.Code = Code;
                                    error.AuxCode = AuxCode;
                                    error.Message = Message;

                                }
                            }
                        }
                    }
                }

            }
    }
    private bool UpdateCheddarGetterPerApp(string AppID)
    {
        try
        {
            CGError servererror = new CGError();
            Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);

            if (String.IsNullOrEmpty(servererror.Code) == false)
            {
                RadNotification1.Title = "WARNING";
                RadNotification1.Text = servererror.Message + " . Please contact [email protected] for assistance";
                RadNotification1.Visible = true;
                RadNotification1.Show();
                return false;
            }

            CustomerPost updateCustomer = new CustomerPost();

            //Copy over the plan since we are not changing that.
            updateCustomer.strPlanCode = customer_details.Subscriptions[0].SubscriptionsPlans[0].Code;

            updateCustomer.Company = CompanyTextBox.Text;
            updateCustomer.FirstName = FirstNameTextBox.Text;
            updateCustomer.LastName = LastNameTextBox.Text;
            updateCustomer.Email = EmailTextBox.Text;

            //Extra fields required for nonFREE plans
            updateCustomer.CCFirstName = CCFirstNameTextbox.Text;
            updateCustomer.CCLastName = CCLastNameTextBox.Text;
            updateCustomer.CCNumber = CCNumberTextBox.Text;
            updateCustomer.CCExpiration = CCExpirationTextBox.Text;
            updateCustomer.CCZip = CCZipTextBox.Text;
            updateCustomer.CCCardCode = CCCardCodeTextBox.Text;

            updateCustomer.Code = AppID;
            System.Diagnostics.Debug.WriteLine("Updating Customerinfo for AppID=" + AppID);

            //Send it to the server
            Customer returnCustomer = CheddarGetter.UpdateCustomerAndSubscription(updateCustomer, servererror);
            //FAILURE
            if (String.IsNullOrEmpty(servererror.Code) == false)
            {
                RadNotification1.Title = "WARNING";
                RadNotification1.Text = servererror.Message + " . Please contact [email protected] for assistance";
                RadNotification1.Visible = true;
                RadNotification1.Show();
                return false;
            }

            //SUCCESS
            if (String.IsNullOrEmpty(returnCustomer.Code) == false)
                return true;

        }

        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
            throw;
        }
        return false;
    }
    private void page_refresh()
    {
        try
        {
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
            HideAllNativeTicks();
            HideAllWebTicks();

            AppID = State["application_id"].ToString();

            if (String.IsNullOrEmpty(AppID) == false)
            {
                CGError servererror = new CGError();
                Customer customer_details = CheddarGetter.GetCustomer(AppID, servererror);

                if (String.IsNullOrEmpty(servererror.Code) == false)
                {
                    USERINFO.Visible = false;
                    RadMultiPageMaster.Visible = false;

                    RadNotification1.Title = "WARNING";

                    if (servererror.Code.IndexOf("NotFound") >= 0)
                        RadNotification1.Text = "No publishing service found for the App";
                    else
                        RadNotification1.Text = servererror.Message;

                    RadNotification1.Visible = true;
                    RadNotification1.Show();

                    return;
                }

                if (customer_details.Subscriptions[0].CanceledDateTime != null)
                {
                    USERINFO.Visible = false;
                    RadMultiPageMaster.Visible = false;

                    RadNotification1.Title = "WARNING";
                    RadNotification1.Text = "Cannot modify a cancelled publishing service. The most recent publishing service for this App was cancelled on " + customer_details.Subscriptions[0].CanceledDateTime.ToString() + ". Please create a new publishing service.";

                    RadNotification1.Visible = true;
                    RadNotification1.Show();

                    return;
                }

                if (String.Compare(customer_details.Code, AppID, false) == 0)
                {
                    CompanyTextBox.Text = customer_details.Company;
                    EmailTextBox.Text = customer_details.Email;
                    FirstNameTextBox.Text = customer_details.FirstName;
                    LastNameTextBox.Text = customer_details.LastName;

                    CCFirstNameTextbox.Text = customer_details.Subscriptions[0].CCFirstName;
                    CCLastNameTextBox.Text = customer_details.Subscriptions[0].CCLastName;
                    CCZipTextBox.Text = customer_details.Subscriptions[0].CCZip;

                }

                AppType = State["SelectedAppType"].ToString();
                AppID = State["application_id"].ToString();
                TickAndSelect_CurrentPlan();
            }

            USERINFO.Visible = true;

            if (State["SelectedAppType"].ToString() == Constants.WEB_APP_TYPE)
            {
                RadMultiPageMaster.Visible = true;
                RadMultiPageMaster.SelectedIndex = 1;
                RadPageNativeSection.Visible = false;
                RadPageWebSection.Visible = true;
                WebPricingMultiPage.SelectedIndex = 0;
                RadTabStrip1.SelectedIndex = 0;
            }
            else
            {
                RadMultiPageMaster.Visible = true;
                RadMultiPageMaster.SelectedIndex = 0;
                RadPageNativeSection.Visible = true;
                RadPageWebSection.Visible = false;
                NativePricingMultiPage.SelectedIndex = 0;
                RadTabStripNative.SelectedIndex = 0;
            }

            PreFillBillingFormDetails();
        }
        catch (Exception)
        {

            throw;
        }
    }