コード例 #1
0
        public void TestAddPlacesLocationExtensionVBExample()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new VBExamples.AddPlacesLocationExtension().Run(user, config.PlacesLoginEmail,
                                                                placesAccessToken);
            });
        }
コード例 #2
0
        public void TestAddShoppingCampaignForShowcaseAdsVBExample()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new VBExamples.AddShoppingCampaignForShowcaseAds().Run(user, budgetId,
                                                                       config.MerchantCenterId);
            });
        }
コード例 #3
0
        public void TestAddShoppingCampaignCSharpExample()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new CSharpExamples.AddShoppingCampaign().Run(user, budgetId, config.MerchantCenterId,
                                                             true);
            });
        }
コード例 #4
0
        public void TestAddGoogleMyBusinessLocationExtensionVBExample()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new VBExamples.AddGoogleMyBusinessLocationExtensions().Run(user, config.GMBLoginEmail,
                                                                           gmbAccessToken, null);
            });
        }
コード例 #5
0
        public void TestAddMultiAssetResponsiveDisplayAdVBExample()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new VBExamples.AddMultiAssetResponsiveDisplayAd().Run(
                    user, displayAdGroupId);
            });
        }
コード例 #6
0
        public ClientReport GetClientReport(string query, string format, bool?returnMoneyInMicros)
        {
            AdWordsAppConfig config      = (AdWordsAppConfig)User.Config;
            string           downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer,
                                                         reportVersion, format);
            string postData = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));

            return(GetClientReportInternal(downloadUrl, postData, returnMoneyInMicros));
        }
コード例 #7
0
        public void TestAddShoppingDynamicRemarketingCampaignVBExample()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new VBExamples.AddShoppingDynamicRemarketingCampaign().Run(
                    user, config.MerchantCenterId, budgetId, userListId);
            });
        }
コード例 #8
0
        public void TestAddAdCustomizersVBExample()
        {
            AdWordsAppConfig config   = (AdWordsAppConfig)user.Config;
            string           feedName = "AdCustomizerFeed" + utils.GetTimeStampAlpha();

            RunExample(delegate() {
                new VBExamples.AddAdCustomizers().Run(user, adGroupId1, adGroupId2, feedName);
            });
        }
コード例 #9
0
        /// <summary>
        /// Configures the AdWords user for OAuth.
        /// </summary>
        private void ConfigureUserForOAuth()
        {
            AdWordsAppConfig config = (user.Config as AdWordsAppConfig);

            if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                string.IsNullOrEmpty(config.OAuth2RefreshToken))
            {
                user.OAuthProvider = (OAuth2ProviderForApplications)Session["OAuthProvider"];
            }
        }
コード例 #10
0
        public ClientReport GetClientReport <T>(T reportDefinition, bool?returnMoneyInMicros)
        {
            AdWordsAppConfig config = (AdWordsAppConfig)User.Config;

            string postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(
                                                                     reportDefinition));
            string downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer,
                                               reportVersion);

            return(GetClientReportInternal(downloadUrl, postBody, returnMoneyInMicros));
        }
コード例 #11
0
        /// <summary>
        /// Downloads a report to disk.
        /// </summary>
        /// <param name="query">The AWQL query for report definition.</param>
        /// <param name="format">The report format.</param>
        /// <param name="path">The path to which report should be downloaded.
        /// </param>
        /// <returns>The client report.</returns>
        public ClientReport DownloadClientReport(string query, string format, string path)
        {
            DeprecationUtilities.ShowDeprecationMessage(this.GetType());

            AdWordsAppConfig config      = (AdWordsAppConfig)User.Config;
            string           downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer,
                                                         reportVersion, format);
            string postData = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));

            return(DownloadClientReportInternal(downloadUrl, postData, path));
        }
コード例 #12
0
        public void Init()
        {
            listener = AdWordsTraceListener.Instance;

            // Set static values for testing.
            AdWordsAppConfig config = (AdWordsAppConfig)listener.Config;

            config.GetType().GetProperty("ClientCustomerId").SetValue(config, TestCustomerId, null);
            config.GetType().GetProperty("MaskCredentials").SetValue(config, true, null);

            ((TraceListener)listener).DateTimeProvider = new MockDateTimeProvider();
        }
コード例 #13
0
        /// <summary>
        /// Downloads a report to disk.
        /// </summary>
        /// <param name="reportDefinition">The report definition.</param>
        /// <param name="path">The path to which report should be downloaded.
        /// </param>
        /// <returns>The client report.</returns>
        public ClientReport DownloadClientReport <T>(T reportDefinition, string path)
        {
            DeprecationUtilities.ShowDeprecationMessage(this.GetType());
            AdWordsAppConfig config = (AdWordsAppConfig)User.Config;

            string postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(
                                                                     reportDefinition));
            string downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer,
                                               reportVersion);

            return(DownloadClientReportInternal(downloadUrl, postBody, path));
        }
コード例 #14
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create an AdWordsAppConfig object with the default settings in
            // App.config.
            AdWordsAppConfig config = new AdWordsAppConfig();

            if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                string.IsNullOrEmpty(config.OAuth2RefreshToken))
            {
                DoAuth2Configuration(config);
            }
        }
        public GADCustomReport Get(GADCustomReportInitializer initializer)
        {
            GCommonCredentialsExtended cred   = (GCommonCredentialsExtended)(new GCommonCredentialManager <GRestUserCredentialReceiver, GRestUserCredentialInitializer>().Get(new GRestUserCredentialInitializer(initializer.Config.CredentialsJsonPath, null)));
            AdWordsAppConfig           config = new AdWordsAppConfig();

            config.DeveloperToken = initializer.Config.DeveloperToken;

            AdWordsUser user = new AdWordsUser(config);

            user.Config.OAuth2RefreshToken = cred.RefreshToken;
            user.Config.OAuth2AccessToken  = cred.AccessToken;
            user.Config.OAuth2ClientId     = cred.ClientId;
            user.Config.OAuth2ClientSecret = cred.ClientSecret;



            config.ClientCustomerId = initializer.Account.Id;
            // Create the required service.

            ReportQuery query = new ReportQueryBuilder()
                                .Select(initializer.Columns.Select(x => x.Value.Name).ToArray())
                                .From(initializer.Type.Name)
                                .During(initializer.DateStart, initializer.DateEnd)
                                .Build();
            ReportUtilities utilities = new ReportUtilities(user, "v201809", query,
                                                            DownloadFormat.XML.ToString());
            string xmlResult;

            using (ReportResponse response = utilities.GetResponse())
            {
                using (var sr = new StreamReader(response.Stream))
                {
                    xmlResult = sr.ReadToEnd();
                }
            }
            XmlSerializer           serializer = new XmlSerializer(typeof(XML201809ReportResponse));
            XML201809ReportResponse xmlReport;

            using (TextReader tr = new StringReader(xmlResult))
            {
                xmlReport = (XML201809ReportResponse)serializer.Deserialize(tr);
            }
            GADCustomReport report = new GADCustomReport(initializer);

            report.Rows = xmlReport.Table.Row.Select(x => new CustomReportRow(
                                                         ((XmlNode[])x)
                                                         .Where(t => initializer.AlterColumns.ContainsKey(t.Name.ToLower()))
                                                         .Select(t => new CustomReportCell(initializer.AlterColumns[t.Name.ToLower()], t.Value)).ToArray()
                                                         )
                                                     ).ToArray();
            return(report);
        }
コード例 #16
0
        /// <summary>
        /// Builds an HTTP request for downloading reports.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <param name="postBody">The POST body.</param>
        /// <returns>A webrequest to download reports.</returns>
        private HttpWebRequest BuildRequest(string downloadUrl, string postBody)
        {
            AdWordsAppConfig config = this.User.Config as AdWordsAppConfig;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(downloadUrl);

            request.Method    = "POST";
            request.Proxy     = config.Proxy;
            request.Timeout   = config.Timeout;
            request.UserAgent = config.GetUserAgent();

            request.Headers.Add("clientCustomerId: " + config.ClientCustomerId);
            request.ContentType = "application/x-www-form-urlencoded";
            if (config.EnableGzipCompression)
            {
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip
                                                                     | DecompressionMethods.Deflate;
            }
            else
            {
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.None;
            }
            if (this.User.OAuthProvider != null)
            {
                request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader();
            }
            else
            {
                throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
            }

            request.Headers.Add("developerToken: " + config.DeveloperToken);
            // The client library will use only apiMode = true.
            request.Headers.Add("apiMode", "true");

            request.Headers.Add("skipReportHeader", config.SkipReportHeader.ToString().ToLower());
            request.Headers.Add("skipReportSummary", config.SkipReportSummary.ToString().ToLower());
            request.Headers.Add("skipColumnHeader", config.SkipColumnHeader.ToString().ToLower());

            // Send the includeZeroImpressions header only if the user explicitly
            // requested it through the config object.
            if (config.IncludeZeroImpressions.HasValue)
            {
                request.Headers.Add("includeZeroImpressions", config.IncludeZeroImpressions.ToString().
                                    ToLower());
            }

            using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) {
                writer.Write(postBody);
            }
            return(request);
        }
コード例 #17
0
        /// <summary>
        /// Builds an HTTP request for downloading reports.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <param name="postBody">The POST body.</param>
        /// <param name="logEntry">The logEntry to write the HTTP logs.</param>
        /// <returns>A webrequest to download reports.</returns>
        private HttpWebRequest BuildRequest(string downloadUrl, string postBody, LogEntry logEntry)
        {
            AdWordsAppConfig config = this.User.Config as AdWordsAppConfig;

            HttpWebRequest request =
                (HttpWebRequest)HttpUtilities.BuildRequest(downloadUrl, "POST", config);

            request.Headers.Add("clientCustomerId: " + config.ClientCustomerId);
            request.ContentType = "application/x-www-form-urlencoded";

            // Set an authorization header only if the authorization mode is OAuth2. For testing
            // purposes, the authorization method will be set to Insecure, and no authorization
            // header will be sent.
            if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2 &&
                this.User.OAuthProvider != null)
            {
                request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader();
            }
            else
            {
                throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
            }

            request.Headers.Add("developerToken: " + config.DeveloperToken);
            // The client library will use only apiMode = true.
            request.Headers.Add("apiMode", "true");

            request.Headers.Add("skipReportHeader", config.SkipReportHeader.ToString().ToLower());
            request.Headers.Add("skipReportSummary", config.SkipReportSummary.ToString().ToLower());
            request.Headers.Add("skipColumnHeader", config.SkipColumnHeader.ToString().ToLower());

            // Send the includeZeroImpressions header only if the user explicitly
            // requested it through the config object.
            if (config.IncludeZeroImpressions.HasValue)
            {
                request.Headers.Add("includeZeroImpressions",
                                    config.IncludeZeroImpressions.ToString().ToLower());
            }

            // Send the useRawEnumValues header only if the user explicitly
            // requested it through the config object.
            if (config.UseRawEnumValues.HasValue)
            {
                request.Headers.Add("useRawEnumValues",
                                    config.UseRawEnumValues.ToString().ToLower());
            }

            HttpUtilities.WritePostBodyAndLog(request, postBody, "reportdownload", logEntry,
                                              HEADERS_TO_MASK);
            return(request);
        }
コード例 #18
0
        public void TestAddGoogleMyBusinessLocationExtensionVBExample()
        {
            // Delete any enabled GMB feeds and their customer feeds, since only one enabled GMB feed
            // is allowed per account.
            utils.DeleteEnabledGmbFeeds(user);
            utils.DeleteEnabledGmbCustomerFeeds(user);

            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            RunExample(delegate() {
                new VBExamples.AddGoogleMyBusinessLocationExtensions().Run(user, config.GMBLoginEmail,
                                                                           gmbAccessToken, null);
            });
        }
コード例 #19
0
        public void Init()
        {
            campaignId = utils.CreateSearchCampaign(user, BiddingStrategyType.MANUAL_CPC);
            adGroupId1 = utils.CreateAdGroup(user, campaignId);
            adGroupId2 = utils.CreateAdGroup(user, campaignId);

            // Load defaults from config file.
            AdWordsAppConfig appConfig = new AdWordsAppConfig();

            appConfig.OAuth2RefreshToken = appConfig.GMBOAuth2RefreshToken;

            AdsOAuthProviderForApplications oAuth2Provider = new OAuth2ProviderForApplications(appConfig);

            oAuth2Provider.RefreshAccessToken();
        }
