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;
            }
    }
    // Modified from original viziapps code with the additional checks so only valid ones are added to the ComboBox.
    private bool InitAppsList(Hashtable State, RadComboBox AppsList)
    {
        Util util = new Util();
        try
        {

            if (AppsList == null)
                return false;

           // string sql = "SELECT DISTINCT application_name FROM applications WHERE customer_id='" + State["CustomerID"].ToString() + "' ORDER BY application_name";

            //Get only native Apps to load onto this ComboBox.
            string sql = "SELECT DISTINCT application_name,application_id FROM applications WHERE customer_id='" + State["CustomerID"].ToString() + "' AND application_type <> 'web'" + " ORDER BY application_name";

            DB db = new DB();
            DataRow[] rows = db.ViziAppsExecuteSql(State, sql);
            AppsList.Items.Clear();
            foreach (DataRow row in rows)
            {
                string app_name = row["application_name"].ToString();
                string application_id = row["application_id"].ToString();

                BillingUtil billingutil = new BillingUtil();

                                                                                                //Inserting only Apps which meet all these criteria.
                if ((billingutil.IsAppStoreSubmissionPaid(State, app_name) == false) &&          // + never submitted for App preparation as yet.
                     (billingutil.IsAppPaid(State, app_name) == false) &&                       // + not yet paid for anything
                     (util.IsFreeProductionValid(State, application_id) == true) &&             // + completed the Production Form Submission
                     (billingutil.IsAppCancelled(State, app_name) == false))                    // + never cancelled any service.
                    {
                      AppsList.Items.Add(new RadComboBoxItem(app_name, app_name));
                    }

            }

            if (AppsList.IsEmpty)
                return false;

            AppsList.Items.Insert(0, new RadComboBoxItem("Select App ->", "Select App ->"));
            AppsList.Items[0].Selected = true;

            return true;
        }
        catch (Exception ex)
        {
            util.ProcessMainExceptions(State, Response, ex);
        }
        return false;
    }
    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;
    }
    private bool ApplicationInit(Hashtable State, RadComboBox AppsList, string AppID, string AppCGCustomerCode)
    {
        Util util = new Util();
        string app = AppsList.SelectedValue;

        if (app.Contains("->"))
            return false;

        State["SelectedApp"] = app;

        State["SelectedAppType"] = util.GetAppType(State);

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

        BillingUtil billingutil = new BillingUtil();
        AppCGCustomerCode = billingutil.getAppPaidSKU(State);

        if (State["SelectedDeviceType"] == null)
        {
            State["SelectedDeviceView"] = State["SelectedDeviceType"] = Constants.IPHONE;
        }

        XmlUtil x_util = new XmlUtil();
        State["SelectedDeviceView"] = State["SelectedDeviceType"] = x_util.GetAppDeviceType(State);

        string username = State["Username"].ToString();
        State["customer_id"] = util.GetCustomerIDFromUsername(State, username);

        return true;
    }
    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;
        }
    }
    protected void RadComboAppSelector_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {
        try
        {
            BillingUtil billingutil = new BillingUtil();
            Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];

            if (ApplicationInit(State, RadComboAppSelector, AppID, AppCGCustomerCode) == true)
                page_refresh();
            else
                showhistory.Visible = false;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + ": " + ex.StackTrace);
        }
    }
    protected void RadComboAppSelector_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
            BillingUtil billingutil = new BillingUtil();
            try
            {

                if (ApplicationInit(State, RadComboAppSelector, AppID, AppCGCustomerCode))
                    page_refresh();
            }
            catch (Exception)
            {

                throw;
            }
    }
    // Modified from original viziapps code with the Additional Branded check so only valid ones are added to the ComboBox.
    private bool InitAppsList(Hashtable State, RadComboBox AppsList)
    {
        Util util = new Util();
        BillingUtil billingutil = new BillingUtil();
        try
        {

            if (AppsList == null)
                return false;

            //string sql = "SELECT DISTINCT application_name FROM applications WHERE customer_id='" + State["CustomerID"].ToString() + "' ORDER BY application_name";
            string sql = "SELECT DISTINCT application_name,application_type FROM applications WHERE customer_id='" + State["CustomerID"].ToString() + "' ORDER BY application_name";
            DB db = new DB();
            DataRow[] rows = db.ViziAppsExecuteSql(State, sql);
            AppsList.Items.Clear();
            foreach (DataRow row in rows)
            {
            string app_name = row["application_name"].ToString();
            string app_type = row["application_type"].ToString();

                //For native-hybrid apps do the branded check here inserting only Apps that have paid for branding.
            if (app_type.Contains("native") || app_type.Contains("hybrid"))
            {

                //Inserting only Apps which meet all these criteria.
                if ((billingutil.IsAppStoreSubmissionPaid(State, app_name) == true) &&          // + Submitted for App preparation.
                     (billingutil.IsAppPaid(State, app_name) == false))                       // + not yet paid for any service
                {
                    AppsList.Items.Add(new RadComboBoxItem(app_name, app_name));
                }
            }
            else
            {
                //Inserting only Apps which meet all these criteria.
                if (billingutil.IsAppPaid(State, app_name) == false)                            // not yet paid for any service
                    AppsList.Items.Add(new RadComboBoxItem(app_name, app_name));
            }

            }

            if (AppsList.IsEmpty)
                return false;

            AppsList.Items.Insert(0, new RadComboBoxItem("Select App ->", "Select App ->"));
            AppsList.Items[0].Selected = true;

            return true;
        }
        catch (Exception ex)
        {
            util.ProcessMainExceptions(State, Response, ex);
        }

        return false;
    }
    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 RadComboAppSelector_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        BillingUtil billingutil = new BillingUtil();
        try
        {

           if (ApplicationInit(State,RadComboAppSelector,AppID,AppCGCustomerCode))
               page_refresh();
            else
            {
                RadNotification1.Title = "WARNING";
                RadNotification1.Text = "Problem initializing the App.";
                RadNotification1.Visible = true;
                RadNotification1.Show();
                return;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }