Esempio n. 1
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="baseCampaignId">Id of the campaign to use as base of the
        /// trial.</param>
        /// <param name="draftId">Id of the draft.</param>
        public void Run(AdWordsUser user, long draftId, long baseCampaignId)
        {
            using (TrialService trialService = (TrialService)user.GetService(
                       AdWordsService.v201710.TrialService))
                using (TrialAsyncErrorService trialAsyncErrorService =
                           (TrialAsyncErrorService)user.GetService(
                               AdWordsService.v201710.TrialAsyncErrorService)) {
                    Trial trial = new Trial()
                    {
                        draftId             = draftId,
                        baseCampaignId      = baseCampaignId,
                        name                = "Test Trial #" + ExampleUtilities.GetRandomString(),
                        trafficSplitPercent = 50
                    };

                    TrialOperation trialOperation = new TrialOperation()
                    {
                        @operator = Operator.ADD,
                        operand   = trial
                    };
                    try {
                        long trialId = trialService.mutate(new TrialOperation[] { trialOperation }).value[0].id;

                        // Since creating a trial is asynchronous, we have to poll it to wait
                        // for it to finish.
                        Selector trialSelector = new Selector()
                        {
                            fields = new string[] {
                                Trial.Fields.Id, Trial.Fields.Status, Trial.Fields.BaseCampaignId,
                                Trial.Fields.TrialCampaignId
                            },
                            predicates = new Predicate[] {
                                Predicate.Equals(Trial.Fields.Id, trialId)
                            }
                        };

                        trial = null;
                        bool isPending    = true;
                        int  pollAttempts = 0;

                        do
                        {
                            int sleepMillis = (int)Math.Pow(2, pollAttempts) *
                                              POLL_INTERVAL_SECONDS_BASE * 1000;
                            Console.WriteLine("Sleeping {0} millis...", sleepMillis);
                            Thread.Sleep(sleepMillis);

                            trial = trialService.get(trialSelector).entries[0];

                            Console.WriteLine("Trial ID {0} has status '{1}'.", trial.id, trial.status);
                            pollAttempts++;
                            isPending = (trial.status == TrialStatus.CREATING);
                        } while (isPending && pollAttempts <= MAX_RETRIES);

                        if (trial.status == TrialStatus.ACTIVE)
                        {
                            // The trial creation was successful.
                            Console.WriteLine("Trial created with ID {0} and trial campaign ID {1}.",
                                              trial.id, trial.trialCampaignId);
                        }
                        else if (trial.status == TrialStatus.CREATION_FAILED)
                        {
                            // The trial creation failed, and errors can be fetched from the
                            // TrialAsyncErrorService.
                            Selector errorsSelector = new Selector()
                            {
                                fields = new string[] {
                                    TrialAsyncError.Fields.TrialId, TrialAsyncError.Fields.AsyncError
                                },
                                predicates = new Predicate[] {
                                    Predicate.Equals(TrialAsyncError.Fields.TrialId, trial.id)
                                }
                            };

                            TrialAsyncErrorPage trialAsyncErrorPage = trialAsyncErrorService.get(errorsSelector);
                            if (trialAsyncErrorPage.entries == null || trialAsyncErrorPage.entries.Length == 0)
                            {
                                Console.WriteLine("Could not retrieve errors for trial {0}.", trial.id);
                            }
                            else
                            {
                                Console.WriteLine("Could not create trial ID {0} for draft ID {1} due to the " +
                                                  "following errors:", trial.id, draftId);
                                int i = 0;
                                foreach (TrialAsyncError error in trialAsyncErrorPage.entries)
                                {
                                    ApiError asyncError = error.asyncError;
                                    Console.WriteLine("Error #{0}: errorType='{1}', errorString='{2}', " +
                                                      "trigger='{3}', fieldPath='{4}'", i++, asyncError.ApiErrorType,
                                                      asyncError.errorString, asyncError.trigger, asyncError.fieldPath);
                                }
                            }
                        }
                        else
                        {
                            // Most likely, the trial is still being created. You can continue
                            // polling, but we have limited the number of attempts in the
                            // example.
                            Console.WriteLine("Timed out waiting to create trial from draft ID {0} with " +
                                              "base campaign ID {1}.", draftId, baseCampaignId);
                        }
                    } catch (Exception e) {
                        throw new System.ApplicationException("Failed to create trial from draft.", e);
                    }
                }
        }