コード例 #20
0
        /// <summary>
        /// Handles the Click event of the btnAuthorize control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnAuthorizeButtonClick(object sender, EventArgs e)
        {
            // This code example shows how to run an AdWords API web application
            // while incorporating the OAuth2 web application flow into your
            // application. If your application uses a single AdWords manager account
            // login to make calls to all your accounts, you shouldn't use this code
            // example. Instead, you should run OAuthTokenGenerator.exe to generate a
            // refresh token and use that configuration in your website's Web.config.
            AdWordsAppConfig config = user.Config as AdWordsAppConfig;

            if (user.Config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                string.IsNullOrEmpty(config.OAuth2RefreshToken))
            {
                Response.Redirect("OAuthLogin.aspx");
            }
        }
コード例 #21
0
        public void TestSetUserAgent()
        {
            AdWordsAppConfig config = new AdWordsAppConfig();

            Assert.Throws(typeof(ArgumentException), delegate() {
                config.UserAgent = CONTROL_CHARS_USERAGENT;
            });

            Assert.Throws(typeof(ArgumentException), delegate() {
                config.UserAgent = UNICODE_USERAGENT;
            });

            Assert.DoesNotThrow(delegate() {
                config.UserAgent = ASCII_USERAGENT;
            });
        }
コード例 #22
0
        /// <summary>
        /// Gets the seed keywords from a Search Query Report.
        /// </summary>
        /// <param name="user">The user for which reports are run.</param>
        /// <param name="campaignId">ID of the campaign for which we are generating
        ///  keyword ideas.</param>
        /// <returns>A list of seed keywords from SQR, to be used for getting
        /// further keyword ideas.</returns>
        private List <SeedKeyword> GetSeedKeywordsFromQueryReport(AdWordsUser user, long campaignId)
        {
            string query = string.Format("Select Query, MatchTypeWithVariant, Clicks, Impressions " +
                                         "from SEARCH_QUERY_PERFORMANCE_REPORT where CampaignId = {0} during LAST_MONTH",
                                         campaignId);

            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.SkipReportHeader  = true;
            config.SkipReportSummary = true;

            ReportUtilities utilities = new ReportUtilities(user, query, DownloadFormat.CSV.ToString());
            ReportResponse  response  = utilities.GetResponse();

            List <SeedKeyword> retval = new List <SeedKeyword>();

            using (response) {
                byte[] data   = response.Download();
                string report = Encoding.UTF8.GetString(data);

                CsvFile csvFile = new CsvFile();
                csvFile.ReadFromString(report, true);

                foreach (string[] row in csvFile.Records)
                {
                    row[1] = row[1].Replace("(close variant)", "").Trim();
                    SeedKeyword sqrKeyword = new SeedKeyword()
                    {
                        Keyword = new LocalKeyword()
                        {
                            Text      = row[0],
                            MatchType = (KeywordMatchType)Enum.Parse(typeof(KeywordMatchType), row[1], true)
                        },
                        Stat = new Stat()
                        {
                            Clicks      = long.Parse(row[2]),
                            Impressions = long.Parse(row[3])
                        },
                        Source = GetNewKeywords.Source.SQR
                    };
                    retval.Add(sqrKeyword);
                }
            }

            LimitResults(retval, Settings.SQR_MAX_RESULTS);
            return(retval);
        }
コード例 #23
0
        /// <summary>
        /// Builds an HTTP request for downloading reports.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <param name="returnMoneyInMicros">True if money values are returned
        /// in micros.</param>
        /// <param name="postBody">The POST body.</param>
        /// <returns>A webrequest to download reports.</returns>
        private HttpWebRequest BuildRequest(string downloadUrl, bool?returnMoneyInMicros,
                                            string postBody)
        {
            AdWordsAppConfig config = user.Config as AdWordsAppConfig;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(downloadUrl);

            request.Method    = "POST";
            request.Proxy     = config.Proxy;
            request.Timeout   = config.Timeout;
            request.UserAgent = config.GetUserAgent();

            request.Headers.Add("clientCustomerId: " + config.ClientCustomerId);
            request.ContentType = "application/x-www-form-urlencoded";
            if (config.EnableGzipCompression)
            {
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip
                                                                     | DecompressionMethods.Deflate;
            }
            else
            {
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.None;
            }
            if (this.User.OAuthProvider != null)
            {
                request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader();
            }
            else
            {
                throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
            }

            if (returnMoneyInMicros.HasValue)
            {
                ValidateVersionReqirementsForMoneyMicros();
                request.Headers.Add("returnMoneyInMicros: " + returnMoneyInMicros.ToString().ToLower());
            }
            request.Headers.Add("developerToken: " + config.DeveloperToken);
            // The client library will use only apiMode = true.
            request.Headers.Add("apiMode", "true");

            using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) {
                writer.Write(postBody);
            }
            return(request);
        }
