Пример #1
0
        async Task RunAsync(INetUtility netUtil, ILoggerFactory loggerFactory)
        {
            try
            {
                var credential = InstalledAppCredential.ReadFromFile("Path of your json file downloaded from your Google API Console");
                var oauth2Util = new OAuth2Utility(netUtil);
                var tokenInfo  = await oauth2Util.GetTokenInfoAsync(credential, "refreshToken");                // assume you have already obtained your refresh token

                var adWordsApiConfig = new AdWordsApiConfig();
                adWordsApiConfig.AccessToken      = tokenInfo.AccessToken;
                adWordsApiConfig.ClientCustomerId = "Your client customer ID";
                adWordsApiConfig.DeveloperToken   = "Developer token";
                adWordsApiConfig.UserAgent        = "Testing example";          // this and the rest of the properties are optional

                // An example of using some AdWords service
                ICampaignService campaignService = new CampaignService(adWordsApiConfig, netUtil, loggerFactory);                 // loggerFactory can be null
                var selector = new Selector <CampaignServiceField>()
                               .AddFields(CampaignServiceField.Id, CampaignServiceField.Name)
                               .AddPredicate(CampaignServiceField.Status, PredicateOperator.Equals, CampaignStatus.Enabled.ToXmlValue());
                var campaignPage = await campaignService.GetAsync(selector);

                // An example of getting AdWords report
                IReportUtility reportUtil = new ReportUtility(adWordsApiConfig, netUtil, loggerFactory);                 // loggerFactory can be null
                var            rptDef     = new ReportDefinition();
                rptDef.DateRangeType  = ReportDefinitionDateRangeType.AllTime;
                rptDef.DownloadFormat = DownloadFormat.GzippedCsv;
                rptDef.ReportName     = "Testing Report";
                rptDef.ReportType     = ReportDefinitionReportType.CampaignPerformanceReport;
                rptDef.Selector       = new Selector
                {
                    Fields = new List <string>()
                };
                rptDef.Selector.Fields.AddRange(new string[] { "CampaignId", "CampaignName", "Impressions" });
                var reportCsv = await reportUtil.GetContentStringAsync(rptDef);
            }
            catch (Exception ex)
            {
                _logger.LogError("{0}: {1}{2}{3}", ex.GetType().Name, ex.Message, Environment.NewLine, ex.StackTrace);
            }
        }
        public async Task TestGetTokenInfoAsync_ByRefreshToken_Passed()
        {
            var    credential   = new TestCredential();
            string refreshToken = "refreshToken";

            var net      = new DummyNetUtility();
            var response = new DummyHttpWebResponse(HttpStatusCode.OK, @"{
""access_token"": ""accessToken"",
""expires_in"": 123
}");

            net.AddResponse(response);
            var      oauth2     = new OAuth2Utility(net);
            DateTime timeBefore = DateTime.UtcNow;
            var      tokenInfo  = await oauth2.GetTokenInfoAsync(credential, refreshToken);

            DateTime timeAfter = DateTime.UtcNow;

            Assert.Equal("accessToken", tokenInfo.AccessToken);
            Assert.Equal(123, tokenInfo.ExpiresIn);
            Assert.True(timeBefore <= tokenInfo.IssuedTime && tokenInfo.IssuedTime <= timeAfter, $"Expect {timeBefore} <= Issued Time {tokenInfo.IssuedTime} <= {timeAfter}");
        }
        private void ObtainValidAccessToken(TestConfig testConfig)
        {
            lock (_lock)
            {
                if (!IsAccessTokenExpired(testConfig))
                {
                    return;
                }
                var              oauth2Util = new OAuth2Utility(GetNetUtility());
                string           fullPath   = testConfig.GetFilePath(testConfig.Oauth2.CredentialJsonPath);
                OAuth2Credential credential = InstalledAppCredential.ReadFromFile(fullPath);
                if (credential.ProjectId == null)
                {
                    credential = WebAppCredential.ReadFromFile(fullPath);
                }
                var tokenInfo = oauth2Util.GetTokenInfoAsync(credential, testConfig.Oauth2.RefreshToken).Result;

                testConfig.Oauth2.AccessToken = tokenInfo.AccessToken;
                testConfig.Oauth2.ExpiresIn   = tokenInfo.ExpiresIn;
                testConfig.Oauth2.IssuedTime  = tokenInfo.IssuedTime.ToUniversalTime().ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "Z";
                testConfig.Save();
            }
        }