Esempio n. 2
0
        /// <summary>
        /// Creates a test trial for running further tests.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="baseCampaignId">The base campaign ID for the draft.</param>
        /// <param name="draftId">ID of the draft to use when creating trial.</param>
        /// <returns>The trial ID.</returns>
        public long CreateTrial(AdWordsUser user, long draftId, long baseCampaignId)
        {
            // Get the TrialService.
            TrialService trialService = (TrialService)user.GetService(
                AdWordsService.v201605.TrialService);

            Trial trial = new Trial()
            {
                draftId             = draftId,
                baseCampaignId      = baseCampaignId,
                name                = "Test Trial #" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff"),
                trafficSplitPercent = 50
            };

            TrialOperation trialOperation = new TrialOperation()
            {
                @operator = Operator.ADD,
                operand   = trial
            };

            long trialId = trialService.mutate(new TrialOperation[] { trialOperation }).value[0].id;

            // Since creating a trial is asynchronous, we have to poll it to wait
            // for it to finish.
            Selector trialSelector = new Selector()
            {
                fields = new string[] {
                    Trial.Fields.Id, Trial.Fields.Status, Trial.Fields.BaseCampaignId,
                    Trial.Fields.TrialCampaignId
                },
                predicates = new Predicate[] {
                    Predicate.Equals(Trial.Fields.Id, trialId)
                }
            };

            trial = null;
            bool isPending    = true;
            int  pollAttempts = 0;

            do
            {
                int sleepMillis = (int)Math.Pow(2, pollAttempts) *
                                  POLL_INTERVAL_SECONDS_BASE * 1000;
                Console.WriteLine("Sleeping {0} millis...", sleepMillis);
                Thread.Sleep(sleepMillis);

                trial = trialService.get(trialSelector).entries[0];

                Console.WriteLine("Trial ID {0} has status '{1}'.", trial.id, trial.status);
                pollAttempts++;
                isPending = (trial.status == TrialStatus.CREATING);
            } while (isPending && pollAttempts <= MAX_RETRIES);

            if (trial.status == TrialStatus.ACTIVE)
            {
                return(trial.id);
            }
            else
            {
                throw new System.ApplicationException("Failed to create an active trial for testing.");
            }
        }
Esempio n. 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack || OrderID == 0 || (Order = OrderService.GetOrder(OrderID)) == null)
            {
                return;
            }

            var sb = StaticBlockService.GetPagePartByKeyWithCache("OrderSuccessTop");

            if (sb == null || (!CustomerContext.CurrentCustomer.IsAdmin && !sb.Enabled))
            {
                SbOrderSuccessTopText = string.Empty;
            }
            else
            {
                SbOrderSuccessTopId   = sb.StaticBlockId;
                SbOrderSuccessTopText = sb.Content ?? string.Empty;

                SbOrderSuccessTopText = SbOrderSuccessTopText.Replace("#ORDER_ID#", OrderID.ToString());
            }

            if (SettingsOrderConfirmation.SuccessOrderScript.IsNotEmpty())
            {
                string orderScript = SettingsOrderConfirmation.SuccessOrderScript
                                     .Replace("#ORDER_ID#", Order.OrderID.ToString())
                                     .Replace("#ORDER_SUM#", Order.Sum.ToString("#.##"))
                                     .Replace("#CUSTOMER_EMAIL#", HttpUtility.HtmlEncode(Order.OrderCustomer.Email))
                                     .Replace("#CUSTOMER_FIRSTNAME#", HttpUtility.HtmlEncode(Order.OrderCustomer.FirstName))
                                     .Replace("#CUSTOMER_LASTNAME#", HttpUtility.HtmlEncode(Order.OrderCustomer.LastName))
                                     .Replace("#CUSTOMER_PHONE#", HttpUtility.HtmlEncode(Order.OrderCustomer.MobilePhone))
                                     .Replace("#CUSTOMER_ID#", Order.OrderCustomer.CustomerID.ToString());

                var regex    = new Regex("<<(.*)>>");
                var match    = regex.Match(orderScript);
                var products = new StringBuilder();

                if (match.Groups.Count > 0 && match.Groups[1].Value.IsNotEmpty())
                {
                    var productLine = match.Groups[1].Value;
                    foreach (var item in Order.OrderItems)
                    {
                        products.Append(
                            productLine.Replace("#PRODUCT_ARTNO#", HttpUtility.HtmlEncode(item.ArtNo))
                            .Replace("#PRODUCT_NAME#", HttpUtility.HtmlEncode(item.Name))
                            .Replace("#PRODUCT_PRICE#", item.Price.ToString("#.##"))
                            .Replace("#PRODUCT_AMOUNT#", item.Amount.ToString("#.##")));
                    }

                    orderScript = orderScript.Replace("<<" + productLine + ">>", products.ToString());
                }

                lSuccessScript.Text = orderScript;
            }

            LoadGoogleAnalytics(Order);

            if (GoogleTagManager.Enabled)
            {
                TagManager.PageType   = GoogleTagManager.ePageType.purchase;
                TagManager.TotalValue = Order.OrderItems.Sum(item => item.Price * item.Amount);

                TagManager.Transaction = new Transaction()
                {
                    TransactionAffiliation = SettingsMain.ShopName,
                    TransactionId          = Order.OrderID,
                    TransactionTotal       = Order.Sum - Order.ShippingCost,
                    TransactionShipping    = Order.ShippingCost,
                    TransactionProducts    =
                        new List <TransactionProduct>(
                            Order.OrderItems.Select(
                                item =>
                                new TransactionProduct()
                    {
                        Name     = item.Name,
                        Price    = item.Price,
                        Quantity = item.Amount,
                        SKU      = item.ArtNo,
                        Category =
                            CategoryService.GetCategory(
                                ProductService.GetFirstCategoryIdByProductId((int)item.ProductID)).Name
                    }))
                };
            }
            TrialService.TrackEvent(TrialEvents.CheckoutOrder, OrderID.ToString());
        }