コード例 #24
0
        private void Download_Click(object sender, EventArgs e)
        {
            AdWordsAppConfig config = (AdWordsAppConfig)User.Config;

            string QUERY_REPORT_URL_FORMAT = "{0}/api/adwords/reportdownload/{1}?" + "__fmt={2}";

            string reportVersion = "v201302";
            string format        = DownloadFormat.GZIPPED_CSV.ToString();
            string downloadUrl   = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer, reportVersion, format);
            string query         = this.AWQL_textBox.Text;
            string postData      = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));

            ClientReport retval = new ClientReport();

            FeedAttributeType f = new FeedAttributeType();


            ReportsException ex = null;

            this.response.Text += "\n Report download has started...";
            int    maxPollingAttempts = 30 * 60 * 1000 / 30000;
            string path = this.path.Text;

            for (int i = 0; i < 3; i++)
            {
                this.response.Text += "\n Attempt #1...";

                try
                {
                    using (FileStream fs = File.OpenWrite(path))
                    {
                        fs.SetLength(0);
                        bool isSuccess = DownloadReportToStream(downloadUrl, config, true, fs, postData, User);
                        if (!isSuccess)
                        {
                            string errors = File.ReadAllText(path);
                        }
                    }
                }
                catch (Exception exception)
                {
                    this.response.Text = exception.Message;
                }
            }
            this.response.Text += "\n DONE !";
        }
コード例 #25
0
        /// <summary>
        /// Configures the AdWords user for OAuth.
        /// </summary>
        private void ConfigureUserForOAuth()
        {
            AdWordsAppConfig config = (user.Config as AdWordsAppConfig);

            if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2)
            {
                user.OAuthProvider = (OAuth2ProviderForApplications)Session["OAuthProvider"];
                if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
                    string.IsNullOrEmpty(config.OAuth2RefreshToken))
                {
                    user.OAuthProvider = (OAuth2ProviderForApplications)Session["OAuthProvider"];
                }
            }
            else
            {
                throw new Exception("Authorization mode is not OAuth.");
            }
        }
コード例 #26
0
        /// <summary>
        /// Handles the Click event of the btnDownloadReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing
        /// the event data.</param>
        protected void OnDownloadReportButtonClick(object sender, EventArgs e)
        {
            ConfigureUserForOAuth();
            ReportDefinition definition = new ReportDefinition();

            definition.reportName     = "Last 7 days CRITERIA_PERFORMANCE_REPORT";
            definition.reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT;
            definition.downloadFormat = DownloadFormat.GZIPPED_CSV;
            definition.dateRangeType  = ReportDefinitionDateRangeType.LAST_7_DAYS;

            // Create selector.
            Selector selector = new Selector();

            selector.fields = new string[] { "CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
                                             "CriteriaDestinationUrl", "Clicks", "Impressions", "Cost" };

            Predicate predicate = new Predicate();

            predicate.field     = "Status";
            predicate.@operator = PredicateOperator.IN;
            predicate.values    = new string[] { "ACTIVE", "PAUSED" };
            selector.predicates = new Predicate[] { predicate };

            definition.selector = selector;

            // Optional: Include zero impression rows.
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.IncludeZeroImpressions = true;

            string filePath = Path.GetTempFileName();

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201506", definition);
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to download report.", ex);
            }
            Response.AddHeader("content-disposition", "attachment;filename=report.gzip");
            Response.WriteFile(filePath);
            Response.End();
        }
コード例 #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            AdWordsAppConfig config = new AdWordsAppConfig()
            {
                Email            = this.MccEmail.Text,
                Password         = this.MccPassword.Text,
                DeveloperToken   = "5eCsvAOU06Fs4j5qHWKTCA",
                ApplicationToken = "5eCsvAOU06Fs4j5qHWKTCA",
                //ClientEmail = "*****@*****.**",
                UserAgent             = "Edge.BI",
                EnableGzipCompression = true
            };
            AdWordsUser user          = new AdWordsUser(new AdWordsServiceFactory().ReadHeadersFromConfig(config));
            var         reportService = (ReportDefinitionService)user.GetService(AdWordsService.v201101.ReportDefinitionService);

            this.AuthToken.Text        = reportService.RequestHeader.authToken;
            this.DeveloperToken.Text   = reportService.RequestHeader.developerToken;
            this.ApplicationToken.Text = reportService.RequestHeader.applicationToken;
        }
コード例 #28
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="fileName">The file to which the report is downloaded.
        /// </param>
        public void Run(AdWordsUser user, string fileName)
        {
            ReportDefinition definition = new ReportDefinition();

            definition.reportName     = "Last 7 days CRITERIA_PERFORMANCE_REPORT";
            definition.reportType     = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT;
            definition.downloadFormat = DownloadFormat.GZIPPED_CSV;
            definition.dateRangeType  = ReportDefinitionDateRangeType.LAST_7_DAYS;

            // Create selector.
            Selector selector = new Selector();

            selector.fields = new string[] { "CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria",
                                             "FinalUrls", "Clicks", "Impressions", "Cost" };

            Predicate predicate = new Predicate();

            predicate.field     = "Status";
            predicate.@operator = PredicateOperator.IN;
            predicate.values    = new string[] { "ENABLED", "PAUSED" };
            selector.predicates = new Predicate[] { predicate };

            definition.selector = selector;

            // Optional: Include zero impression rows.
            AdWordsAppConfig config = (AdWordsAppConfig)user.Config;

            config.IncludeZeroImpressions = true;

            string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;

            try {
                ReportUtilities utilities = new ReportUtilities(user, "v201506", definition);
                using (ReportResponse response = utilities.GetResponse()) {
                    response.Save(filePath);
                }
                Console.WriteLine("Report was downloaded to '{0}'.", filePath);
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to download report.", ex);
            }
        }
コード例 #29
0
        /// <summary>
        /// Gets the report response.
        /// </summary>
        /// <returns>
        /// The report response.
        /// </returns>
        protected override ReportResponse GetReport()
        {
            AdWordsAppConfig config = (AdWordsAppConfig)User.Config;
            string           postBody;
            string           downloadUrl;

            if (usesQuery)
            {
                downloadUrl = string.Format(QUERY_REPORT_URL_FORMAT, config.AdWordsApiServer,
                                            reportVersion, format);
                postBody = string.Format("__rdquery={0}", HttpUtility.UrlEncode(query));
            }
            else
            {
                downloadUrl = string.Format(ADHOC_REPORT_URL_FORMAT, config.AdWordsApiServer,
                                            reportVersion);
                postBody = "__rdxml=" + HttpUtility.UrlEncode(ConvertDefinitionToXml(
                                                                  reportDefinition));
            }
            return(DownloadReport(downloadUrl, postBody));
        }
コード例 #30
0
        public AdWordsUser GetConfiguration()
        {
            AdWordsUser      user = new AdWordsUser();
            AdWordsAppConfig _configAppReference = new AdWordsAppConfig();

            _configAppReference.DeveloperToken     = _config.DeveloperToken;
            _configAppReference.ClientCustomerId   = _config.ClientCustomerId;
            _configAppReference.OAuth2RefreshToken = _config.OAuth2RefreshToken;
            _configAppReference.OAuth2Scope        = _config.OAuth2Scope;
            _configAppReference.OAuth2AccessToken  = _config.OAuth2AccessToken;

            user = new AdWordsUser(_configAppReference);

            user.Config.OAuth2AccessToken  = _config.OAuth2AccessToken;
            user.Config.OAuth2ClientId     = _config.OAuth2ClientId;
            user.Config.OAuth2ClientSecret = _config.OAuth2ClientSecret;
            user.Config.OAuth2RefreshToken = _config.OAuth2RefreshToken;
            user.Config.OAuth2Scope        = _config.OAuth2Scope;

            return(user);
        }